远程执行命令

服务器:

#远程执行命令
from socket import *
import subprocess
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(back_log)

while True:
    conn,addr=tcp_server.accept()
    print('新的客户端链接',addr)
    while True:
        #
        try:
            cmd=conn.recv(buffer_size)
            # if not cmd:break
            print('收到客户端命令是',cmd)

        #执行命令,得到命令的运行结果,cmd_res
            res=subprocess.Popen(cmd.decode('utf-8'),shell=True,
                                 stderr=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE)
            err=res.stderr.read()
            if err:#有值
                cmd_res=err
            else:
                cmd_res=res.stdout.read()
            #
            conn.send(cmd_res)
        except Exception as e:
            print(e)
            break
    conn.close()

客户端:

from socket import *
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_client=socket(AF_INET,SOCK_STREAM)#数据报
tcp_client.connect(ip_port)
while True:
   cmd=input('>>').strip()
   if not cmd:continue
   if cmd=='quit':break
   tcp_client.send(cmd.encode('utf-8'))
   cmd_res=tcp_client.recv(buffer_size)
   print('命令的执行结果是',cmd_res.decode('gbk '))
tcp_client.close()

 

posted @ 2018-05-23 18:15  未来的技术  阅读(116)  评论(0编辑  收藏  举报