socketserver Version remote execution command client End .
import socket sk = socket.socket() address = ("127.0.0.1", 8088) sk.connect(address) while True: cmd = input(" Please enter a command :") sk.sendall(bytes(cmd, encoding='utf8')) if cmd == 'exit': break len_result = sk.recv(1024) len_result = int(str(len_result, encoding='utf8')) sk.sendall(bytes("ok", encoding='utf8')) result = bytes() while len(result) != len_result: date = sk.recv(1024) result += date print(str(result, encoding='gbk')) sk.close()
socketserver Version remote execution command server End
import socketserver import subprocess class Myserver(socketserver.BaseRequestHandler): def handle(self): print(" Server side start ") conn = self.request print(conn) client_address = self.client_address while True: try: cmd = str(conn.recv(1024), encoding='utf8') except Exception as e: print(e) break if cmd == 'exit': break print(" client :{}, command :{}".format(client_address, cmd)) cmd_result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) cmd_result_stdout = cmd_result.stdout.read() cmd_result_stderr = cmd_result.stderr.read() if len(cmd_result_stdout) == 0: result = cmd_result_stderr else: result = cmd_result_stdout conn.sendall(bytes(str(len(result)), encoding='utf8')) conn.recv(1024) conn.sendall(result) conn.close() if __name__ == '__main__': server = socketserver.ThreadingTCPServer(('127.0.0.1', 8088), Myserver) server.serve_forever()