服务端:
import socketimport subprocessphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #可以重复适用系统端口phone.bind(('192.168.43.14', 8081))phone.listen(5)while True: conn, clent_add = phone.accept() while True: try: #1 接受命令 data = conn.recv(1024) obj = subprocess.Popen(data.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = obj.stdout.read() stderr = obj.stderr.read() #if not data:break #如果客户端挂掉,此方法适用于linux操作系统 #print(data.decode('utf-8')) #2 执行命令 拿到结果 #3 拔执行命令的结果发送给客户端 conn.send(stdout+stderr) #+"这里可以继续优化 except ConnectionResetError: #如果客户端挂掉,此方法适用于windows操作系统 break conn.close()phone.close()客户端:
import socketphone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)phone.connect(('192.168.43.14', 8081))while True: msg = input('>>>').strip() if not msg: continue #一旦输入为空,虽然应用层可以收到,但是到应用层的操作系统就没有了,故无法发给服务端 #发命令 phone.send(msg.encode('utf-8')) #执行命令并发送结果 data = phone.recv(1024) #这里的1024 有个巨大的坑 print(data.decode('GBK'))phone.close()补充内容:
import osres = os.system('dir')print(res)# import subprocess# obj = subprocess.Popen('dffif /', shell= True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)# print('正确管道', obj.stdout.read().decode('GBK'))# print('错误管道', obj.stderr.read().decode('GBK'))