server端:
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import socket import subprocess sk = socket.socket() sk.bind(("127.0.0.1", 9000)) sk.listen(5) while True: print "Sever Listening..." conn, addr = sk.accept() while True: accept_data = conn.recv(1024) if not accept_data:break print "recv cmd: ",accept_data cmd = accept_data.strip() exec_result = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) cmd_resule = exec_result.stdout.read() if len(cmd_resule) ==0: cmd_resule = "command error" ack_msg = "Size|%s" %str(len(cmd_resule)) conn.send(ack_msg) conn.send(cmd_resule) conn.close()
client端:
#!/usr/bin/env python2.7 # -*- coding: utf-8 -*- import socket sk = socket.socket() sk.connect(("127.0.0.1", 9000)) while True: data_input = raw_input("cmd: ").strip() if len(data_input) == 0:continue if data_input == 'q':break sk.sendall(data_input) server_ack_msg = sk.recv(100) cmd_res_msg = str(server_ack_msg).split("|") print cmd_res_msg if cmd_res_msg[0] == "Size": cmd_res_size = int(cmd_res_msg[1]) res = "" received_size = 0 while received_size < cmd_res_size: data = sk.recv(500) received_size += len(data) res += str(data) else: print "-----recv done------" print res sk.close()