首页 > 代码库 > python基础之socket编程-------基于tcp的套接字实现远程执行命令的操作

python基础之socket编程-------基于tcp的套接字实现远程执行命令的操作

远程实现cmd功能:

 

技术分享
import socket
import subprocess
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.bind(("127.0.0.1",8080))
phone.listen(5)
print("starting....")
while True:
    conn,addr=phone.accept()
    while True:
        try:
            date=conn.recv(1024)
            s=date.decode("utf8")
            res=subprocess.Popen("%s"%(s),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,)
            if res.stdout:
                re1=res.stdout.read()
                conn.send(re1)
            if res.stderr:
                re2=res.stderr.read()
                conn.send(re2)
        except Exception:
            break
conn.close()
phone.close()
真正执行命令的服务端
技术分享
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(("127.0.0.1",8080))
while True:
    msg=input("请输入你的CMD命令:")
    if not msg:continue
    phone.send(msg.encode("utf8"))
    data=phone.recv(1024)
    print(data.decode("gbk"))
phone.close()
远程控制客户端

(莫名其妙的感觉哪里不对劲儿?)

 

python基础之socket编程-------基于tcp的套接字实现远程执行命令的操作