python ssh小程序
时间:2020-10-08 19:49:49
收藏:0
阅读:44
client.py
import socket import os import struct import json if os.name == ‘nt‘: code = ‘gbk‘ elif os.name == ‘posix‘: code = ‘utf-8‘ client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client.connect((‘127.0.0.1‘,8080)) while 1: msg = input(‘content:‘).strip() if not msg: continue client.send(msg.encode(code)) #获取header长度 header_lenth = client.recv(4) print(‘*********‘,header_lenth) header_lenth = struct.unpack(‘i‘,header_lenth)[0] #获取header header = client.recv(header_lenth) # header = struct.unpack(‘i‘,header)[0] #信息长度 data_lenth = json.loads(header.decode(code))[‘lenth‘] print(data_lenth) data_recv_lenth = 0 data_recv = b‘‘ while data_recv_lenth < data_lenth: data = client.recv(1024) data_recv += data data_recv_lenth += len(data_recv) print(data_recv.decode(code),len(data_recv.decode(code))) client.close()
server.py
import socket import subprocess import os import struct import json if os.name == ‘nt‘: code = ‘gbk‘ elif os.name == ‘posix‘: code = ‘utf-8‘ #定义socket类型为 Ipv4 tcp server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #设定socket可重用ip server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #绑定IP、端口 server.bind((‘127.0.0.1‘,8080)) #监听连接数 server.listen(5) while 1: #等待连接 conn,client_addr = server.accept() print(client_addr) while 1: try: #接收到的信息 data = conn.recv(1024) if not data: continue print(data) #执行获取到的命令,注意命令需是非bytes类型,接收到的bytes类型数据需要解码 obj = subprocess.Popen(data.decode(code),shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE) stderr = obj.stderr.read() stdout = obj.stdout.read() data = stderr+stdout #制作报头 header_dict = { ‘filename‘:‘a.txt‘, ‘md5‘:‘aaaaaaaaaaaaaa‘, ‘lenth‘:len(data) } header = json.dumps(header_dict).encode(code) # data_lenth = struct.pack(‘i‘,len(data)) header_lenth = struct.pack(‘i‘,len(header)) #发送header长度 conn.send(header_lenth) #发送header conn.send(header) #返回信息 conn.send(data) except ConnectionResetError: break conn.close() server.close()
评论(0)