from socket import *
import subprocess
ip_port = ('127.0.0.1', 8080)
back_log = 5
buffer_size = 1024
tcp_server = socket(AF_INET, SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(back_log)
while True:
conn, addr = tcp_server.accept()
while True:
try:
cmd = conn.recv(buffer_size)
if not cmd: break
cmd = cmd.decode('utf-8')
print('收到客户端命令', cmd)
res = subprocess.Popen(cmd, shell=True,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE
)
err = res.stderr.read()
if err:
cmd_res = err
else:
cmd_res = res.stdout.read()
if not cmd_res:
cmd_res = '该命令没有返回结果'.encode('gbk')
conn.send(cmd_res)
except Exception:
break
conn.close()
tcp_server.close()
客户端:
from socket import *
ip_port = ('127.0.0.1', 8080)
tcp_client = socket(AF_INET, SOCK_STREAM)
tcp_client.connect(ip_port)
while True:
cmd = input('请输入命令').strip()
if not cmd: continue
if cmd == 'quit': break
cmd = cmd.encode('utf-8')
tcp_client.send(cmd)
cmd_res = tcp_client.recv(1024)
print('命令执行的结果是', cmd_res.decode('gbk'))