#Author Kang
import os
import subprocess
import socket
server = socket.socket()
server.bind(('localhost',9999))
server.listen()
print("等待客户端连接:>>>>")
while True:
conn,addr = server.accept()
print("接受了一个新的链接!!")
while True:
data = conn.recv(1024)
cmd = subprocess.getstatusoutput(data.decode())
print("执行命令:>>",cmd)
res_size = str(len(cmd[1].encode("utf-8")))
print(res_size)
if len(cmd[1]) != 0:
conn.send(res_size.encode("utf-8"))
ack = conn.recv(1024) #解决SOCKET粘包的问题,即发送命令结果大小与命令结果同时发送
conn.send(cmd[1].encode("utf-8"))
elif cmd[0] == 0 and len(cmd[1]) == 0:
res = '命令执行成功,但没有返回值'
conn.send(res_size.encode("utf-8"))
ack = conn.recv(1024) # 解决SOCKET粘包的问题
conn.send(res.encode("utf-8"))
if len(data) == 0:
break
server.close()
客户端代码
#Author Kang
import socket
client = socket.socket()
client.connect(('localhost',9999))
while True:
msg = input("请输入你要传递的信息:>>>>>")
if len(msg) == 0:
continue
client.send(msg.encode("utf-8")) #发送命令给服务器端
cmd_size = client.recv(1024) #接受服务器返回结果的长度
print("接受结果的大小为:",cmd_size.decode())
recv_size = 0
res_data = ""
client.send("我已经可以可以接受了".encode("utf-8")) #为了解决粘包的问题,返回我已经接送命令返回的大小,开始接受结果
while recv_size < int(cmd_size): #判断当前接受的大小与服务器执行命令大小,如小于继续接受
data = client.recv(1024)
recv_size += len(data)
res_data += data.decode()
else:
print(res_data)
client.close()
本文标题:Python之SSH实例(解决SOCKET粘包与大数据返回的问题)
分享链接:
http://kswsj.cn/article/gsdpji.html