socket subprocess远程执行系统命令

server 端

import socket
import subprocess

server = socket.socket()
server.bind(("127.0.0.1",8080))
server.listen(5)

while True:
    conn, addr = server.accept()
    print(addr)

    while True:
        try:
            cmd = conn.recv(1024)
            obj = subprocess.Popen(cmd.decode(),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE
                             )
            stdout = obj.stdout.read()
            stderr = obj.stderr.read()

            conn.send(stdout+stderr)
        except ConnectionResetError:
            break

    conn.close()
server.close()

 

 

client 端

from socket import *
client = socket(AF_INET,SOCK_STREAM)
client.connect(('127.0.0.1',8080))

while True:
    cmd = input(">>:").strip()
    client.send(cmd.encode())
    res = client.recv(1024)
    print(res.decode("gbk"))

client.close()

cmd:   

        dir | ipconfig

上一篇:回到Java控制台


下一篇:与子进程stdout / stdin通信