1. 程式人生 > >TCP 遠端執行CMD (解決粘包問題) 程式碼

TCP 遠端執行CMD (解決粘包問題) 程式碼

服務端

 1 from socket import *
 2 import subprocess,json,struct
 3 
 4 server= socket(AF_INET,SOCK_STREAM)
 5 server.bind(('127.0.0.1',8081))
 6 server.listen(5)
 7 
 8 while True:
 9     client,client_addr=server.accept()
10     while True:
11         try:
12             cmd=client.recv(1024).decode('utf-8
') 13 if not cmd:break 14 # 執行命令 15 obj=subprocess.Popen(cmd, 16 shell=True, 17 stdout=subprocess.PIPE, 18 stderr=subprocess.PIPE 19 )
20 # 顯示正確和錯誤資訊 21 stdout=obj.stdout.read() 22 stderr=obj.stderr.read() 23 print('執行結果長為%s' %(len(stdout)+len(stderr))) 24 # 制定報頭 25 head_dic={'filename':'a.txt', 26 'md5':'rdgdgfdgfdgd', 27 '
size':len(stdout)+len(stderr) 28 } 29 head_json=json.dumps(head_dic) 30 head_bytes=head_json.encode('utf-8') 31 # 傳送報頭長度 32 head_len=len(head_bytes) 33 head_len_bytes = struct.pack('i', head_len) 34 client.send(head_len_bytes) 35 # 傳送報頭 36 client.send(head_bytes) 37 # 傳送真實資料 38 client.send(stdout) 39 client.send(stderr) 40 except ConnectionResetError: 41 print('客戶端異常關閉') 42 break 43 client.close() 44 45 server.close()

 

客戶端

 1 from socket import *
 2 import json,struct
 3 
 4 client= socket(AF_INET,SOCK_STREAM)
 5 client.connect(('127.0.0.1',8081))
 6 
 7 while True:
 8     cmd=input('>>>').strip()
 9     if not cmd:continue
10     client.send(cmd.encode('utf-8'))
11     # 先接受報頭長度
12     head_len=struct.unpack('i',client.recv(4))[0]
13     # 接收報頭
14     head_bytes=client.recv(head_len)
15     # 解析報頭
16     head_json=head_bytes.decode('utf-8')
17     head_dic=json.loads(head_json)
18     print(head_json)
19     total_size=head_dic['size']
20     # 取出真實資料
21     recv_size=0
22     finnally_data=b''
23     while total_size>recv_size:
24         recv_data=client.recv(1024)
25         finnally_data+=recv_data
26         recv_size+=len(recv_data)
27     print(finnally_data.decode('gbk'))
28 
29 client.close()