server
#server #!usr/bin/evn python # -*- coding:utf-8 -*- import socket import subprocess sk=socket.socket() addrs=('127.0.0.1',8888) sk.bind(addrs) sk.listen(5) while 1: conn,addr=sk.accept() print(addrs) while 1: data=conn.recv(1024) print(str(data,'utf-8')) if not data:break obj=subprocess.Popen(str(data,'utf8'),shell=True,stdout=subprocess.PIPE)#没有最后一个参数会放到子进程中 cmd_ret = obj.stdout.read() ret_len = bytes(str(len(cmd_ret)), 'utf8') conn.sendall(ret_len) conn.sendall(cmd_ret) sk.close()
client
#!usr/bin/evn python # -*- coding:utf-8 -*- import socket sk=socket.socket() print(sk) address=('127.0.0.1',8888) sk.connect(address) while True: ipt=input('>>>') if ipt=='exit': break sk.sendall(bytes(ipt,'utf-8')) ret_len=int(str(sk.recv(1024),'utf-8')) data=bytes() while len(data)!=ret_len: rev=sk.recv(1024) data+=rev print(str(data,'gbk')) sk.close()