服务端
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # _author_ = ‘hjm‘ 4 # @Time : 2018/1/20 下午8:10 5 # @Email : HUANGJIANMING@huazhu.com 6 # @File : server_socket.py 7 # @Software: PyCharm 8 import socket,os 9 10 server=socket.socket() 11 server.bind((‘127.0.0.1‘,9999)) 12 #服务端绑定地址 13 server.listen() 14 #服务端监听 15 while True: 16 con,addr=server.accept() 17 18 print("new conn",addr) 19 while True: 20 print(‘等待新的指令!‘) 21 data=con.recv(1024) 22 if not data: 23 print(‘客户端已经断开‘) 24 break 25 cmd_res=os.popen(data.decode()).read() 26 if len(cmd_res)==0: 27 cmd_res=‘out put....‘ 28 cmd_sazi=len(cmd_res) 29 con.send(str(cmd_sazi).encode(‘utf-8‘)) 30 31 #con.recv(1024)#分割粘包 32 con.send(cmd_res.encode(‘utf-8‘)) 33 print("send down") 34 server.close()
客户端
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # _author_ = ‘hjm‘ 4 # @Time : 2018/1/20 下午8:10 5 # @Email : HUANGJIANMING@huazhu.com 6 # @File : client_socket.py 7 # @Software: PyCharm 8 import socket 9 10 clinet = socket.socket() 11 ip_port = (‘127.0.0.1‘, 9999) 12 clinet.connect(ip_port) 13 while True: 14 cmd = input(‘>>:‘).strip() 15 # 客户端输入命令,ls ,ifconfig 16 if len(cmd) == 0: continue # 不能发送空数据 17 clinet.send(cmd.encode(‘utf-8‘)) 18 19 # 客户端发送指令 20 cmd_saiz = clinet.recv(1024) 21 # 接收服务发送的数据大小 22 print(cmd_saiz) 23 #clinet.send(b‘123‘) 24 received_saiz = 0 25 26 while received_saiz != int(cmd_saiz.decode(‘utf-8‘)):#判断接收的大小与发送的大小是否一致 27 data = clinet.recv(1024) 28 # 客户端接收1024字节数据 29 received_saiz += len(data) 30 31 print(data.decode()) 32 clinet.close()