1.服务端
import socket, os
server = socket.socket()
server.bind(('localhost',22222))
server.listen()
while True:
conn, addr = server.accept()
print("new conn:", addr)
while True:
data = conn.recv(1024)
if not data:
print("客户端已断开")
break
print("执行指令", data)
cmd_res = os.popen(data.decode("utf-8")).read()
if len(cmd_res) == 0:
cmd_res = 'cmd has no output...'
conn.send(str(len(cmd_res)).encode("utf-8"))
client_ack = conn.recv(1024)#避免socket粘包 也可time.sleep(0.5)
conn.send(cmd_res.encode("utf-8"))
server.close()
2.客户端
import socket标签:received,utf,socket,res,cmd,粘包,ssh,data From: https://www.cnblogs.com/circlecircle/p/18468558
client = socket.socket()
client.connect(('localhost', 22222))
while True:
cmd = input(">>:").strip()
if len(cmd) == 0: continue
client.send(cmd.encode("utf-8"))
cmd_res_size = client.recv(1024) #接受命令结果的长度
client.send("可以接收数据了".encode("utf-8"))
received_size = 0
received_data = b''
while received_size < int(cmd_res_size.decode("utf-8")):
data = cmd_res = client.recv(1024)
received_size += len(data)
#print(data.decode("utf-8"))
received_data += data
else:
print("cmd res receive done...", received_size)
print(received_data.decode("utf-8"))
client.close()