day 30 客户端获取cmd 命令的步骤

时间:2024-08-24 15:06:26
import subprocess
import struct
import json
from socket import *
server=socket(AF_INET,SOCK_STREAM)
server.bind(('127.0.0.1',8099))
# print(server)
server.listen(5)
while True:
conn,addr=server.accept()
print(conn)
print(addr)
while True:
try:
cmd=conn.recv(8096)
if not cmd:break #针对linux #执行命令
cmd=cmd.decode('utf-8')
#调用模块,执行命令,并且收集命令的执行结果,而不是打印
obj = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout=obj.stdout.read()
stderr=obj.stderr.read() # 1:先制作报头,报头里放:数据大小, md5, 文件
header_dic = {
'total_size':len(stdout)+len(stderr),
'md5': 'xxxxxxxxxxxxxxxxxxx',
'filename': 'xxxxx',
'xxxxx':'123123'
}
header_json = json.dumps(header_dic)
header_bytes = header_json.encode('utf-8')
header_size = struct.pack('i', len(header_bytes))
#字典的此长度(报头的长度)
# 2: 先发报头的长度
conn.send(header_size) # 3:先发报头
conn.send(header_bytes) # 4:再发送真实数据
conn.send(stdout)
conn.send(stderr)
except ConnectionResetError:
break
conn.close() server.close() -----------
import struct
import json
from socket import * client=socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8099)) while True:
cmd=input('>>: ').strip()
if not cmd:continue
client.send(cmd.encode('utf-8'))
# 1:先收报头长度
obj = client.recv(4)
header_size = struct.unpack('i', obj)[0]
# 2:先收报头,解出报头内容
header_bytes = client.recv(header_size)
header_json = header_bytes.decode('utf-8')
header_dic = json.loads(header_json)
print(header_dic)
total_size = header_dic['total_size']
# 3:循环收完整数据
recv_size=0
res=b''
while recv_size < total_size:
recv_data=client.recv(1024)
res+=recv_data
recv_size+=len(recv_data)
print(res.decode('gbk'))
client.close()