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,这智商让人捉急啊。
时间: 2024-10-08 16:58:50