服务端
##sock_server_ssh import socket,os server = socket.socket() server.bind(('localhost',9999)) server.listen() while True: print("接收新指令") 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()).read()#接受字符串,执行结果也是字符串 print("before send",len(cmd_res)) if len(cmd_res) == 0: cmd_res = "cmd has no output..." conn.send(str(len(cmd_res)).encode("utf-8"))#先发大小给客户端 conn.send(cmd_res.encode("utf-8")) print("send done") server.close()
客户端
1 ##socket_server_client 2 3 import socket 4 client = socket.socket() 5 client.connect(("localhost",9999)) 6 7 while True: 8 cmd = input(">>:").strip() 9 if len(cmd) ==0:continue 10 client.send(cmd.encode('UTF-8')) 11 cmd_res_size = client.recv(1024)#接收命令结果的长度 12 print("命令结果大小:",cmd_res_size) 13 received_size = 0 14 #received_data = b'' 15 while received_size < int(cmd_res_size.decode()) : 16 17 data = client.recv(1024) 18 received_size += len(data)#每次收到的有可能小于1024,所以必须用len判断 19 #print(data.decode()) 20 print(received_size) 21 else: 22 print("cmd res receive done...",received_size) 23 24 #cmd_res = client.recv(1024) 25 26 #print(cmd_res) 27 28 client.close()