Python implements the FTP server service, and python implements the ftp server

Source: Internet
Author: User

Python implements the FTP server service, and python implements the ftp server

Active and passive modes of FTP services

Before starting, let's talk about the FTP active mode and passive mode. The difference between the two is that the two images may be clearer:

Active Mode:

Active mode work process:

1. The client initiates a connection to port 21 of the server using random non-privileged port N, which is a port greater than 1024.

2. The client starts listening to port N + 1;

3. The server actively connects to port N + 1 of the client with Port 20.

Advantages of the Active Mode:

The server configuration is simple, which facilitates server security management. The server only needs to open port 21.

Disadvantages of Active Mode:

If the firewall is enabled on the client or the client is in the Intranet (after the NAT Gateway), the connection initiated by the server to the client port may fail.

Passive Mode:

Passive Mode:

1. The client connects to port 21 of the server with random non-privileged ports

2. The server enables a non-privileged port as a passive port and returns it to the client.

3. The client actively connects to the server's passive port with a port of non-privilege + 1

Disadvantages of passive mode:

Server Configuration Management is a little complicated, which is not conducive to security. The server must open a random high port so that the client can connect. Therefore, Most FTP service software can manually configure the range of passive ports.

Advantages of passive mode: no requirements for the Client Network Environment

After learning about FTP, you can use python to implement FTP services.

Preparations

Python version: python 3.4.3

Installation module pyftpdlib

pip3 install pyftpdlib

Create Code File FtpServer. py

Code

Implement simple local verification

From pyftpdlib. authorizers import DummyAuthorizerfrom pyftpdlib. handlers import FTPHandlerfrom pyftpdlib. servers import FTPServer # instantiate a virtual user. This is the top condition for FTP verification. authorizer = DummyAuthorizer () # Add the user permission and path. The parameters in the brackets are (user name, password, user directory, and permission) authorizer. add_user ('user', '000000', '/home/', perm = 'elradfmw ') # To add an anonymous user, you only need to go to authorizer. add_anonymous ('/home/huangxm') # initialize ftp handle handler = FTPHandlerhandler. authorizer = authorizer # listens to ip addresses and ports. Because non-root users in linux cannot use port 21, I use port 2121 server = FTPServer ('192. 168.0.108 ', 2121), handler) # start to serve the server. serve_forever ()

Enable Service

$ Python FtpServer. py

Test:

Enter an incorrect password and try:

Unable to log on because the verification fails.

But this seems to be the active ftp mode. How can we implement the passive mode?

Use the following code to add a passive Port:

Handler. passive_ports = range (2000,2333)

Complete code:

From pyftpdlib. authorizers import DummyAuthorizerfrom pyftpdlib. handlers import FTPHandlerfrom pyftpdlib. servers import FTPServer # instantiate a virtual user. This is the top condition for FTP verification. authorizer = DummyAuthorizer () # Add the user permission and path. The parameters in the brackets are (user name, password, user directory, and permission) authorizer. add_user ('user', '000000', '/home/', perm = 'elradfmw ') # To add an anonymous user, you only need to go to authorizer. add_anonymous ('/home/huangxm') # initialize ftp handle handler = FTPHandlerhandler. authorizer = authorizer # Add the passive port range handler. passive_ports = range (2000,233 3) # Listening ip address and port server = FTPServer ('123. 168.0.108 ', 2121), handler) # start to serve the server. serve_forever ()

Enable the Service to view the passive port information:

$ python FtpServer.py [I 2017-01-11 15:18:37] >>> starting FTP server on 192.168.0.108:2121, pid=46296 <<<[I 2017-01-11 15:18:37] concurrency model: async[I 2017-01-11 15:18:37] masquerade (NAT) address: None[I 2017-01-11 15:18:37] passive ports: 2000->2332

FTP user management:

Through the above practice, the FTP server can already work normally, but what if many FTP users are needed? Does each user write it again?

In fact, we can define a user File user. py

# Username and password permission directory # root 12345 elradfmwM/homehuangxm 12345 elradfmwM/home

Traverse the file and Add rows not starting with # To the user_list list.

Complete code:

From pyftpdlib. authorizers import DummyAuthorizerfrom pyftpdlib. handlers import FTPHandlerfrom pyftpdlib. servers import FTPServerdef get_user (userfile): # define a user list user_list = [] with open (userfile) as f: for line in f: print (len (line. split () if not line. startswith ('#') and line: if len (line. split () = 4: user_list.append (line. split () else: print ("user. conf configuration error ") return user_list # instantiate a virtual user. This is the first condition for FTP verification. authorizer = DummyAuthorizer () # Add the user permission and path. The parameters in the brackets are (username, password, user directory, permission) # authorizer. add_user ('user', '000000', '/home/', perm = 'elradfmw ') user_list = get_user ('/home/huangxm/test_py/FtpServer/user. conf ') for user in user_list: name, passwd, permit, homedir = user try: authorizer. add_user (name, passwd, homedir, perm = permit) Does T Exception as e: print (e) # To add anonymous users, you only need to path authorizer. add_anonymous ('/home/huangxm') # initialize ftp handle handler = FTPHandlerhandler. authorizer = authorizer # Add the passive port range handler. passive_ports = range (2000,233 3) # Listening ip address and port server = FTPServer ('123. 168.0.108 ', 2121), handler) # start to serve the server. serve_forever ()

The FTP service has been completed.

Standardize the code

First, create the conf directory to store settings. py and user. py.

Directory structure (not required in cache ):

Setting. py

Ip = '0. 0.0.0 'port = '000000' # upload speed: 2121 KB/smax_upload = 300*1024 # download speed: 300 KB/smax_download = 1024*150 # maximum number of connections max_cons = # maximum number of IP addresses max_per_ip = 10 # passive port range, note that the number of passive ports is greater than the maximum number of IP addresses. Otherwise, passive_ports = (2000,220 0) may fail to be connected) # enable Anonymous Access on | offenable_anonymous = 'off' # anonymous user directory anonymous_path = '/home/huangxm' # enable log on | offenable_logging = 'off' # Log File loging_name = 'pyftp. log' # Welcome Message welcome_msg = 'Welcome to my ftp'

User. py

# Username and password permission directory # root 12345 elradfmwM/home/huangxm 12345 elradfmwM/home/test 12345 elradfmwM/home/huangxm

FtpServer. py

From pyftpdlib. authorizers import DummyAuthorizerfrom pyftpdlib. handlers import FTPHandler, ThrottledDTPHandlerfrom pyftpdlib. servers import FTPServerfrom conf import settingsimport loggingdef get_user (userfile): # define a user list user_list = [] with open (userfile) as f: for line in f: if not line. startswith ('#') and line: if len (line. split () = 4: user_list.append (line. split () else: print ("user. conf configuration error ") return user_listdef ftp_server (): # instantiate a virtual user. This is the first condition for FTP verification. authorizer = DummyAuthorizer () # Add User Permissions and paths, the parameters in the brackets are (user name, password, user directory, permission) # authorizer. add_user ('user', '000000', '/home/', perm = 'elradfmw ') user_list = get_user ('conf/user. py ') for user in user_list: name, passwd, permit, homedir = user try: authorizer. add_user (name, passwd, homedir, perm = permit) Does T Exception as e: print (e) # To add anonymous users, you only need to path if settings. enable_anonymous = 'on': authorizer. add_anonymous (settings. anonymous_path) # Set the download speed to dtp_handler = ThrottledDTPHandler dtp_handler.read_limit = settings. max_download dtp_handler.write_limit = settings. max_upload # initialize ftp handle handler = FTPHandler handler. authorizer = authorizer # log record if settings. enable_logging = 'on': logging. basicConfig (filename = settings. loging_name, level = logging. INFO) # handler. banner = settings. welcome_msg # Add the passive port range handler. passive_ports = range (settings. passive_ports [0], settings. passive_ports [1]) # Listening ip address and port server = FTPServer (settings. ip, settings. port), handler) # maximum number of connections server. max_cons = settings. max_cons server. max_cons_per_ip = settings. max_per_ip # Start Service print ('start Service') server. serve_forever () if _ name _ = "_ main _": ftp_server ()

Finally, let's talk about permission issues.

Read Permission:

E Change file directory
L List objects
R Receiving files from the server

Write Permission:

A File Upload
D Delete an object
F File rename
M Create a file
W Write Permission
M File Transfer Mode (set file permissions through FTP)

M example:

Check the permissions on the server:

You can see that the permission has been modified.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.