This article mainly introduces the PYTHON3 implementation of the FTP service function, server for Linux, with a certain reference value, interested in small partners can refer to
The example of this article for you to share the PYTHON3 implementation of the FTP service function of the specific code for your reference, the specific content as follows
Feature Description:
Executable commands:
Ls
Pwd
Cd
Put
Rm
Get
Mkdir
1, User encryption authentication
2. Allow multiple users to log in at the same time
3, each user has their own home directory, and can only access their own home directory
4, run in their own home directory at random to switch directories
5. Allow uploading and downloading files, and the file is consistent
6. Show progress bar during transmission
Server main code:
# Author by andy# _*_ coding:utf-8 _*_import OS, sys, JSON, hashlib, socketserver, Timebase_dir = Os.path.dirname (Os.path. DirName (Os.path.abspath (file))) Sys.path.append (Base_dir) from conf import Userdb_setclass ftp_server (socketserver. Baserequesthandler): User_home_dir = ' def auth (self, *args): ' Verify user name and password ' ' cmd_dic = args[0] Username = cmd_dic["Use Rname "] Password = cmd_dic[" password "] f = open (Userdb_set.userdb_set (), ' r ') User_info = Json.load (f) if username in User_info.keys (): if password = = User_info[username]: self.request.send (' 0 '. Encode ()) Os.chdir ('/home/%s '% Userna Me) Self.user_home_dir = Os.popen (' pwd '). Read (). strip () data = "%s login successed"% username self.loging (data) Else:self.request.send (' 1 '. Encode ()) data = "%s Login Failed"% username self.loging (data) F.close else: Self.request.send (' 1 '. Encode ()) data = "%s Login Failed"% username self.loging (data) F.close ################### ####################### def get (sElf, *args): "Transfer file to Client" ' Request_code = {' 0 ': ' File is ready to get ', ' 1 ': ' File not found! ' } cmd_dic = Args[0] Self.loging (Json.dumps (cmd_dic)) filename = cmd_dic["filename"] if os.path.isfile (filename): sel F.request.send (' 0 '. Encode (' Utf-8 ')) # confirms that the file exists Self.request.recv (1024x768) self.request.send (str (os.stat (filename). st_ Size). Encode (' Utf-8 ')) Self.request.recv (1024x768) m = Hashlib.md5 () f = open (filename, ' RB ') for line in F:M.UPDA Te (line) self.request.send (line) Self.request.send (M.hexdigest () encode (' Utf-8 ')) print (' from SERVER:MD5 value have been sended! ') F.close () else:self.request.send (' 1 '. Encode (' Utf-8 ')) ########################################### def CD (self, *arg s): ' Execute CD command ' ' User_current_dir = Os.popen (' pwd '). Read (). Strip () Cmd_dic = Args[0] Self.loging (Json.dumps (cmd_dic)) Path = cmd_dic[' path '] if Path.startswith ('/'): If Self.user_home_dir in Path:os.chdir (path) New_dir = Os.popen (' pwd '). Read () user_current_dIR = New_dir self.request.send (' Change dir successfully! '). Encode ("Utf-8")) data = ' Change dir successfully! ' Self.loging (data) elif os.path.exists (path): Self.request.send (' Permission denied! '. Encode ("Utf-8")) data = ' Permission denied! ' Self.loging (data) else:self.request.send (' Directory not found! '). Encode ("Utf-8")) data = ' Directory not found! ' Self.loging (data) elif os.path.exists (path): Os.chdir (path) New_dir = Os.popen (' pwd '). Read (). Strip () if Self.user_h Ome_dir in New_dir:self.request.send (' Change dir successfully! '. Encode ("Utf-8")) User_current_dir = New_dir data = ' Change dir successfully! ' Self.loging (data) Else:os.chdir (user_current_dir) self.request.send (' Permission denied! '. Encode ("Utf-8")) data = ' Permission denied! ' Self.loging (data) else:self.request.send (' Directory not found! '). Encode ("Utf-8")) data = ' Directory not found! ' Self.loging (data) ########################################### def RM (selF, *args): Request_code = {' 0 ': ' File Exist,and ' confirm whether to RM ', ' 1 ': ' File not found! ' } cmd_dic = Args[0] Self.loging (Json.dumps (cmd_dic)) filename = cmd_dic[' filename '] if os.path.exists (filename): sel F.request.send (' 0 '. Encode ("Utf-8")) # Verify that the file exists Client_response = SELF.REQUEST.RECV (1024x768). Decode () if client_response = = ' 0 ': Os.popen (' rm-rf%s '% filename) self.request.send ((' File%s has been deleted! '% filename). Encode ("Utf-8")) Self.loging (' file%s has been deleted! '% filename) else:self.request.send ((' file%s not deleted! '% filename). enco De ("Utf-8")) self.loging (' File%s not deleted! '% filename) else:self.request.send (' 1 '. Encode ("Utf-8")) ######### ############################### def pwd (self, *args): ' Execute pwd command ' ' cmd_dic = args[0] Self.loging (Json.dumps (cmd_dic)) Server_response = Os.popen (' pwd '). Read (). strip (). Encode ("Utf-8") self.request.send (server_response) ############## ############################### def ls (self, *args): ' Execute ls ' named ' ' Cmd_dic = args[0] Self.loging (Json.dumps (cmd_dic)) path = cmd_dic[' path '] cmd = ' ls-l%s '% p Ath Server_response = os.popen (cmd). read (). Encode ("Utf-8") self.request.send (server_response) ##################### ####################### def put (self, *args): ' Receive client file ' ' Cmd_dic = args[0] Self.loging (Json.dumps (cmd_dic)) Filenam E = cmd_dic["filename"] filesize = cmd_dic["Size"] if os.path.isfile (filename): f = open (filename + '. New ', ' WB ') Els e:f = open (filename, ' wb ') Request_code = {' £ º ': ' Ready to recceive data! ', ' "": ' Not ready to received data! ' } self.request.send (' $ '. Encode ()) Receive_size = 0 while true:if receive_size < Filesize:data = self.requ EST.RECV (1024x768) f.write (data) Receive_size + = len (data) Else:data = "File%s has been uploaded successfully!"% FileName self.loging (data) print break ################################################ def mkdir (self, *args): Request_code = {' 0 ': ' Directory has been made! ', ' 1 ': ' Directory is aleady exist! ' } cmd_dic = Args[0] Self.loging (Json.dumps (cmd_dic)) Dir_name = cmd_dic[' dir_name '] if os.path.exists (dir_name): Sel F.request.send (' 1 '. Encode ("Utf-8")) Else:os.popen (' mkdir%s '% dir_name) self.request.send (' 0 '. Encode ("Utf-8")) # # ########################################### def loging (self, data): ' log record ' localtime = Time.asctime ( Time.localtime (Time.time ())) Log_file = '/root/ftp/ftpserver/log/server.log ' with open (log_file, ' a ', encoding= ' Utf-8 ') as F:f.write ('%s--> '% localtime + data + ' \ n ') ############################################## def handle ( Self): # print ("The IP you used for this visit is:%s"%self.client_address[0]) # localtime = Time.asctime (Time.localtime (Time.time ())) # PRI NT (localtime) while True:try:self.data = Self.request.recv (1024x768). Decode () # # print (self.data) Cmd_dic = JSO N.loads (self.data) action = cmd_dic["action"] # print ("User request%s"%action) if hasattr (self, ACtion): func = GetAttr (self, Action) func (Cmd_dic) except Exception as E:self.loging (str (e)) Breakdef run ( ): HOST, PORT = ' 0.0.0.0 ', 6969 print ("The server is Started,and listenning at PORT 6969") Server = Socketserver. Threadingtcpserver (HOST, PORT), Ftp_server) Server.serve_forever () if name = = ' main ': Run ()
Set User Password code:
#Author by andy#_*_ coding:utf-8 _*_import os,json,hashlib,sysbase_dir = Os.path.dirname (Os.path.dirname ( Os.path.abspath (file)) Userdb_file = base_dir+ "\data\\userdb" # print (userdb_file) def userdb_set (): If Os.path.isfile (userdb_file): # Print (userdb_file) return userdb_file else: print (' Please create a user for your server first! ') user_data = {} dict={} exit_flags = True while exit_flags: username = input ("Please input Username: ") if username! = ' exit ': password = input (" Please input Passwod: ") if password! = ' exit ': User_data.update ({Username:password}) m = Hashlib.md5 () # m.update (' hello ') # Print (M.hexdigest ()) For i in User_data: # Print (I,user_data[i]) m.update (User_data[i].encode ()) dict.update ({i: M.hexdigest ()}) else: break else: break f = open (Userdb_file, ' W ') json.dump (dict,f ) F.close () return userdb_file
Directory structure: