Python Network Programming 简明教程
Python - FTP
FTP 或文件传输协议是一种著名的网络协议,用于在网络中的计算机之间传输文件。它是在客户端服务器架构上创建的,可以与用户身份验证一起使用。它也可以在没有身份验证的情况下使用,但那样的安全性会比较低。维护当前工作目录和其他标志的 FTP 连接,并且每次传输都需要通过二级连接,数据才会传输。大多数常见的网络浏览器都可以检索托管在 FTP 服务器上的文件。
FTP or File Transfer Protocol is a well-known network protocol used to transfer files between computers in a network. It is created on client server architecture and can be used along with user authentication. It can also be used without authentication but that will be less secure. FTP connection which maintains a current working directory and other flags, and each transfer requires a secondary connection through which the data is transferred. Most common web browsers can retrieve files hosted on FTP servers.
The Methods in FTP class
在 python 中,我们使用 ftplib 模块,该模块具有以下所需方法,以便在传输文件时列出文件。
In python we use the module ftplib which has the below required methods to list the files as we will transfer the files.
Method |
Description |
pwd() |
Current working directory. |
cwd() |
Change current working directory to path. |
dir([path[,…[,cb]]) |
Displays directory listing of path. Optional call-back cb passed to retrlines(). |
storlines(cmd, f) |
Uploads text file using given FTP cmd - for example, STOR file name. |
storbinary(cmd,f[, bs=8192]) |
Similar to storlines() but is used for binary files. |
delete(path) |
Deletes remote file located at path. |
mkd(directory) |
Creates remote directory. |
exception ftplib.error_temp |
Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received.. |
exception ftplib.error_perm |
Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received.. |
connect(host[, port[, timeout]]) |
Connects to the given host and port. The default port number is 21, as specified by the FTP protocol.. |
quit() |
Closes connection and quits. |
以下是以上一些方法的示例。
Below are the examples of some of the above methods.
Listing the Files
下面的示例对 FTP 服务器使用匿名登录并列出当前目录的内容。它通过文件名和目录名进行处理并将它们存储为一个列表。然后打印这些文件和目录。
The below example uses anonymous login to the ftp server and lists the content of the current directory. It treates through the name of the files and directories and stores them as a list. Then prints them out.
import ftplib
ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
- lrwxrwxrwx 1 0 0 1 Nov 13 2012 ftp -> .
- lrwxrwxrwx 1 0 0 3 Nov 13 2012 mirror -> pub
- drwxr-xr-x 23 0 0 4096 Nov 27 2017 pub
- drwxr-sr-x 88 0 450 4096 May 04 19:30 site
- drwxr-xr-x 9 0 0 4096 Jan 23 2014 vol
Changing the Directory
下面的程序使用 ftplib 模块中可用的 cwd 方法来更改目录,然后获取所需的内容。
The below program uses the cwd method available in the ftplib module to change the directory and then fetch the required content.
import ftplib
ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")
data = []
ftp.cwd('/pub/') change directory to /pub/
ftp.dir(data.append)
ftp.quit()
for line in data:
print "-", line
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
- lrwxrwxrwx 1 504 450 14 Nov 02 2007 FreeBSD -> os/BSD/FreeBSD
- lrwxrwxrwx 1 504 450 20 Nov 02 2007 ImageMagick -> graphics/ImageMagick
- lrwxrwxrwx 1 504 450 13 Nov 02 2007 NetBSD -> os/BSD/NetBSD
- lrwxrwxrwx 1 504 450 14 Nov 02 2007 OpenBSD -> os/BSD/OpenBSD
- -rw-rw-r-- 1 504 450 932 Jan 04 2015 README.nluug
- -rw-r--r-- 1 504 450 2023 May 03 2005 WhereToFindWhat.txt
- drwxr-sr-x 2 0 450 4096 Jan 26 2008 av
- drwxrwsr-x 2 0 450 4096 Aug 12 2004 comp
Fetching the Files
在如上所述获取文件列表后,我们可以使用 getfile 方法来获取特定文件。此方法将文件的副本从远程系统移动到发起 FTP 连接的本地系统。
After getting the list of files as shown above, we can fetch a specific file by using the getfile method. This method moves a copy of the file from the remote system to the local system from where the ftp connection was initiated.
import ftplib
import sys
def getFile(ftp, filename):
try:
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
except:
print "Error"
ftp = ftplib.FTP("ftp.nluug.nl")
ftp.login("anonymous", "ftplib-example-1")
ftp.cwd('/pub/') change directory to /pub/
getFile(ftp,'README.nluug')
ftp.quit()
当我们运行上面的程序时,我们发现文件 README.nlug 存在于发起连接的本地系统中。
When we run the above program, we find the file README.nlug to be present in the local system from where the connection was initiated.