开发简单的FTP:
1. 用户登陆
2. 上传/下载文件put/get
3. 不同用户家目录不同home
4. 查看当前目录下文件ls
5. 充分使用面向对象知识
目录:
1 import os,socket,optparse,json,time 2 3 STATUS_CODE ={ 4 200 : "操作成功", 5 601 : ‘操作失败‘ 6 } 7 8 class FTPClient(object): 9 def __init__(self): 10 self.parser = optparse.OptionParser() 11 self.parser.add_option(‘-H‘, ‘--host‘, dest=‘host‘, help=‘host of server‘) 12 self.parser.add_option(‘-P‘,‘--port‘,type=‘int‘,dest= ‘port‘,help=‘port of server‘) 13 self.parser.add_option(‘-u‘,‘--username‘,dest= ‘username‘,help=‘username‘) 14 self.parser.add_option(‘-p‘,‘--password‘,dest= ‘password‘,help=‘password‘) 15 (self.options,self.args) = self.parser.parse_args() 16 self.verify_args() 17 self.make_connection() 18 self.header = {} 19 20 def make_connection(self): 21 self.sock = socket.socket() 22 self.sock.connect((self.options.host,self.options.port)) 23 24 def verify_args(self): 25 if self.options.host and self.options.port: 26 if self.options.port > 0 and self.options.port<= 65535: 27 if self.options.username and self.options.password: 28 return True 29 else: 30 exit(‘check your username and password‘) 31 else: 32 exit("worry Port!") 33 34 else: 35 exit(‘Please check your host and port! They can not be null!‘) 36 37 def authenticate(self): 38 ‘‘‘登陆验证‘‘‘ 39 # print(‘authenticating.........‘) 40 # print(self.get_auth_result(self.options.username,self.options.password).get(‘code‘)) 41 if self.get_auth_result(self.options.username,self.options.password).get(‘code‘) == 200: 42 self.header = {‘username‘:self.options.username} 43 return True 44 else: 45 raise Exception(‘worry username or password!‘) 46 # retry_count = 0 47 # while retry_count < 3: 48 # user = input("username>>>").strip() 49 # password = input("password>>>").strip() 50 # self.get_auth_result(user,password) 51 # else: 52 # retry_count += 1 53 def get_auth_result(self,username,password): 54 data = { 55 ‘action‘ : ‘auth‘, 56 ‘username‘ : username, 57 ‘password‘ : password 58 } 59 # print(data) 60 self.sock.sendall(json.dumps(data).encode()) 61 # print(‘send sucessfully‘) 62 # print(self.get_response()) 63 # print(type(self.get_response())) 64 return self.get_response() 65 66 def get_response(self): 67 ‘‘‘获取服务器结果‘‘‘ 68 recv = self.sock.recv(1024) 69 recv = json.loads(recv.decode()) 70 # print(recv) 71 print(‘response‘,recv) 72 # print(type(recv)) 73 return recv 74 75 def opearte_cmd(self,cmd): 76 # print(‘12345‘) 77 # print(cmd,‘&&&&&&&&‘) 78 if cmd is None : 79 raise Exception(‘cmd cannot be null‘) 80 cmd_list =cmd.split() 81 if cmd_list[0] ==‘get‘ and len(cmd_list) == 2: 82 self._get(cmd) 83 return 84 if cmd_list[0] ==‘put‘ and len(cmd_list) == 2: 85 if os.path.exists(cmd_list[1]): 86 self._put(cmd) 87 return 88 if cmd_list[0] ==‘ls‘: 89 self._ls() 90 return 91 if cmd_list[0] ==‘exit‘: 92 exit() 93 else: 94 raise Exception(‘cmd is worry!please try again later!‘) 95 96 def get_FileSize(self,filePath): 97 fsize = os.path.getsize(filePath) 98 # fsize = fsize / float(1024) 99 # return round(fsize, 2) 100 return fsize 101 def _get(self,cmd): 102 cmd_list = cmd.split() 103 data = { 104 ‘header‘: self.header, 105 ‘action‘: ‘get‘, 106 ‘filename‘: cmd_list[1] 107 } 108 recv = self.sock.sendall(json.dumps(data).encode()) 109 response = self.get_response() 110 print(‘recv‘,response) 111 112 if response.get(‘code‘) == 200: 113 file_size = response.get(‘file_size‘) 114 with open(cmd_list[1],‘wb‘) as f: 115 recv_size = 0 116 while recv_size < int(file_size): 117 recv_data = self.sock.recv(1024) 118 # print(recv_data) 119 recv_size += len(recv_data) 120 # print(recv_size) 121 f.write(recv_data) 122 self.sock.send(b‘1‘) 123 print(self.get_response()) 124 return 125 else: 126 raise Exception(‘worry with server in get file .‘) 127 128 129 def _put(self,cmd): 130 cmd_list = cmd.split() 131 filename = cmd_list[1].split(‘\\\\‘)[-1] 132 print(cmd_list[1]) 133 file_size = self.get_FileSize(cmd_list[1]) 134 data = { 135 ‘header‘: self.header, 136 ‘action‘: ‘put‘, 137 ‘filename‘: filename, 138 ‘file_size‘:file_size 139 } 140 self.sock.sendall(json.dumps(data).encode()) 141 recv = self.get_response() 142 if recv.get(‘code‘) == 200: 143 print(os.path.exists(cmd_list[1])) 144 f = open(cmd_list[1],‘rb‘) 145 size = 0 146 for line in f: 147 size += len(line) 148 # print(size) 149 # print(line) 150 self.sock.send(line) 151 self.sock.recv(1) 152 f.close() 153 print(‘recv:‘,self.get_response()) 154 return True 155 else: 156 msg = { 157 ‘code‘:recv.get(‘code‘), 158 ‘message‘: STATUS_CODE.get(recv.get(‘code‘)) 159 } 160 raise Exception(msg) 161 162 def _ls(self): 163 data = { 164 ‘header‘: self.header, 165 ‘action‘: ‘ls‘ 166 } 167 self.sock.sendall(json.dumps(data).encode()) 168 print(‘recv:‘, self.get_response()) 169 return True 170 171 #python FTP1\\Client\\client.py -H 127.0.0.1 -P 9001 -u alex -p 1234 172 173 def interactive(self): 174 if self.authenticate(): 175 print(‘start interactive‘.center(60,‘-‘)) 176 while True: 177 print(‘‘‘ 178 List of functions: 179 get : e.g:get XXX.txt, 180 put : e.g:put XXX.txt, 181 ls : e.g:ls 182 exit : e.g:exit 183 ‘‘‘) 184 cmd = input("cmd>>>").strip() 185 self.opearte_cmd(cmd) 186 continue 187 188 189 #python FTP1\\Client\\client.py -H 127.0.0.1 -P 9001 -u alex -p 1234 190 # put C:\\Users\\Administrator\\Desktop\\noteForPython.txt 191 if __name__ == ‘__main__‘: 192 client = FTPClient() 193 client.interactive()
1 import os,sys 2 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 3 sys.path.append(base_dir) 4 5 from core import main 6 7 if __name__ == ‘__main__‘: 8 main.ArgvHandler()
1 import os,sys 2 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 3 4 USER_HOME = ‘%s/home‘%(base_dir) 5 LOG_DIR = ‘%s/log‘%(base_dir) 6 LOG_level = ‘DEBUG‘ 7 ACCOUNT_FILE = ‘%s/db/account.ini‘%(base_dir) 8 9 HOST = ‘127.0.0.1‘ 10 PORT = 9001
1 import socketserver,json,configparser,os,time 2 3 STATUS_CODE ={ 4 200 : "操作成功", 5 601 : ‘操作失败‘ 6 } 7 Base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 8 from conf import settings 9 class FTPHandler(socketserver.BaseRequestHandler): 10 def handle(self): 11 while True: 12 print("welcome to FTPHander-handle-whileTrue...") 13 self.data = self.request.recv(1024).strip() 14 if self.data is None: 15 print("Client is closed") 16 break 17 print(self.client_address[0]) 18 19 data = json.loads(self.data.decode()) 20 21 if data.get(‘action‘) == ‘auth‘: 22 self._auth(data) 23 elif data.get(‘action‘) in (‘put‘,‘get‘,‘ls‘): 24 func = getattr(self,‘_%s‘%data.get(‘action‘)) 25 func(data) 26 else: 27 print(‘invlid cmd‘) 28 self.send_response(601) 29 30 31 def _auth(self,data): 32 # print(data) 33 parser = configparser.ConfigParser() 34 parser.read(settings.ACCOUNT_FILE) 35 section_list = parser.sections() 36 if data.get(‘username‘) in section_list: 37 true_pwd = parser.get(data.get(‘username‘),‘password‘) 38 quation = parser.get(data.get(‘username‘),‘quation‘) 39 # print(true_pwd,quation) 40 # print(data.get(‘password‘)) 41 if true_pwd == data.get(‘password‘): 42 # print(‘1313‘) 43 self.send_response(200) 44 45 46 # def _auth(self,*args,**kwargs): 47 # print(args.center(60,‘-‘)) 48 # parser = configparser.ConfigParser() 49 # parser.read(settings.ACCOUNT_FILE) 50 # section_list = parser.sections() 51 # if args[‘username‘] in section_list: 52 # true_pwd = parser.get(args[‘username‘],‘password‘) 53 # quation = parser.get(args.get[‘username‘],‘quation‘) 54 # if true_pwd == args[‘password‘]: 55 # self.send_response(200) 56 # if args.get(‘username‘) in section_list: 57 # true_pwd = parser.get(args.get(‘username‘),‘password‘) 58 # quation = parser.get(args.get(‘username‘),‘quation‘) 59 # if true_pwd == args.get(‘password‘): 60 # self.send_response(200) 61 62 def send_response(self,code,data=None): 63 response ={‘code‘:code,‘msg‘:STATUS_CODE[code]} 64 if data: 65 response.update( data ) 66 self.request.send(json.dumps(response).encode()) 67 68 def verify_data(self,*args): 69 pass 70 71 def _put(self,data): 72 print(‘start put......................................................‘) 73 self.verify_data(data) 74 if data.get(‘header‘) == {}: 75 self.send_response(601) 76 parser = configparser.ConfigParser() 77 parser.read(settings.ACCOUNT_FILE) 78 section_list = parser.sections() 79 username_of_data = data.get(‘header‘).get(‘username‘) 80 flag = username_of_data in section_list 81 # print(flag) 82 if flag: 83 quation = parser.get(username_of_data, ‘quation‘) 84 # home_DIR = Base_dir.join(‘home\\%s‘ % username_of_data) 85 home_DIR = os.path.join(Base_dir,‘home\\%s‘ % username_of_data) 86 # print(home_DIR) 87 user_exit_file = os.listdir(home_DIR) 88 print(user_exit_file) 89 size_exited = 0 90 for filePath in user_exit_file: 91 filePath = os.path.join(home_DIR,filePath) 92 size_exited += self.get_FileSize(filePath) 93 94 puted_file_size = data.get(‘file_size‘) 95 96 if puted_file_size > int(quation) - size_exited: 97 self.send_response(601) 98 else: 99 self.send_response(200) 100 puted_filename = data.get(‘filename‘) 101 if puted_filename in user_exit_file: 102 puted_filename = ‘%s-1‘% puted_filename 103 # filename = home_DIR.join(puted_filename) 104 filename = os.path.join(home_DIR,puted_filename) 105 get_FileSize = 0 106 with open(filename,"wb") as f: 107 while get_FileSize < puted_file_size: 108 file_data = self.request.recv(1024) 109 f.write(file_data) 110 get_FileSize += len(file_data) 111 self.request.send(b‘1‘) 112 # print(file_data) 113 # print(get_FileSize, puted_file_size) 114 self.send_response(200) 115 print(‘put successfully...‘.center(60,‘-‘)) 116 117 118 def get_FileSize(self,filePath): 119 fsize = os.path.getsize(filePath) 120 # fsize = fsize / float(1024) 121 # return round(fsize, 2) 122 return fsize 123 124 def _get(self,data): 125 print(‘start get................‘) 126 # self.verify_data(data) 127 if data.get(‘header‘) == {}: 128 self.send_response(601) 129 parser = configparser.ConfigParser() 130 parser.read(settings.ACCOUNT_FILE) 131 section_list = parser.sections() 132 username_of_data = data.get(‘header‘).get(‘username‘) 133 filename = data.get(‘filename‘) 134 # home of user 135 home_DIR = os.path.join(Base_dir,‘home\\%s‘ % username_of_data) 136 #abspath 137 filename = os.path.join(home_DIR,filename) 138 if os.path.isfile(filename): 139 file_size = os.path.getsize(filename) 140 self.send_response(200,{‘file_size‘:‘%s‘%file_size}) 141 f = open(filename,‘rb‘) 142 for line in f: 143 print(line) 144 self.request.send(line) 145 self.request.recv(1) 146 self.send_response(200) 147 print("get successfully.....") 148 else: 149 self.send_response(601) 150 151 152 def _ls(self,data): 153 print(‘start ls...‘) 154 self.verify_data(data) 155 if data.get(‘header‘) == {}: 156 self.send_response(601) 157 parser = configparser.ConfigParser() 158 parser.read(settings.ACCOUNT_FILE) 159 section_list = parser.sections() 160 username_of_data = data.get(‘header‘).get(‘username‘) 161 flag = username_of_data in section_list 162 if flag: 163 home_DIR = os.path.join(Base_dir, ‘home\\%s‘ % username_of_data) 164 user_exit_file = os.listdir(home_DIR) 165 self.request.sendall(json.dumps(user_exit_file).encode()) 166 for i in user_exit_file: 167 print(i) 168 169 170 def _cd(self,*args,**kwargs): 171 pass 172 173 if __name__ == ‘__main__‘: 174 HOST, PORT = settings.Host, settings.PORT
1 from core.ftp_server import FTPHandler 2 from conf import settings 3 import socketserver 4 5 class ArgvHandler(object): 6 def __init__(self): 7 self.start() 8 # self.parser = optparse.OptionParser() 9 # self.parser.add_option(‘-H‘,‘--host‘,dest= ‘host‘,help=‘host of server‘) 10 # self.parser.add_option(‘-P‘,‘--port‘,type=int,dest= ‘port‘,help=‘port of server‘) 11 # (self.options,self.args) = self.parser.parse_args() 12 # print(self.options,self.args) 13 # # print(dir(self.options)) 14 # print(self.options.host) 15 # self.verify_args() 16 17 18 def verify_args(self): 19 if hasattr(self,self.args[0]): 20 func = getattr(self,self.args[0]) 21 func() 22 23 else: 24 print(self.parser.print_help()) 25 26 def start(self): 27 print(‘going to start...‘.center(60,‘-‘)) 28 server = socketserver.ThreadingTCPServer((settings.HOST, settings.PORT),FTPHandler) 29 server.serve_forever()