主要依赖的是 subprocess模块
Server端:
import socket
import subprocess
sk = socket.socket()
sk.bind(("127.0.0.1",10050))
sk.listen()
conn,addr = sk.accept()
while True:
if getattr(conn,'_closed'):
conn, addr = sk.accept()
# 获取接收到的命令
exec_cmd = conn.recv(1024)
cmd = exec_cmd.decode("utf-8")
if cmd=="bye":
conn.close()
continue
ret = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
stdout_bytes = ret.stdout.read()
stderr_bytes = ret.stderr.read()
if stdout_bytes:
conn.send(stdout_bytes)
else:
conn.send(stderr_bytes)
#conn.close()
sk.close()
Client端
import socket
sk = socket.socket()
sk.connect_ex(("127.0.0.1",10050))
while True:
cmd_str = input(">>>")
sk.send(cmd_str.encode("utf-8"))
if cmd_str=="bye":
break
ret = sk.recv(4096)
ret_str = ret.decode("gbk")
print(ret_str)
sk.close()