Socket的介绍就不多说了,网上都能搜到,直接说脚本,要实现FTP的功能要有服务器端和客户端,
服务器端:
import SocketServer import commands import time class MySockServer(SocketServer.BaseRequestHandler): def handle(self): print "Got a new conn from", self.client_address while True: cmd = self.request.recv(1024) if not cmd:break cmd = cmd.split() if cmd[0] =="get": print "Start transfer......." with open(cmd[1],‘rb‘) as f: self.request.send(f.read()) time.sleep(0.2) self.request.send("OOK") #这算是个标示吧。客户端收到这个说明已经传完了 continue cmd_result = commands.getstatusoutput(cmd[0]) #执行客户端发地来的shell命令 self.request.send(cmd_result[1]) if __name__ == ‘__main__‘: host=‘‘ port = 52167 s = SocketServer.ThreadingTCPServer((host,port), MySockServer) s.serve_forever() 客户端: import socket import time host = ‘x.x.x.x‘ #服务器的地址 port = 52167 addr = host,port s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(addr) while True: Input = raw_input(‘Please your input:‘).strip() if len(Input)==0:continue s.send(Input) Input = Input.split() if Input[0]== ‘get‘: print "get file ....." with open(Input[1],‘wb‘) as f: f.write(s.recv(1024)) time.sleep(0.2) if s.recv(1024) == "OOK": print "Down finsh ......" continue data = s.recv(1024) print data
一直在自学python但一直都是断断续续的不能坚持。学了好长时间才会写个简单的Socket,这智商让人捉急啊。
本文出自 “linux管理” 博客,请务必保留此出处http://hans925.blog.51cto.com/542170/1567973
利用python Socket写一个类似FTP的脚本(只写了下载,上传和下载差不多就不多写了)
原文地址:http://hans925.blog.51cto.com/542170/1567973