server 端
import socket import subprocess import struct import json server = socket.socket() server.bind(("127.0.0.1",8080)) server.listen(5) while True: conn, addr = server.accept() print(addr) while True: try: cmd = conn.recv(1024) obj = subprocess.Popen(cmd.decode(), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout = obj.stdout.read() stderr = obj.stderr.read() header_dic = { "total_size":len(stdout) + len(stderr), "md5" : "password", "filename" : "a.txt" } header_json = json.dumps(header_dic) header_bytes = header_json.encode("utf-8") header_size = len(header_bytes) header = struct.pack("i", header_size) conn.send(header) conn.send(header_bytes) conn.send(stdout+stderr) except ConnectionResetError: break conn.close() server.close()
client 端
import json import struct from socket import * client = socket(AF_INET,SOCK_STREAM) client.connect(('127.0.0.1',8080)) while True: cmd = input(">>:").strip() if not cmd : continue client.send(cmd.encode()) header_size = struct.unpack("i",client.recv(4))[0] header_bytes = client.recv(header_size) header_json = header_bytes.decode() header_dic = json.loads(header_json) total_size = header_dic["total_size"] recv_size = 0 res = b"" while recv_size < total_size: recv_data = client.recv(1024) res += recv_data recv_size += len(recv_data) print(res.decode("gbk")) client.close()
cmd:
dir | ipconfig