tcp远程控制命令输出

# 服务端

import socket
import subprocess

# 开机
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定ip,端口
phone.bind(('127.0.0.1', 8080))

# 监听
phone.listen(5)

# 链接循环
while 1:
    # 接收最大1024个bytes
    conn, addr = phone.accept(1024) 

    # 通信循环
    while 1:
        # 异常处理
        try:
            data = conn.recv(1024)

            # unix下不能接收空
            if len(data) == 0:break

            res = subprocess.Popen(bata.decode('gbk'),   (windows默认字符编码‘gbk’)      
            shell=True, stderr=subprocess.PIPE, 
            stdout=subprocess.PIPE)

            resout = res.stdout.read()
            reserr = res.stderr.read()

         # windows下接收空退出   
         except Exception:
            break
    
    conn.close()

phone.close() 
# 客户端

import socket

phone= socket.socket(socket.AF_INET, socket.SCOK_STREAM)

# 连接
phone.connect(('127.0.0.1', 8080))

# 循环输出
while 1:
    msg = input('请输入命令>>>').strip()

    # 不能输入空
    if len(msg) == 0:continue

    # 发送消息
    phone.send(msg.encode('gkb'))
    
    data = phone.recv(1024)

    print(data.decode('gbk'))

# 关闭
phone.close    

运行服务端,再运行客户端(当然这是自己和自己玩...),输入个 dir 命令试一下:

                    

 

 恩,就这样。。

 

posted @ 2020-04-20 16:45  三根烦恼丝啊  阅读(216)  评论(0编辑  收藏  举报