服务端:
import socket
import subprocess
import json
import struct
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(('192.168.43.177',8095))
server.listen(5)
while True:
conn,client_addr = server.accept()
while True:
try:
cmd = conn.recv(8096)
if not cmd :break
#数据解析
obj = subprocess.Popen(cmd.decode('utf-8'),shell=True,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
stdout = obj.stdout.read()
stderr = obj.stderr.read()
total_size = len(stdout)+len(stderr)
header = {'filename':'djaidj',
'total_size':total_size
}
header_json = json.dumps(header)
header_bytes = header_json.encode('utf-8')
conn.send(struct.pack('i',len(header_bytes)))
conn.send(header_bytes)
conn.send(stdout)
conn.send(stderr)
except ConnectionResetError:
break
conn.close()
server.close()
客户端
import socket
import subprocess
import json
import struct
client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect(('192.168.43.177',8095))
while True:
cmd = input('>>:').strip()
if not cmd:continue
client.send(cmd.encode('utf-8'))
obj = client.recv(4)
header_size = struct.unpack('i',obj)[0]
header_bytes = client.recv(header_size)
header_json = header_bytes.decode('utf-8')
header = json.loads(header_json)
total_size = header['total_size']
recv_data = b''
recv_size = 0
while recv_size < total_size:
res = client.recv(1024)
recv_data += res
recv_size += len(res)
print(recv_data.decode('gbk'))
client.close()