Use python3 to implement ftp service function instances (server ForLinux)

Source: Internet
Author: User
This article mainly introduces python3's implementation of ftp service functions and server ForLinux, which has some reference value. interested friends can refer to this article to introduce python3's ftp service functions, server For Linux has some reference value. if you are interested, you can refer

The example in this article shares with you the code for implementing ftp service functions in python3 for your reference. the specific content is as follows:

Function introduction:

Executable commands:

Ls
Pwd
Cd
Put
Rm
Get
Mkdir

1. user encryption authentication

2. allow multiple users to log on simultaneously

3. each user has his/her own home directory and can only access his/her home directory.

4. run the command in your home directory and switch the directory at will.

5. upload and download files are allowed, and the files are consistent.

6. display the 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 ): ''' authentication username and password ''' pai_dic = args [0] username = pai_dic ["username"] password = pai_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' % username) 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 el Se: self. request. send ('1 '. encode () data = "% s login failed" % username self. loging (data) f. close ####################################### ### def get (self, * args): ''' transfer the file to the client ''' request_code = {'0': 'File is ready to get', '1': 'file not found! '} Performance_dic = args [0] self. loging (json. dumps (pai_dic) filename = pai_dic ["filename"] if OS. path. isfile (filename): self. request. send ('0 '. encode ('utf-8') # confirm that the file has self. request. recv (1, 1024) self. request. send (str (OS. stat (filename ). st_size ). encode ('utf-8') self. request. recvs (1024) m = hashlib. md5 () f = open (filename, 'RB') for line in f: m. update (line) self. request. send (line) self. request. send (m. hexdige St (). encode ('utf-8') print ('From server: Md5 value has been sended! ') F. close () else: self. request. send ('1 '. encode ('utf-8 ')) ######################################## ### def cd (self, * args): ''' run the cd command ''' user_current_dir = OS. popen ('pwd '). read (). strip () 1__dic = args [0] self. loging (json. dumps (pai_dic) path = pai_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. reque St. 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_home_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 Please confirm whether to rm ', '1': 'file not found! '} Performance_dic = args [0] self. loging (json. dumps (pai_dic) filename = pai_dic ['filename'] if OS. path. exists (filename): self. request. send ('0 '. encode ("UTF-8") # check whether the file has client_response = self. request. recv (1, 1024 ). 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). encode ("UTF-8") self. loging ('file % s not deleted! '% Filename) else: self. request. send ('1 '. encode ("UTF-8 ")) ######################################## def pwd (self, * args): '''run the pwd command ''' into _dic = args [0] self. loging (json. dumps (pai_dic) server_response = OS. popen ('pwd '). read (). strip (). encode ("UTF-8") self. request. send (server_response) ######################################## ##### def ls (self, * args): '''execute the ls name ''' into _dic = args [0] self. loging (json. Dumps (pai_dic) path = pai_dic ['path'] cmd = 'ls-l % s' % path server_response = OS. popen (cmd ). read (). encode ("UTF-8") self. request. send (server_response) ######################################## #### def put (self, * args): '''receive client file' ''' into _dic = args [0] self. loging (json. dumps (pai_dic) filename = pai_dic ["filename"] filesize = pai_dic ["size"] if OS. path. isfile (filename): f = open (filename + '. new ', 'WB ') else: f = open (filename, 'WB') request_code = {'000000': 'Ready to recceive data! ', '000000':' Not ready to received data! '} Self. request. send ('20140901 '. encode () receive_size = 0 while True: if receive_size <filesize: data = self. request. recvs (1024) f. write (data) receive_size + = len (data) else: data = "File % s has been uploaded successfully! "% Filename self. loging (data) print (data) break ####################################### ######### def mkdir (self, * args): request_code = {'0': 'directory has been made! ', '1': 'directory is aleady exist! '} Performance_dic = args [0] self. loging (json. dumps (1__dic) dir_name = 1__dic ['dir _ name'] if OS. path. exists (dir_name): self. request. send ('1 '. encode ("UTF-8") else: OS. popen ('mkdir % s' % dir_name) self. request. send ('0 '. encode ("UTF-8 ")) ######################################## ##### def loging (self, data): '''logging ''' 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 address you used for this access is % s" % self. client_address [0]) # localtime = time. asctime (time. localtime (time. time () # print (localtime) while True: try: self. data = self. request. recv (1, 1024 ). decode () # print (self. data) pai_dic = json. loads (self. data) action = pai_dic ["action"] # print ("user request % s" % action) if hasattr (self, action): func = getattr (self, action) func (performance_dic) doesn t 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 ('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 f = open (userdb_file, 'w') json. dump (dict, f) f. close () return userdb_file

Directory structure:

The above describes how to use python3 to implement ftp service function instances (Server For Linux). For more information, see other related articles in the first PHP community!

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.