第四版 远程命令标准版

server

#服务端

#服务端
import socket
import struct
import json
import subprocess

phone = socket.socket()
phone.bind(('127.0.0.1',8848))
print('服务器启动成功!等待连接。。。')
phone.listen(5)
while 1:
conn, addr = phone.accept()
print(f'{addr}连接成功。。。')
while 1:
try:
data = conn.recv(1024)
if data.upper() == b'Q':
print('客户端退出程序!')
break
obj = subprocess.Popen(data.decode('utf-8'),
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,

)
form_obj = obj.stdout.read() +obj.stderr.read()
len_obj = len(form_obj)
dic = {

'file_name': 'test1',
'md5': 6567657678678,
'total_size': len_obj,
}

json_dic = json.dumps(dic)
json_dic_bytes = json_dic.encode('utf-8')
len_json_dic_bytes = len(json_dic_bytes)

len_json_dic_bytes_form = struct.pack('i',len_json_dic_bytes)

conn.send(len_json_dic_bytes_form)
conn.send(json_dic_bytes)
conn.send(form_obj)

except ConnectionError:
print('客户端异常断开连接......')
break

conn.close()
phone.close()


#客户端
client
import socket
import json
import struct

phone = socket.socket()
phone.connect(('127.0.0.1',8848))
print('与服务器连接成功。。。')
print('退出程序请输入:Q/q')
while 1:
data = input(">>>:").strip().encode('utf-8')
if not data:
print('输入的内容不能为空!')
continue
phone.send(data)
if data.upper() == b'Q':
print('退出程序!')
break

total_size = phone.recv(4)
json_total_size = struct.unpack('i',total_size)[0]

dic_json_bytes = phone.recv(json_total_size)
dic_json = dic_json_bytes.decode('utf-8')
dic = json.loads(dic_json)

total_data = b''
while len(total_data) < dic['total_size']:
total_data += phone.recv(1024)

print(total_data.decode('gbk'))
phone.close()
posted @ 2021-12-02 14:34  新时代的潜行者  阅读(30)  评论(0)    收藏  举报