python远程执行命令

1. 使用os模块远程执行命令

服务端代码

 1 import socket
 2 import os
 3 
 4 sh_server = socket.socket()  #创建一个socket对象
 5 sh_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  #重置IP和端口
 6 sh_server.bind(('127.0.0.1',8001))  #绑定服务器IP和端口
 7 sh_server.listen(5)  #设置最大监听数
 8 
 9 while True: #链接循环
10     conn,addr = sh_server.accept()  #阻塞,等待客户端过来链接
11 
12     while True: #通信循环
13     # 接收客户端发送过来的消息
14     cmd = conn.recv(buffer_size).decode('utf-8')
15     #使用os模块中的popen远程执行命令
16     data = os.popen(cmd)
17     res_msg=data.read()
18     #执行结果发送给客户端
19     conn.send(res_msg.encode('gbk'))
20     print(res_msg)
21     print(len(res_msg))
22 conn.close()
23     

客户端代码

 1 import socket
 2 
 3 sh_client = socket.socket() #创建socket对象
 4 sh_client.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
 5 
 6 sh_client.connect(('127.0.0.1',8001))  #链接服务端
 7 
 8 while True: #通信循环
 9     cmd = input("请输入要执行的命令:")
10     if cmd == '': continue
11     if cmd =='exit' or cmd =='quit':break
12     sh_client.send(cmd.encode('utf-8'))
13     res_info = sh_client.recv(1024).decode('gbk')
14     print('命令执行结果是:',res_info)
15 sh_client.close()

 

2. 使用subprocess模块执行远程命令

服务端代码

 1 import socket
 2 import subprocess
 3 
 4 sh_server = socket.socket()
 5 sh_server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)  #重置IP和端口
 6 sh_server.bind(('127.0.0.1',8001))
 7 sh_server.listen(5)
 8 
 9 while True: #链接循环
10     conn,addr = sh_server.accept()  #阻塞,等待客户端过来链接
11     print('客户端信息',conn,addr)
12 
13     while True: #通信循环
14         # 接收客户端发送过来的消息
15         print('----------接收命令')
16         cmd = conn.recv(buffer_size).decode('utf-8')
17         print('要执行的命令是:',cmd)
18         if cmd == 'exit' or cmd == 'quit':break
19         #使用subprocess模块执行远程命令
20         ret = subprocess.Popen(cmd,shell=True,
21                                stdout = subprocess.PIPE,
22                                stderr = subprocess.PIPE,
23                                stdin = subprocess.PIPE)
24 
25         err = ret.stderr.read()
26         if err:
27             ret_msg = err
28         else:
29             ret_msg = ret.stdout.read()
30         if not ret_msg:
31             ret_msg = "命令执行成功".encode('gbk')
32         print('---------命令执行完成')
33         conn.send(ret_msg)
34     
35     conn.close()

客户端代码

 1 import socket
 2 
 3 sh_client = socket.socket()
 4 sh_client.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
 5 
 6 sh_client.connect(('127.0.0.1',8001))
 7 
 8 while True: #通信循环
 9     cmd = input("请输入要执行的命令:")
10     if cmd == '': continue
11     if cmd =='exit' or cmd =='quit':break
12     sh_client.send(cmd.encode('utf-8'))
13     res_info = sh_client.recv(1024).decode('gbk')
14     print('命令执行结果是:',res_info)
15 sh_client.close()

 

posted @ 2020-03-16 11:12  wuchenhu  阅读(416)  评论(0编辑  收藏  举报