How to implement FTP server service in Python (Collection)
This article mainly introduces the method of implementing FTP server in python. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look.
Active mode and passive mode of FTP service
Before we start, let’s talk about the active mode and passive mode of FTP. The difference between them may be more clear by using two pictures:
Active mode:
Active mode working process:
1. The client initiates a connection to the server port 21 using a random non-privileged port N, which is a port greater than 1024.
2. The client starts listening to port N+1;
3. The server will actively connect to the client’s N+1 port through port 20.
Advantages of active mode:
The server configuration is simple, which is conducive to server security management. The server only needs to open port 21
Active mode Disadvantages:
If the client has a firewall turned on, or the client is on the intranet (behind a NAT gateway), the connection initiated by the server to the client port may fail
Passive Mode:
Passive mode working process:
1. The client connects to port 21 of the server through a random unprivileged port
2. The server opens an unprivileged port as a passive port and returns it to the client
3. The client actively connects to the server's passive port using the unprivileged port + 1 port
Disadvantages of passive mode:
Server configuration management is slightly complicated, which is not conducive to security. The server needs to open random high-level ports so that clients can connect, so most FTP service software can manually configure the passive port range
Passive Advantages of the mode: There are no requirements for the client network environment
After understanding FTP, start using python to implement FTP services
Preparation work
This The python version used for the first time: python 3.4.3
Install the module pyftpdlib
##
pip3 install pyftpdlib
Implement simple local verification
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer #实例化虚拟用户,这是FTP验证首要条件 authorizer = DummyAuthorizer() #添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限) authorizer.add_user('user', '12345', '/home/', perm='elradfmw') #添加匿名用户 只需要路径 authorizer.add_anonymous('/home/huangxm') #初始化ftp句柄 handler = FTPHandler handler.authorizer = authorizer #监听ip 和 端口,因为linux里非root用户无法使用21端口,所以我使用了2121端口 server = FTPServer(('192.168.0.108', 2121), handler) #开始服务 server.serve_forever()
Start the service
$python FtpServer.pyTest Try:Add passive ports through the following code:
handler.passive_ports = range(2000, 2333)Full code:from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer #实例化虚拟用户,这是FTP验证首要条件 authorizer = DummyAuthorizer() #添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限) authorizer.add_user('user', '12345', '/home/', perm='elradfmw') #添加匿名用户 只需要路径 authorizer.add_anonymous('/home/huangxm') #初始化ftp句柄 handler = FTPHandler handler.authorizer = authorizer #添加被动端口范围 handler.passive_ports = range(2000, 2333) #监听ip 和 端口 server = FTPServer(('192.168.0.108', 2121), handler) #开始服务 server.serve_forever()
$ 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? Should each user write it once? In fact, we can define a user file user.py#用户名 密码 权限 目录 # root 12345 elradfmwM /home huangxm 12345 elradfmwM /home
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler from pyftpdlib.servers import FTPServer def get_user(userfile): #定义一个用户列表 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配置错误") return user_list #实例化虚拟用户,这是FTP验证首要条件 authorizer = DummyAuthorizer() #添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限) #authorizer.add_user('user', '12345', '/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) except Exception as e: print(e) #添加匿名用户 只需要路径 authorizer.add_anonymous('/home/huangxm') #初始化ftp句柄 handler = FTPHandler handler.authorizer = authorizer #添加被动端口范围 handler.passive_ports = range(2000, 2333) #监听ip 和 端口 server = FTPServer(('192.168.0.108', 2121), handler) #开始服务 server.serve_forever()
Standardize the code
First create the conf directory to store settings.py and user.pyDirectory structure (don’t worry about the cache):ip = '0.0.0.0' port = '2121' #上传速度 300kb/s max_upload = 300 * 1024 #下载速度 300kb/s max_download = 300 * 1024 #最大连接数 max_cons = 150 #最多IP数 max_per_ip = 10 #被动端口范围,注意被动端口数量要比最大IP数多,否则可能出现无法连接的情况 passive_ports = (2000, 2200) #是否开启匿名访问 on|off enable_anonymous = 'off' #匿名用户目录 anonymous_path = '/home/huangxm' #是否开启日志 on|off enable_logging = 'off' #日志文件 loging_name = 'pyftp.log' #欢迎信息 welcome_msg = 'Welcome to my ftp'
#用户名 密码 权限 目录 #root 12345 elradfmwM /home/ huangxm 12345 elradfmwM /home/ test 12345 elradfmwM /home/huangxm
##
from pyftpdlib.authorizers import DummyAuthorizer from pyftpdlib.handlers import FTPHandler, ThrottledDTPHandler from pyftpdlib.servers import FTPServer from conf import settings import logging def get_user(userfile): #定义一个用户列表 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配置错误") return user_list def ftp_server(): #实例化虚拟用户,这是FTP验证首要条件 authorizer = DummyAuthorizer() #添加用户权限和路径,括号内的参数是(用户名, 密码, 用户目录, 权限) #authorizer.add_user('user', '12345', '/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) except Exception as e: print(e) #添加匿名用户 只需要路径 if settings.enable_anonymous == 'on': authorizer.add_anonymous(settings.anonymous_path) #下载上传速度设置 dtp_handler = ThrottledDTPHandler dtp_handler.read_limit = settings.max_download dtp_handler.write_limit = settings.max_upload #初始化ftp句柄 handler = FTPHandler handler.authorizer = authorizer #日志记录 if settings.enable_logging == 'on': logging.basicConfig(filename=settings.loging_name, level=logging.INFO) #欢迎信息 handler.banner = settings.welcome_msg #添加被动端口范围 handler.passive_ports = range(settings.passive_ports[0], settings.passive_ports[1]) #监听ip 和 端口 server = FTPServer((settings.ip, settings.port), handler) #最大连接数 server.max_cons = settings.max_cons server.max_cons_per_ip = settings.max_per_ip #开始服务 print('开始服务') server.serve_forever() if __name__ == "__main__": ftp_server()
Finally, let’s talk about the permission issue
Read permission:
Change file directory | |
List files | |
Receive files from server |
d | |
f | |
m | |
w | |
M | |
The above is the detailed content of How to implement FTP server service in Python (Collection). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
