Python中使用subprocess模块远程执行命令
使用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()