Python 通过Socket实现SSH
刚刚看了Itercast的Python Socket视频,就想到Socket能够在主机间收发信息,那加个命令执行不就是SSH了吗?
于是开始动手写一个试试.
服务器:
import socket
import os
server = socket.socket()
host = socket.gethostname()
port = 12345
server.bind((host,port))
server.listen(1)
while(True):
conn,addr = server.accept()
print("Connection Established.")
while(True):
cmd = conn.recv(1024)
result = os.popen(cmd.decode()).read()
conn.send(result.encode('utf-8'))
print("Connection Interrupted.")
server.close()
客户端:
import socket
client = socket.socket()
host = socket.gethostname()
port = 12345
client.connect((host,port))
while(True):
cmd = input(">")
client.send(cmd.encode('utf-8'))
result = client.recv(4096).decode()
print(result)
client.close()
结果:
心得:
这就是最简单的一个小程序,存在很多问题需要解决,比如命令执行结果过长怎么办?粘包怎么办?
但是复习Socket,玩一玩还是很开心的.