python,socket通信编程小例子,客户端发送命令到服务端,并返回运行结果
应用socket,subprocess模块,实现客户端和服务端命令发送并返回结果的小程序,代码如下:
server.py程序 import socket,subprocess sk = socket.socket() address = ('127.0.0.1',8001) sk.bind(address) sk.listen(3) conn,addr = sk.accept() data = conn.recv(1024) obj = subprocess.Popen(str(data,'utf8'),shell=True,stdout=subprocess.PIPE) cmd_result = obj.stdout.read() conn.sendall(cmd_result) sk.close()
client.py程序 import socket sk = socket.socket() address = ('127.0.0.1',8001) sk.connect(address) data = input('>>>') sk.send(bytes(data,'utf8')) result = sk.recv(1024) print(str(result,'utf8')) sk.close()
client.py和server.py通信后在client.py端显示的结果如下:
/usr/bin/python3.6 /home/guoming/python/day26/cmd_client.py
>>>ls
chat_client.py
chat_server.py
client.py
cmd_client.py
cmd_server.py
server.py
test.py