最近在看python网络方面的知识,发现使用socket编写一些小的服务器真是太方便了,简单几行代码就能实现一个服务器,真是高大上呀,废话少说,直接上代码:
SSH服务器端代码:
#!/usr/bin/env python
#coding:utf-8
#file : ssh server
import socket , commands
host = 'localhost'
port = 8998
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR ,1)
s.bind((host,port))
s.listen(2)
while 1:
c,a = s.accept()
print "Connected from:" , a
while 1:
data = c.recv(1024).strip()
if not data:
break
status , result = commands.getstatusoutput(data)
if len(result.strip()) != 0:
c.sendall(result)
else:
c.sendall("Done")
c.close
s.close(
SSH客户端代码:
#!/usr/bin/env python
#coding:utf-8
#file: ssh client
import socket
host = 'localhost'
port = 8998
s =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
while 1:
cd = raw_input("Please enter an command:").strip()
if not cd:
continue
s.sendall(cd)
data =s.recv(8096)
print data
s.close()
这两个脚本实现了简单的linux命令的查询功能,但是有一个bug就是长命令的查询功能没有实现,下次进行更正。