首页 > 代码库 > python_day socket 交互模拟ssh

python_day socket 交互模拟ssh

服务端

import socket
import subprocess
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server.bind((‘127.0.0.1‘,80))
server.listen(5)
while True:
conn,address=server.accept()
while True:
try:
data=http://www.mamicode.com/conn.recv(1024)
if not data:break
print(data)
res=subprocess.Popen(data.decode(‘utf-8‘),shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
err=res.stderr.read()
if err:
msg=err
else:
msg=res.stdout.read()
conn.send(msg)
except Exception:
break
conn.close()
server.close()



客户端
import socket
client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client.connect((‘127.0.0.1‘,80))

while True:
inp=input(‘cmd>>:‘).strip()
if not inp:continue
client.send(inp.encode(‘utf-8‘))
data=http://www.mamicode.com/client.recv(1024)
print(data.decode(‘gbk‘))
client.close()



python_day socket 交互模拟ssh