模拟ssh功能
#subprocess
#ssh 是远程执行命令
#subprocess 执行系统命令的模块
import subprocess
#执行系统dir命令,把执行的正确结果放到管道中
# obj=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
obj=subprocess.Popen('tasklistdd',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
#拿到正确结果的管道,读出里面的内容
ss=obj.stdout.read()
err=obj.stderr.read()
print('错误信息',str(err,encoding='gbk'))
#因为windows用的gbk编码,用gbk解码
# print(str(ss,encoding='utf-8'))
print(str(ss,encoding='gbk'))
#ssh的server
import socket
import subprocess
soc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
soc.bind(('127.0.0.1',8001))
soc.listen(3)
while True:
print('等待客户端连接')
conn,addr=soc.accept()
print('有个客户端连接上了',addr)
while True:
try:
data=conn.recv(1024)
if len(data)==0:
break
print(data)
obj = subprocess.Popen(str(data,encoding='utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#执行正确的结果 b 格式,gbk编码(windows平台)
msg=obj.stdout.read()
#把执行的结果通过网络传给c端
conn.send(msg)
except Exception:
break
# 关闭通道
conn.close()
# 关闭套接字
soc.close()
#client_ssh
import socket
soc=socket.socket()
soc.connect(('127.0.0.1',8001))
while True:
in_s=input('请输入要执行的命令:')
soc.send(in_s.encode('utf-8'))
data=soc.recv(1024)
print(str(data,encoding='gbk'))
#粘包:tcp会把数据量较小,时间间隔较短的数据,当做同一个包发送