socket之远程执行命令
一:TCP
1、服务端
import socket sk = socket.socket() sk.bind(('127.0.0.1',8090)) sk.listen() conn,addr = sk.accept() while True: cmd = input('cmd : ') if cmd == 'q': conn.send(cmd.encode('utf-8')) break conn.send(cmd.encode('utf-8')) print('stdout : ',conn.recv(1024).decode('gbk')) conn.close() sk.close()
2、客户端
import socket import subprocess sk = socket.socket() sk.connect(('127.0.0.1',8090)) while True: cmd = sk.recv(1024).decode('utf-8') if cmd == 'q': break res = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sk.send(res.stdout.read()) sk.send(res.stderr.read()) sk.close()
二:UDP
1、服务端
import socket sk = socket.socket(type=socket.SOCK_DGRAM) sk.bind(('127.0.0.1',8092)) msg,addr = sk.recvfrom(1024) while True: cmd = input('cmd : ') if cmd == 'q': sk.sendto(cmd.encode('utf-8'),addr) break sk.sendto(cmd.encode('utf-8'),addr) print('stdout : ',sk.recvfrom(1024)[0].decode('gbk')) print('stderr : ',sk.recvfrom(1024)[0].decode('gbk')) sk.close()
2、客户端
import socket import subprocess sk = socket.socket(type=socket.SOCK_DGRAM) sk.sendto(b'111',('127.0.0.1',8092)) while True: cmd = sk.recvfrom(1024)[0].decode('utf-8') #接收到的原始消息是一个元祖,第一为消息,第二为地址 if cmd == 'q': break res = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) sk.sendto(res.stdout.read(),('127.0.0.1',8092)) sk.sendto(res.stderr.read(),('127.0.0.1',8092)) sk.close()