0903编写ssh实现远程执行命令 并解决粘包问题
粘包问题的来源:
粘包问题的根源源于tcp协议是一种流的协议,在使用该协议进行通信时会应为tcp流的形式而没能分辨什么是每一个文件,从而会使文件粘在一起,这就是粘包问题
解决粘包问题的思路:
在接收每一包是自设定报头,从而区分每一个文件,并且在接收文件时将每一个文件都接收干净
用代码实现ssh远程执行命令,并且解决粘包问题
服务端代码:
from socket import * import subprocess import struct import json phone = socket(AF_INET , SOCK_STREAM) phone.bind(('127.0.0.1',8081)) phone.listen(5) while True: conn,adr = phone.accept() while True: try: msg = conn.recv(1024).decode('utf-8') res = subprocess.Popen(msg,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) stdout = res.stdout.read() stderr = res.stderr.read() header_dic = { 'file_name':'a.txt', 'md5':'adsfaf', 'total_size':len(stdout)+len(stderr) } header_dic_json = json.dumps(header_dic) header_dic_b = header_dic_json.encode('utf-8') header = struct.pack('i',len(header_dic_b)) conn.send(header) conn.send(header_dic_b) conn.send(stdout) conn.send(stderr) except Exception: break conn.close()
客户端代码:
import struct from socket import * import json phone = socket(AF_INET,SOCK_STREAM) phone.connect(('127.0.0.1',8081)) while True: msg = input('>>>>>:').strip() if not msg : continue if msg == 'q': break phone.send(msg.encode('utf-8')) header = phone.recv(4) header_dic_l = struct.unpack('i',header)[0] header_dic_json = phone.recv(header_dic_l).decode('utf-8') header_dic = json.loads(header_dic_json) total_size = header_dic['total_size'] recv_size = 0 total_msg = b'' while recv_size < total_size: msg = phone.recv(1024) recv_size +=len(msg) total_msg +=msg print(total_msg.decode('gbk')) phone.close()