Detailed implementation of simple FTP

Source: Internet
Author: User

Job to show:

Develop a simple ftp:
1. User Login
2. Upload/download files
3. Different User home directories
4. View the files in the current directory
5. Full use of object-oriented knowledge

Redmae

 1 User Login 2 3 1, view user directory file 4 2, upload file, 5 3, download 6 4, Exit 7 8 Program Structure: 9 socket_server_client/#程序目录10 |--clients/#client程序主目录11 |      |---__init__.py12 |      |---bin/#启用目录13 |       |      |---__INIT__.PY14 |       |      |---socket_client.py# client Launch 15 |      |16 |      |---cfg/#配置文件目录17 |       |      |---__INIT__.PY18 |       |      |---config.py# configuration file 19 |      |20 |      |---core/#主要程序目录21 |       |      |---__INIT__.PY22 |       |      |---client_func.py# main function 23 |      |24 |      |---home/#客户端下载文件目录25 |26 | |--servers/#server程序主目录27 |      |---__init__.py28 |      |---bin/#启用目录29 |       |      |---__INIT__.PY30 |       |      |---registration.py# User Registration 31 |       |      |---socket_server.py# server start 32 33 |      |34 |      |---cfg/#配置文件目录35 |       |      |---__INIT__.PY36 |       |      |---config.py# configuration File 37 |      |38 |      |---core/#主要程序目录39 |       |      |---__INIT__.PY40 |       |      |---server_classc.py# main function 41 |      |42 | |---db/#用户上传文件主目录43 |              |---user_file/#用户上传目录44 | |---user_names# registered user File 45 |

Service side

servers/

bin/

registration.py

 1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 Import socket,os,json,sys,pickle 5 6 Base_dir=os.path.dirna Me (Os.path.dirname (Os.path.abspath (__file__))) #获取相对路径转为绝对路径赋于变量 7 sys.path.append (Base_dir) #增加环境变量 8 from CFG Import Config 9 print (' User Registration '. Center (' = ') ' True:11 user_=input (' Please enter the user name you want to register: '). Strip () User_dir=os.path.join ( Config. User_dir,user_) #拼接用户目录路径13 if Os.path.isdir (user_dir): # Determine if a directory exists in print (' User already exists please re-lose! ')         Continue16 else:17 pwd_=input (' Please enter password: '). Strip () Pwd_two=input (' Please Confirm password: '). Strip (19)                 If Pwd_==pwd_two:20 try:21 os.mkdir (user_dir) #创建目录22 except Exception as e:23 Print (e) continue25 finally:26 file_dir=user_dir+ ' \\user ' #用户目录下 The user name file for the If not Os.path.isfile (config. User_file): with open (config. User_file, ' W ', encoding= ' Utf-8 ') as f:29 F.WRite (' {} ') with open (config.                 User_file, ' r+ ', encoding= ' Utf-8 ') as F:31 Data=eval (F.readline ()) data[user_]=pwd_33 F.seek (0) f.write (str (data)) print (' User [%s] registered successfully! ') %user_) + exit ()
View Code

socket_server.py

1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 import socket,os,json 5 Import sys 6 Base_dir=os.path.dirnam E (Os.path.dirname (Os.path.abspath (__file__))) #获取相对路径转为绝对路径赋于变量 7 sys.path.append (base_dir) #增加环境变量 8  9 from  core.server_class Import listen_func10 s=socket.socket () #定义11 s.bind ((' localhost ', 9000)) #绑定要监听的 Port S.listen (5 ) #对列513 print (' Listening in ') Listen_func (s)

cfg/

config.py

1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 import OS, sys 5 base_dir=os.path.dirname (os.path.dirname (OS . Path.abspath (__file__))) #获取相对路径转为绝对路径赋于变量 6 sys.path.append (base_dir) #增加环境变量 7  8  9 user_dir=base_dir+ ' \db \\user_file\\ ' #定义用户目录文件路径变量10 user_file=base_dir+ ' \db\\user_names ' #定义用户文件路径变量
View Code

Core/

server_class.py

  1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 Import socket,os,json,sys,pickle 5 6 Base_dir=os.path. DirName (Os.path.dirname (Os.path.abspath (__file__))) #获取相对路径转为绝对路径赋于变量 7 sys.path.append (Base_dir) #增加环境变量 8 9 from CFG Import Config ten #用户名检测函数 def open_file_list (Name,pas): #传入当前类 with open (config. User_file, ' R ', encoding= ' Utf-8 ') as F:15 Data=eval (F.readline ()) + if name in data and Pas==data[name]: 1     7 return True else:19 return False #连接类 (socket_server): 24 "Connect Class" "File_path=config." user_dir# User Path variable-def __init__ (self,data,conn): #传入用户名, password is self.         Data=data self.conn=conn def show_process (self,lens): received_size=0# definition Size 33 current_percent=0# current size percent of received_size<lens:35 if Int ((received_size/lens) *100) >curr ent_percent:36 print (' # ', end= ', FLush=true) Notoginseng Current_percent=int ((received_size/lens) *100) New_size=yield Eceived_size+=new_size def ret_l (self): Ret=socket_server.login (self). data["Name"],self. data[' pwd '],self.conn) #用户名检测 return ret-def open_f (Self,ret): #打开目录 file_dir=os.path.join (sock et_server.file_path,ret[' data ' [' User ']) #用户目录 file_name=os.listdir (file_dir) #目录文件列表 f=file_dir+self. data[' filename ']# #上传的文件名 return file_dir,file_name,f# back to "Def Ls_file" (self,data): #查看文件 self . Conn.send (Json.dumps (data[1]). Encode ()) (Send_file): the "if Self". data[' filename '] in data[1]: f=data[0]+ '/' +self.             data[' filename '] File_obj=open (F, "RB") #打开文件 name=file_obj.name.split ('/') [-1] #文件名 59 Sez=os.path.getsize (f) #获取文件大小 print (SEZ) data_header={"actIon ": Put", "filename": Name, "size": SEZ 65} 66                 Self.conn.send (Json.dumps (Data_header). Encode ()) Send related information after #用json serialization in file_obj:68 Self.conn.send (line) #发送数据 the Elif self. data[' filename '].isdigit (): Num=int (self). data[' filename ']) #转为数字 try:73 f=data[0]+ '/' +data[1][num]# File_obj=open                  (F, "RB") #打开文件 name=file_obj.name.split ('/') [-1] #文件名 sez=os.path.getsize (f) #获取文件大小 77 Print (SEZ) data_header={"action": "Put", "Filena" Me ": Name, Bayi" size ": SEZ, Self.conn.send (Json.dumps (data_header). Enc                 Ode ()) #用json after serialization, send related information in file_obj:85 self.conn.send (line) 86 Self.conn.send (JSON.Dumps (f). Encode ()) #发送文件 except Exception as e:88 data={' filename ': False} 89 Self.conn.send (Json.dumps (data). Encode ()) else:91 data={' filename ': False} self.co Nn.send (data) encode ()) Json.dumps def put_file (self,data): #上传文件 94 File_obj=open (data[2], ' WB ') #打开新建 this file 9 5 rece_size=0# defines the file size value of #prten =socket_server.show_process (self. data["Size"]) #prten. __NEXT__ () 98 while rece_size<self.             data["Size"]: #小于接收的文件大小时, RECV_DATA=SELF.CONN.RECV (4096) file_obj.write (recv_data) #写入文件101 Rece_size+=len (Recv_data) #增加文件大小计算102 103 else:104 Print ("file [%s] received!" %self.     data["filename"]) File_obj.flush () 106 file_obj.close () #关闭文件107 108 109 @staticmethod110 def login (name,pas,conn): #用户检测 function 111 try:112 if Open_file_list (name,pas): 113 tag=true 114 error= ' "datas={' user ': name}116 data={' mag ': ' User authentication through ', ' tag ': true}117 Print (Json.dumps (data). Encode ()) 118 conn.send (Json.dumps (data). Encode ()) 119 Els             e:120 Raise Exception (' \033[41;1m user name or password error \033[0m '%name ' 121 except Exception as e:122             Tag=false123 Error=str (e) 124 datas= ' data={' mag ': ' User or password error ', ' tag ': false}126 Print (' Send data%s '%data) 127 conn.send ("Json.dumps") (Encode ()) "{' tag ': tag, ' ERROR ': Error, ' Data ':d atas}129 #监听函数131 def listen_func (s): true:133 conn,client_addr=s.accept () #端口监听中 ....  Returns two values, joins a numbered object, ip134 print (' Get to New connection: ', client_addr) 135 while true:136 data=conn.recv (4096) #接收数据 Instruction 137 print (' Received data: ', ' 138 data= json.loads (Data.decode ()) ') #反序列139 If Len data ==0:  break141           If data[' action ']== ' user ': #如果是用户名, Authenticate \142 serv=socket_server (data,conn) 143 ret =serv.ret_l () 144 if ret[' tag ']:145 pass146 else:147 continue148 14 9 Print (data) if data[' action ']== "put": #如果接收的字典中是put, is to receive 151 Serv=socket_serv                 ER (data,conn) serv.put_file (Serv.open_f (ret)) #调对象方法153 elif data[' action ']== ' get ': #下载154 Serv=socket_server (Data,conn) #实例化155 Serv.send_file (Serv.open_f (ret)) #调 method 156 E Lif data[' action ']== ' ls ': #查看157 serv=socket_server (Data,conn) 158 serv.ls_file (Serv.open_f ( RET)) 159 continue
View Code

Client

clients/

bin/

socket_client.py

  1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 5 import Socket,os,json,sys 6 base_dir=os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) #获取相对路径转为绝对路径赋于变量 7 sys.path.append (Base_dir) #增加环境变量 8 from Core.client _func Import user_pwd 9 #from core.client_func import show_process from CFG import config one #进度条 def show_proc ESS (lens): received_size=0# definition Size current_percent=0# current size percentage of while received_size<lens:17 if Int ((received_size/lens) *100) >current_percent:18 print (' # ', end= ', flush=true) current_perce Nt=int ((received_size/lens) *100) New_size=yield received_size+=new_size Ket () client.connect (' localhost ', 9000), and true:27 data_d=user_pwd (client), if data_d[' tag ': #运行 # User Login Land success while true:30 print ("===== command prompt = = = 31 View catalog file: ls 32 download: Get file name or  File number such as: Get Test.txtor get 1 33 uploader: Put path/filename such as put E:/test.txt 34 exit: Exit ") cho=i             Nput (' instruction >>: '). Strip () Notoginseng if Len (cho) ==0:continue if cho== ' exit ': Exit () #退出指令 39                     Cmd_list=cho.split () If cmd_list[0]== ' put ': #如果等于下载指令 If Len (cmd_list) ==1:42                 Print (' No input related file name ') Continue filename=cmd_list[1] 45 If Os.path.isfile (filename): #如果文件存在 file_obj=open (filename, "RB") #打开文件 Name=f Ile_obj.name.split ('/') [-1] #文件名 #name =filename.split ("\ \") [-1] #文件名 SEZ=OS.PA                         Th.getsize (filename) #获取文件大小 data_header={"action": "Put", 52 "FileName": Name, "size": SEZ-Client . Send (Json.dumps (data_heAder). Encode ()) #用json serialized, send the relevant information in the "file [%s] send ...."%data_header["filename"]) 58                         file_obj:59 Client.send (line) else:61 Print ("file [%s] is sent!" %data_header["filename"]) else:63 print (' The file does not exist ') continue Elif cmd_list[0]== ' get ': #如查等 the upload instruction, if Len (cmd_list) ==1:67 print (' No                 Enter the relevant file name ') continue filename=cmd_list[1] 71 print (filename)                         data_header={"Action": "Get", "filename": filename, 74 "Size": "Client.send" (Json.dumps (Data_header). Encode () After #用json serialization, send related information about the 4096 (DATAS=CLIENT.RECV) #接收数据 instruction data_l= json.loads (datas.Decode ()) #反序列 if not data_l[' filename ': print (' File not present ') 81 Continue File_dir=config. user_dir+data_l["filename"] file_obj=open (File_dir, ' WB ') #打开新建 This file rece_size=0# definition file Size value of prten=show_process (data_l["size"]) prten.__next__ () e_size<data_l["Size"]: #小于接收的文件大小时, RECV_DATA=CLIENT.RECV (4096) FILE_OBJ.W                         Rite (Recv_data) #写入文件 Rece_size+=len (recv_data) #增加文件大小计算 try:92 Prten.send (Len (recv_data)) except stopiteration as e:94 print ( ' 100% ') else:97 print ("file [%s] received!" %data_l["filename"]) 98 File_obj.flush () File_obj.close () #关闭文件100 E Lif cmd_list[0]== ' ls ': #View Catalog Files 101 data_header={102 "action": "LS", 103 "filename": ' , 104 "Size": "}106 client.send (Json.dumps (data_header). Enc Ode ()) #用json after serialization, send related information 107 datas=client.recv (4096) #接收数据 Directive 108 data_l= json.loads (DATAS.D     Ecode ()) #反序列109 for k,v in Enumerate (data_l): Print (' number:%s file name:%s '% (K,V)) 111 112 else:113 print (data_d[' mag ')
View Code

cfg/

config.py

1 #! Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4  5 import OS, sys 6 base_dir=os.path.dirname (Os.path.dirn Ame (Os.path.abspath (__file__))) #获取相对路径转为绝对路径赋于变量 7 sys.path.append (base_dir) #增加环境变量 8  9 user_dir=base_dir+ ' \ Home\\ ' #定义用户目录文件路径变量

Core/

client_func.py

1 #!  Usr/bin/env Python 2 #-*-coding:utf-8-*-3 # Author Calmyan 4 Import socket,os,json,sys 5 #用户名登陆函数 6 def user_pwd (client): 7     user_=input (' Please enter user name: '). Strip () 8     pwd_=input (' Please enter password: '). Strip () 9     data_header={10                 "action": "User ", one                 " name ": user_,12                 " pwd ":p wd_13             }14     client.send (Json.dumps (Data_header). Encode ()) #用json serialized, Send related information     data=client.recv (4096) #接收数据 Directive     data_s=json.loads (Data.decode (' Utf-8 ')) #反序列17     return Data _S18 #进度条21 def show_process (lens):     received_size=0# definition size,     current_percent=0# current size percentage     received_size<lens:25         if Int ((received_size/lens) *100) >current_percent:26             print (' # ', end= ', Flush=true)             Current_percent=int ((received_size/lens) *100)         new_size=yield29         received_size+= New_size
View Code
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.