模拟ssh发送cmd指令
服务端
import socket
import subprocess
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 8087))
server.listen(5)
print('wait...')
while True:
conn, client_addr = server.accept()
print(client_addr)
while True:
try:
cmd = conn.recv(1024)
print(cmd)
pipeline = subprocess.Popen(cmd.decode('utf-8'),
shell=True,
stderr=subprocess.PIPE, # 报错信息
stdout=subprocess.PIPE) # 返回信息
# 获取两个信息
stuout = pipeline.stdout.read()
stderr = pipeline.stderr.read()
# 也可以写成,if和else,不过这两个一般只会出现一个,所以这样写也没问题
conn.send(stuout+stderr)
except ConnectionResetError:
break
客户端
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8087))
while True:
# 这里就可以输入一个cmd中的命令了,如ipconfig, dir等,但有一些输入过长的命令无法获取
msg = input('please your enter msg').strip()
client.send(msg.encode('utf-8'))
cmd = client.recv(1024)
print(cmd.decode("gbk"))