tcp连接发送命令客户端接收后返回结果给服务端

 

服务端

import socket

sk = socket.socket()
sk.bind(('127.0.0.1',4567))
sk.listen()

conn, addr = sk.accept()

while 1:
    cmd = input('please input your cmd:')
    if cmd=='q':
        conn.send(b'q')
        break
    conn.send(cmd.encode('gbk'))
    ret =conn.recv(1024).decode('gbk')
    print(ret)
conn.close()
sk.close()

客户端:  

subprocess模块用来接收执行命令, 

res = subprocess.Popen(cmd,shell=True,用来设置系统执行
                     stdout=subprocess.PIPE,存放结果
                     stderr=subprocess.PIPE存放错误结果
import socket
import subprocess

sk = socket.socket()
sk.connect(('127.0.0.1',4567))

while 1:
    cmd = sk.recv(1024).decode('gbk')
    if cmd == b'q':
        break
    # cmd = 'ipconfig'
    res = subprocess.Popen(cmd,shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    # print(res.stdout.read().decode('gbk'))
    sk.send(res.stdout.read())
    sk.send(res.stderr.read())

sk.close()

 

posted @ 2020-04-11 14:06  taysem  阅读(892)  评论(0编辑  收藏  举报