模拟ssh实现远程执行命令

服务端必须满足至少三点:
1. 绑定一个固定的ip和port
2. 一直对外提供服务,稳定运行
3. 能够支持并发
from socket import *

client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8081))

# 通信循环
while True:
    cmd=input('>>: ').strip()
    if len(cmd) == 0:continue
    client.send(cmd.encode('utf-8'))
    cmd_res=client.recv(1024000)
    print(cmd_res.decode('gbk'))

client.close()
客户端
服务端必须满足至少三点:
1. 绑定一个固定的ip和port
2. 一直对外提供服务,稳定运行
3. 能够支持并发
from socket import *
import subprocess

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

# 链接循环
while True:
    conn, client_addr = server.accept()
    print(client_addr)

    # 通信循环
    while True:
        try:
            cmd = conn.recv(1024) #cmd=b'dir'
            if len(cmd) == 0: break  # 针对linux系统
            #subprocess.Popen 执行系统命令
            obj=subprocess.Popen(cmd.decode('utf-8'),
                             shell=True,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE
                             )
            stdout=obj.stdout.read()
            stderr=obj.stderr.read()
            print(len(stdout) + len(stderr))
            conn.send(stdout+stderr)
        except ConnectionResetError:
            break

    conn.close()

server.close()
服务端

猜你喜欢

转载自www.cnblogs.com/zhouhao123/p/11261824.html