TCP服务端
import struct
import subprocess
from socket import *
from threading import Thread
from multiprocessing import Process
def communication(conn):
while True:
try:
data_bytes = conn.recv(1024)
if not data_bytes:
break
obj = subprocess.Popen(
data_bytes.decode('utf-8'),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = obj.stdout.read(), obj.stderr.read()
total_size = len(stdout) + len(stderr)
# 定制报头
header_bytes = struct.pack('i', total_size)
conn.send(header_bytes)
# 发送数据
conn.send(stdout)
conn.send(stderr)
except ConnectionResetError as e:
print(e)
break
conn.close()
if __name__ == '__main__':
server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1', 8080))
server.listen(5)
while True:
conn, client_address = server.accept()
print("连接客户端:", client_address)
# t = Thread(target=communication, args=(conn,))
# t.start()
p = Process(target=communication, args=(conn,))
p.start()
server.close()
TCP客户端
import struct
from socket import *
client = socket()
client.connect(('127.0.0.1', 8080))
while True:
cmd = input('输入CMD命令>>: ').strip()
if not cmd:
continue
client.send(cmd.encode('utf-8'))
# 解包
header_bytes = client.recv(4)
header_length = struct.unpack('i', header_bytes)[0]
# 循环接收并打印数据
recv_size = 0
while recv_size < header_length:
data_bytes = client.recv(1024)
recv_size += len(data_bytes)
print(data_bytes.decode('gbk'), end='')
print()