In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use python to build a FTP server". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to build a FTP server with python".
First, understand the FTP server
FTP (File transfer Protocol), which runs on the tcp protocol, uses two ports, a data port and a command port, also known as a control port. By default, 20 is the data port and 21 is the control port.
FTP has two transmission modes: active mode and passive mode.
(1) active mode: the client first connects to the command port of the FTP server (default is 21) from any non-special port n (the port greater than 1023, which is also the command port of the client), issues a command to the server, tells the server to use the nasty 1 port as the data port for data transmission, and then listens on the nasty 1 port. When the server receives PORT 1, it returns a "ACK" to the client, then the server connects from its own data port (20) to the data port previously specified by the client, and finally the client returns a "ACK" to the server.
(2) passive mode: in order to solve the problem of the connection initiated by the server to the client, a passive FTP, or PASV, is developed, which is enabled when the client notifies the server that it is in passive mode. In passive mode, both command connections and data connections are initiated by the client. When a FTP connection is opened, the client opens any two unprivileged ports (greater than 1023). The first port connects to port 21 of the server, but unlike the active approach, the client does not submit PORT commands and allows the server to connect to the data port back and forth, but to submit PASV commands. The result is that the server opens any unprivileged port and sends a PORT p command to the client, which then initiates a connection from the local port Number1 to the server port p to transfer data
Summary: active mode is conducive to the management of the FTP server, but not to the management of the client. Because the FTP server attempts to establish a connection with the client's high random port, which is likely to be blocked by the client's firewall. The passive mode is the opposite.
Second, use python to build FTP server
Python needs to use pyftpdlib module to build FTP.
1. Install pyftpdlib module C:UsersLTP > pip3 install pyftpdlibC:UsersLTP > python3-m pyftpdlib-p 21
two。 Locate the directory where the pyftpdlib module source file is located
C:UsersLTP > python3... > import pyftpdlib > pyftpdlib.__path__ ['/ usr/local/python3/lib/python3.7/site-packages/pyftpdlib']
3. Go to the pyftpdlib directory
If you find two files, filesystems.py and handlers.py, perform a backup first.
C:UsersLTP > dir E:PycharmProjectsuntitledproject01venvLibsite-packagespyftpdlib2021/05/15 17:50 .2021 / 05 authorizers.py2021/05/15 15 17:50.. 2017-12-30 16:44 35246 authorizers.py2021/05/15 17:49 24798 filesystems-copy. Py2021/05/15 17:49 24798 filesystems.py2019/10/24 16:26 144635 handlers-copy. Py2019/10/24 16: 26 144635 handlers.py2017/12/30 16:44 36769 ioloop.py2019/10/24 16:26 5823 log.py2019/10/24 16:26 3844 prefork.py2019/10/24 16:26 21658 servers.py2021/05/15 17:45 test2019/10/24 16:26 774 _ compat.py2019/10/24 16:28 2845 _ _ init__.py2018/04/26 18:41 4879 _ _ main__.py2021/05/15 17:46 _ _ pycache__ 12 files 450704 bytes 4 directories 44605644800 available bytes # backup filesystems.py and handlers.py# modify filesystems.py files # change the original "utf-8" to "gbk" "(bytes of gbk type supported by windows) 503 yield line.encode ('gbk' Self.cmd_channel.unicode_errors# modify handlers.py file # modify the original "utf-8" to "gbk" (bytes of gbk type supported by windows) 1413 return bytes.decode ('gbk', self.unicode_errors)
4. Write and run FTP code
# the script is a ftp running on windows. Before running, you need to install the pyftpdlib module, pip3 install pyftpdlib# modifies the filesystems.py file, and modifies the "utf-8" in line 503 to "gbk" (gbk type bytes supported by windows), that is, yield line.encode ('gbk', self.cmd_channel.unicode_errors# modifies the handlers.py file) Change the word "utf-8" in line 1413 to "gbk" (bytes of type gbk supported by windows), that is, return bytes.decode ('gbk', self.unicode_errors) from pyftpdlib.authorizers import DummyAuthorizerfrom pyftpdlib.handlers import FTPHandler,ThrottledDTPHandlerfrom pyftpdlib.servers import FTPServerfrom pyftpdlib.log import LogFormatterimport logging# 1. Log output to file and terminal logger = logging.getLogger ('FTP-LOG') logger.setLevel (logging.DEBUG) cs = logging.StreamHandler () cs.setLevel (logging.INFO) fs = logging.FileHandler (filename='test.log', mode='a') Encoding='utf-8') fs.setLevel (logging.DEBUG) formatter = logging.Formatter ('[% (asctime) s]% (name) s -% (levelname) s:% (message) s') cs.setFormatter (formatter) fs.setFormatter (formatter) logger.addHandler (cs) logger.addHandler (fs) # 2. Instantiate a virtual user, which is the first condition of FTP authorizer = DummyAuthorizer () # 3. Add user permissions and paths. The parameters in parentheses are (user name, password, user directory, permissions). You can add different directories and permissions authorizer.add_user for different users ('user',' 123456 permissions, perm= "elradfmw") # 4. To add an anonymous user, just need the path authorizer.add_anonymous ("dvv /") # 5. Initialize the ftp handle handler = FTPHandlerhandler.authorizer = authorizer# 6. Add the passive port range handler.passive_ports = range (2000 dint 20033) # 7. Upload and download speed setting dtp_handler = ThrottledDTPHandlerdtp_handler.read_limit = 300 * 1024 # 300 kb/sdtp_handler.write_limit = 300 * 1024 # 300 kb/shandler.dtp_handler = dtp_handler# 8. Listen to ip and port. Root user is required in linux to use port 21 server = FTPServer (('0.0.0.0, 21), handler) # 9. Maximum number of connections server.max_cons = 150server.max_cons_per_ip = connections 10. Start the service with printed log information server.serve_forever ()
The meaning of the perm permission parameter in authorizer.add_user ('user',' 123456 permission, "perm= /", "perm"):
1. Read permission:
E: change the file directory
L: list files
R: receive files from the server
2. Write permission
A: file upload
D: delete files
F: file rename
M: create a file
W: write permission
M: file transfer mode (setting file permissions through FTP)
5. Use CMD to log in to FTP authentication
Normal use and authentication
Third, write FTP client programs
Can be used for uploading and downloading files
[root@localhost python] # vim ftp.py#! / bin/env python3#-*-coding: utf-8-*-# Time: 2021-5-15 21 coding Description: FTP CLIENT# File Name: ftp.py# FTP client from ftplib import FTP# 1. Log in to ftpftp = FTP (host='192.168.0.108', user='user', passwd='123456') # to set the encoding mode, because in the windows system Set the encoding method to gbk'ftp.encoding = 'gbk'# switch directory ftp.cwd (' test') # list folder contents ftp.retrlines ('LIST') # or ftp.dir () # download file node.txtftp.retrbinary (' RETR node.txt', open ('node.txt',' wb') .write) # upload file ftpserver.pyftp.storbinary ('STOR ftpserver.py', open (' ftpserver.py') 'rb')) # View the details of the files in the directory for file in ftp.mlsd (path='/test'): print (file)
Execution result:
[root@localhost python] #. / ftp.py
# lists the contents of the test folder
-rw-rw-rw- 1 owner group 1661 May 15 14:19 ftpserver.py
-rw-rw-rw- 1 owner group 12 May 15 14:14 node.txt
# check the details of the files in the directory
('ftpserver.py', {' modify': '20210515142003,' perm': 'radfw',' size': '1661,' type': 'file'})
('node.txt', {' modify': '2021051514442,' perm': 'radfw',' size':'12, 'type':' file'})
[root@localhost python] # ls # node.txt file is downloaded to the client
Ftp.py ftpserver.py node.txt
Verify to the test directory of windows
The ftpserver.py file is uploaded to the server
Thank you for reading, the above is "how to use python to build FTP server" content, after the study of this article, I believe you have a deeper understanding of how to use python to build FTP server this problem, the specific use of the situation also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.