使用 Socket 實現 FTP Server
阿新 • • 發佈:2018-01-03
clas p s continue nds soc root usr ted utf8
使用 Socket 實現 FTP Server ,實現如下功能:
get /tmp/1.txt /tmp/1.txt :把服務端 /tmp/1.txt 下載到客戶端 /tmp/1.txt
put /tmp/1.txt /tmp/1.txt :把客戶端 /tmp/1.txt 上傳到服務端 /tmp/1.txt
[root@localhost ~]# cat ftp_server.py #!/usr/bin/env python #-*- coding: utf8 -*- import socket from subprocess import Popen, PIPE HOST = ‘‘ PORT= 1234 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print ‘conn‘, conn print ‘Connected by‘, addr while 1: cmd = conn.recv(1024) cmd_list = cmd.split() if cmd_list[0] == ‘get‘: with open(cmd_list[1]) as fd:while True: data = fd.read(1024) conn.sendall(data) if not data: conn.sendall(‘EOF‘) break if not cmd: break conn.close()
[root@localhost ~]# cat ftp_client.py #!/usr/bin/env python #-*- coding:utf-8-*- import os import sys import tab import socket HOST = ‘192.168.5.131‘ PORT = 1234 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while True: cmd = raw_input("Please input cmd: ").strip() if cmd.lower()== ‘exit‘ or cmd.lower() == ‘quit‘: break cmd_list = cmd.split() if len(cmd_list) != 3: print "Ex: get file1 file2" continue else: s.sendall(cmd) if not os.path.exists(cmd_list[2]): dst_file = cmd_list[2] else: dst_file = cmd_list[2]+‘.new‘ n = 1 while True: data_rev = s.recv(1024) if data_rev.endswith(‘EOF‘): data = data_rev[:-3] else: data = data_rev if n == 1: with open(dst_file, ‘wb‘) as fd: fd.write(data) else: with open(dst_file, ‘a‘) as fd: fd.write(data) n += 1 if data_rev[-3:] == ‘EOF‘: print "Success! destination file is %s" % dst_file break s.close()
使用 Socket 實現 FTP Server