------类似于cmd的功能,client执行命令,server发命令结果发送到client
-----------server.py-------------------
import subprocess#subprocess.Popen,主要用Popen这个类实现shell import socketsk=socket.socket()print(sk)address=(‘127.0.0.1‘,8003)sk.bind(address)sk.listen(3)print(‘waiting.....‘)while True: conn,addr = sk.accept() print(addr) while True: try: data = conn.recv(1024) except Exception: break if not data: break print(‘.....‘, str(data, ‘utf8‘)) obj=subprocess.Popen(str(data,‘utf8‘),shell=True,stdout=subprocess.PIPE) #stdout=subprocess.PIPE表示通过管道PIP由你的子进程转到我主进程并封装到obj对象里 ----即这一行和下面这一行的功能就是把client发来指令的结果解出来
cmd_result=obj.stdout.read() result_len=bytes(str(len(cmd_result)),‘utf8‘) #算出它的大小 conn.sendall(result_len) #把这个大小的数字传给client conn.recv(1024) conn.sendall(bytes(cmd_result))sk.close() -----------------------------client.py-------------------------------
import socketsk=socket.socket()print(sk)address=(‘127.0.0.1‘,8003)sk.connect(address)while True: inp=input(‘>>>‘) if inp == ‘exit‘: break sk.send(bytes(inp,‘utf8‘)) result_len=int(str(sk.recv(1024),‘utf8‘)) sk.sendall(bytes(‘111‘,‘utf8‘)) print(result_len) data=bytes() while len(data) != result_len: recv= sk.recv(1024) data+=recv print(str(data,‘gbk‘))sk.close()
结果如下图:在client执行dir和ipconfig等命令能拿到结果
原文地址:https://www.cnblogs.com/dbslinux/p/11239650.html
时间: 2024-11-05 23:36:43