Ssh simulation function and subprocess module

Ssh simulation function and subprocess module

ssh --- "remote command execution

subprocess --- "execute system commands module

A, subprocess module

import subprocess
# 执行系统dir命令(查看当前目录下有哪些文件),把执行的正确结果放到管道中
obj = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# stdout是正确信息,stderr是错误信息
# 拿到结果的管道,读出里面的内容
ss = obj.stdout.read()  # 读正确信息
err = obj.stderr.read()  # 读错误信息
print('错误信息>>>',str(err,encoding='gbk'))  # 打印错误信息,因为windows用的gbk编码,所以用gbk解码
print('正确信息>>>',str(ss,encoding='gbk'))  # 打印正确信息

Second, the functional simulation ssh client and server

2.1 analog functions ssh client

import socket
soc = socket.socket() # 不传参默认是tcp协议
soc.connect(('127.0.0.1',8005))
while True:  # 通信循环
    in_s = input('请输入要执行的命令>>>').strip()
    soc.send(in_s.encode('utf8'))  # 转换成bytes格式发送
    data = soc.recv(1024)  # 接收数据
    print(str(data,encoding='gbk')) # 打印接收的数据

Please enter a command to be executed >>> dir
drive E in the volume is to download and install software
Volume Serial Number is E6E3-32EF

E: \ Old Boys Education \ python project \ Pycharm practice \ Network Programming \ 0906 analog ssh (remote command execution) function and subprocess modules directory

2019/09/10 21:04

.
2019/09/10 21:04 ..
2019/09/10 20:30 363 client_ssh.py
2019/09/10 21:04 912 server_ssh.py
2019/09/10 19:56 The subprocess 666 - execute a system command module .py
. 3 files 1,941 bytes
2 bytes available directory 101,702,057,984

2.2 analog functions ssh server

import socket
import subprocess
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.bind(('192.168.11.176',8005))
soc.listen(5)
while True:  # 连接循环
    print('等待客户端连接')
    conn,addr = soc.accept()
    print('有个客户端连接上了>>>',addr)
    while True:  # 通信循环
        try:
            data = conn.recv(1024)
            if len(data) == 0:
                break
            print(data)
            # 使用subprocess模块
            obj = subprocess.Popen(str(data,encoding='utf8'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            # 执行正确的结果bytes格式,gbk编码(windows平台)
            msg = obj.stdout.read()
            # 把执行的结果通过网络传给c端
            conn.send(msg)
        except Exception:
            break
    # 关闭通路
    conn.close()

# 关闭连接
soc.close()

Connection requests from clients
have connected the client >>> ( '127.0.0.1', 50889)
b'dir '

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11503359.html