模拟ssh远程执行命令-代码实现

服务端:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import subprocess

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) # 端口复用
phone.bind(('127.0.0.1', 8090))
phone.listen(10)
while True: # 连接循环
connt , client = phone.accept()
print('starting ....')
print(client)

while True: # 通信循环
try:
# 1.收到命令:
cmd = connt.recv(1024)
if not cmd :continue # 适用于Linux 操作系统

# 2.执行命令:
ojb = subprocess.Popen(cmd.decode('utf-8'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

# 3.返回命令结果给客户端:
stdout = ojb.stdout.read()
stderr = ojb.stderr.read()
connt.send(stdout+stderr)
except ConnectionResetError: # 适用于windows操作系统
break

connt.close()
phone.close()

 

 

客户端:

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket

phone1 = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone1.connect(('127.0.0.1',8090))
while True:
cmd = input('>>>:').strip()
if not cmd:continue
phone1.send(cmd.encode('utf-8'))
data1 =phone1.recv(1024)
print(data1.decode('gbk')) # windows 默认编码是gbk linux 默认编码是 utf-8

phone1.close()

posted on 2019-08-23 15:19  kingforn  阅读(327)  评论(0编辑  收藏  举报