socket 远程命令

# -*- coding: utf-8 -*-
# 斌彬电脑

from socket import *
import subprocess

server = socket(AF_INET, SOCK_STREAM)
server.bind(('',10000))
server.listen(5)

while True:
    conn,addr = server.accept()
    print( '客户端ip地址:',addr )
    while True:
        try:
            cmd = conn.recv(1024)
            # if not cmd: break       # 如果是
            print( '收到命令:',cmd )

            # 生成可执行命令
            res  = subprocess.Popen(cmd.decode('gbk'),shell=True,
                                    stderr=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE)
            err = res.stderr.read()                  #  错误命令才有值
            if err:                                  #  命令正确
                cmd_res = '错误命令'.encode('gbk')   # 错误命令,再读进是空值
            else:
                cmd_res = res.stdout.read()          #   返回执行结果
            conn.send(cmd_res)                       #  结果返回客户端
        except Exception as e:
            print(e)
            break

  

# -*- coding: utf-8 -*-

from socket import *

cl = socket()
cl.connect(('127.0.0.1',10000))

while True:
    cmd = input('--->>>')
    if not cmd:    continue
    if cmd == 'quit': break

    cl.send(cmd.encode('gbk'))
    re = cl.recv(2048)
    print('命令执行结果:',re.decode('gbk'))

  

 

客户端向服务器发送 CMD 命令,并回写

posted @ 2018-07-15 06:45  25班Ph201805201  阅读(532)  评论(0编辑  收藏  举报