socket_server_ssh.py编码如下:
import socket,os
server=socket.socket()
server.bind(("localhost",9999))
server.listen()
while True:
---conn,addr=server.accept() #等电话
---print("new connet。。。",addr)
---while True:
---print("等待新指令....")
---data=conn.recv(1024)
---if not data:
------print("客户端已断开")
------break
---cmd_res=os.popen(data.decode()).read() #接受字符串,执行结果也是字符串
---if len(cmd_res)==0:
------print("cmd_res has not output。。。")
---conn.send((str(len(cmd_res.encode())).encode("utf-8"))
---conn.send(cmd_res.encode("utf-8"))
server.close()
socket_server_client.py编码如下:
import socket
client=socket.socket()
client.connect(("localhost",9999))
while True:
---data=input("请输入指令:").strip()
---if len(data)==0:
------continue
---client.send(data.encode("utf-8"))
---cmd_res_size=client.recv(1024) #先接受大小
---recevied_size=0
---recevied_data=b''
---while recevide_size<int(len(cmd_res_size.decode())):
------data=client.recv(1024)
------recevied_size+=len(data) #每次接收的大小不一样,所以需要用len判断一下
------recevied_data+=data
---else:
------print("cmd_res has recevied done......")
------print(recevied_data.decode())
client.close()