用subprocess(子进程)模块完成远程cmd操作
# 客户端
import socket
client = socket.socket()
client.connect(('127.0.0.1',8889))
while True:
cmd = input('请发送命令:').strip()
if len(cmd) == 0:
continue
if cmd == 'q':
client.send(b'q')
break
cmd = cmd.encode('utf-8')
client.send(cmd)
byte_data = client.recv(1024)
print(byte_data.decode('gbk'))
# 服务端 import socket import subprocess server = socket.socket() server.bind(('127.0.0.1',8889)) server.listen(5) while True: conn,addr = server.accept() while True: try: cmd = conn.recv(1024) if len(cmd) == 0: continue cmd = cmd.decode('utf-8') if cmd == 'q':break obj = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # 这里cmd必须是字符串类型,不是bytes类型的字符串 print(obj) # <subprocess.Popen object at 0x00000000029C6D30> 对象 # print(obj.stdout.read()) # b'' 没赋值变量名返回的是空 success = obj.stdout.read() # 必须赋值一个变量才有值 # print(success) # 返回的是二进制,可以直接基于网络传输 # print(obj.stderr.read()) # b'' 没赋值变量名返回的是空 error = obj.stderr.read() # print(error) # 返回不正确命令的报错信息 if success: conn.send(success) else: conn.send(error) except Exception as e: # 捕获客服端人为断开连接,不至于服务端报错率而断开,毕竟服务端是24h不间断服务的 print(e) break conn.close()