#服务端 import socket import os import subprocess phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print('进行绑定,监听') phone.bind(('127.0.0.1', 8080)) phone.listen(5) def cmd(cmdlist): obj=subprocess.Popen( cmdlist, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout_res=obj.stdout.read() stderr_res=obj.stderr.read() return stdout_res+stderr_res#假如不写成方法,这里可以分成两次发送过去,更加节省内存 while True: conn, add = phone.accept() print('建立连接') while True: try: msg = conn.recv(1024) if not len(msg): break print('执行命令') print(msg) #os.system(msg.decode(encoding='utf-8')) stdout_res=cmd(msg.decode(encoding='utf-8')) print('发送消息') conn.send(stdout_res) except Exception: break conn.close() phone.close() #客户端
import socket st = socket.socket(socket.AF_INET, socket.SOCK_STREAM) st.connect(('127.0.0.1', 8080)) while True: msg=input('请输入cmd 命令').strip() print('发送消息') if not len(msg):continue st.send(msg.encode(encoding='utf-8')) data=st.recv(1024) print(data.decode('gbk')) st.close() #服务端
# import socketserver # # # class Myhandler(socketserver.BaseRequestHandler): # def Hadler(self): # print('连接建立成功') # while True: # try: # data = self.request.recv(1024) # if not len(data): break # self.request.send(data) # # except ConnectionResetError: # break # # self.request.close() # # # if __name__ == '__main__': # print('开始启动') # st = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), Myhandler, bind_and_activate=True) # print('开始建立连接') # st.serve_forever() # 提供无限循环,循环建立链接 # # 每建立链接,就会启动一个线程,专门与刚刚 # # 建立好的链接做通信循环 # # 调用myhandler类产生一个对象,条用该对象下的handler方法,专门与刚刚建立好的 # # 连接做通信循环 import socketserver import json import struct import subprocess import os class MyHandler(socketserver.BaseRequestHandler): def handle(self): # 通信循环 while True: try: cmd = self.request.recv(1024) if len(cmd) == 0: break else: cmd = cmd.decode(encoding='utf-8') if cmd == 'get': path = 'file.txt' if not os.path.exists(path): raise ValueError('没有文件') total_size = os.path.getsize(filename=path) print(total_size) import hashlib with open(path, 'rb') as f: for line in f: line hashlib_value = 'xxxx' else: obj = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) s_out = obj.stdout.read() s_err = obj.stderr.read() total_size = len(s_out) + len(s_err) path = None hashlib_value = '你大爷' header_dic = { 'file_name': path, 'total_size': total_size, 'hashlib': hashlib_value } header_json = (json.dumps(header_dic)).encode(encoding='utf-8') header_len = struct.pack('i', len(header_json)) print('header_len:%s' % header_len) # print(header_len) self.request.send(header_len) # print(header_json) self.request.send(header_json) if cmd == 'get': with open(path, 'rb') as f: for line in f: # print(line) self.request.send(line) else: # print('cmd') self.request.send(s_out) self.request.send(s_err) except ConnectionResetError: break self.request.close() if __name__ == "__main__": s = socketserver.ThreadingTCPServer(('127.0.0.1', 8080), MyHandler, bind_and_activate=True) s.serve_forever() #客户端
# from socket import * # # socket_client = socket(AF_INET, SOCK_STREAM) # print('进行连接') # socket_client.connect(('127.0.0.1', 8080)) # print('连接成功') # while True: # msg = input('请输入') # if not len(msg): continue # socket_client.send(msg.encode(encoding='utf-8')) # data =socket_client.recv(1024) # print(data.decode(encoding='utf-8')) # # socket_client.close() import socket, struct, json, hashlib st = socket.socket(socket.AF_INET, socket.SOCK_STREAM) st.connect(('127.0.0.1', 8080)) def get_file(st): data = st.recv(4) print(data) data = struct.unpack('i', data)[0] header_json = json.loads((st.recv(data)).decode('utf-8')) print(header_json) file_down = b'' encodeing = None while header_json['total_size'] > 0: msg = st.recv(1024) header_json['total_size'] -= len(msg) file_down += msg try: if encodeing == None: print(msg.decode(encoding='utf-8')) else: print(msg.decode(encodeing='gbk')) except Exception: encodeing == False print(msg.decode(encoding='gbk')) return file_down while True: msg = input('请输入').strip() if not len(msg): continue try: st.send(msg.encode('utf-8')) file_down = get_file(st) if msg == 'get': with open('save.txt', 'wb') as f: f.write(file_down) print('end') except ConnectionResetError: break st.close()