51qsx 发表于 2015-11-30 12:08:50

Python ftplib

  http://automationtesting.sinaapp.com/blog/m_ftplib
  https://docs.python.org/2/library/ftplib.html

概述
  该模块是内置模块,定义了FTP类和一些相关项。FTP类实现了FTP协议的客户端。你可以用它来编程来处理一系列FTP相关的任务。

快速入门





1 >>> from ftplib import FTP
2 >>> ftp = FTP('ftp.debian.org')   # connect to host, default port
3 >>> ftp.login(‘usr', 'pwd')         # anonymous loging, just let usr and pwd empty@
4 '230 Login successful.'
5 >>> ftp.cwd('debian')               # change into "debian" directory
6 >>> ftp.retrlines('LIST')         # list directory contents, same as ftp.dir()
7 -rw-rw-r--    1 1176   1176         1063 Jun 15 10:18 README
8 ...
9 drwxr-sr-x    5 1176   1176         4096 Dec 192000 pool
10 drwxr-sr-x    4 1176   1176         4096 Nov 172008 project
11 drwxr-xr-x    3 1176   1176         4096 Oct 102012 tools
12 '226 Directory send OK.'
13 >>> ftp.retrbinary('RETR README', open('README', 'wb').write)
14 '226 Transfer complete.'
15 >>> ftp.quit()
  

类介绍


[*]class ftplib.FTP(]]]]):
  返回FTP类的新实例。提供host时调用connect(host)。提供user时调用login(user, passwd, acct),passwd和acct在没有提供时默认为空。可选timeout参数指定用于像连接尝试之类阻塞操作的超时描述(如果未指定,则timeout 全局默认超时设置)。超时为2.6加入。


[*]class ftplib.FTP_TLS(]]]]]])
  FTP子类,增加TLS支持到FTP,在RFC4217​http://tools.ietf.org/html/rfc4217.html中描述。TLS的快速了解参见​http://zh.wikipedia.org/wiki/TLS。和通常一样连接到21端口但认证以前已经加密了FTP控制连接。调用prot_p()可以保护数据连接。keyfile和certfile中是可选的 - 它们可以包含PEM格式的私钥和SSL连接的证书链文件名。2.7版本新增。
  示例:



>>> from ftplib import FTP_TLS
>>> ftps = FTP_TLS('ftp.python.org')
>>> ftps.login('usr', 'pwd')         # login anonymously before securing control channel
>>> ftps.prot_p()          # switch to secure data connection
>>> ftps.dir() # list directory content securely
total 9
drwxr-xr-x   8 root   wheel      1024 Jan31994 .
drwxr-xr-x   8 root   wheel      1024 Jan31994 ..
drwxr-xr-x   2 root   wheel      1024 Jan31994 bin
drwxr-xr-x   2 root   wheel      1024 Jan31994 etc
d-wxrwxr-x   2 ftp      wheel      1024 Sep5 13:43 incoming
drwxr-xr-x   2 root   wheel      1024 Nov 171993 lib
drwxr-xr-x   6 1094   wheel      1024 Sep 13 19:07 pub
drwxr-xr-x   3 root   wheel      1024 Jan31994 usr
-rw-r--r--   1 root   root          312 Aug11994 welcome.msg
>>> ftps.quit()
>>>

  我这边试验,ftps = FTP_TLS('ftp.python.org')报错socket.error: Network is unreachable。


[*]exception ftplib.error_reply
  Exception raised when an unexpected reply is received from the server. 从服务器接收到非预期的reply时产生。


[*]exception ftplib.error_temp
  Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received. 接收到临时错误(范围400-499响应代码)。


[*]exception ftplib.error_perm
  Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received. 接收到永久性的错误(范围500-599响应代码)。。


[*]exception ftplib.error_proto
  Exception raised when a reply is received from the server that does not fit the response specifications of the File Transfer Protocol, i.e. begin with a digit in the range 1–5. 不符合FTP响应规格的响应,即1-5开头的数字。


[*]ftplib.all_errors
  The set of all exceptions (as a tuple) that methods of FTP instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the four exceptions listed above as well as socket.error and IOError.FTP示例的异常集合,为元组,包含以上4种异常和socket.error和IOError
  模块netrc可以解析.netrc文件,FTP客户端通常使用.netrc文件加载用于验证信息。python源码中的Tools/scripts/ftpmirror.py可以镜像FTP站点,可以看做本模块的实例。

FTP对象
  方法分为处理文本文件和二进制文件,方法名分别对应lines和binary。


[*]FTP.set_debuglevel(level)
  设置实例的调试级别。默认情况为0,不产生任何调试输出。值为1时会产生适量的调试输出,一般每次请求一行。 2或更高的值会产生大量调试输出,记录控制连接上发送和接收的每行。


[*]FTP.connect(host[, port[, timeout]])
  连接到指定的host和port。默认端口号为21。此函数每个实例只调用一次,如果在创建实例时指定了host则不能调用。所有其他的方法经建立连接后使用。在2.6版本:加入超时。


[*]FTP.getwelcome()
  Return the welcome message sent by the server in reply to the initial connection. (This message sometimes contains disclaimers or help information that may be relevant to the user.)


[*]FTP.login(]])
  登录为user。passwd和acct参数可选,默认为空字符串。如果没有指定用户,默认为'anonymous'。如果用户是'anonymous',默认的passwd是'anonymous@'。此函数每个实例只调用一次,acct为"accounting information",很少有系统实现。


[*]FTP.abort()
  中止正在传输的文件,使用未必总是有效,但值得一试。


[*]FTP.sendcmd(command)
  发送简单的命令字符串到服务器,并返回响应字符串。


[*]FTP.voidcmd(command)
  发送一个简单的命令字符串到服务器,并处理响应。返回None如果接收到成功(范围200-299码。否则报error_reply。


[*]FTP.retrbinary(command, callback[, maxblocksize[, rest]])
  用二进制传输方式获取文件。命令应该是适当的RETR命令:'RETR filename'。每次接收到数据块时会调用callback函数。


[*]FTP.retrlines(command[, callback])
  用文本传输方式获取文件。命令应该是适当的RETR命令或LIST, NLST,MLSD。LIST获取文件和信息列表,NLST 获取文件名列表,一些服务器上MLSD返回可读文件和信息的列表。每次接收到一行时会调用callback函数,默认为打印到sys.stdout。


[*]FTP.set_pasv(boolean)
  是否启用"passive"模式,默认为开启。


[*]FTP.storbinary(command, file[, blocksize, callback, rest])
  二进制传输方式存储文件。command是适当的STOR命令:"STOR filename"。file是打开的文件对象,可以使用其read()方法读取blocksize的数据直到EOF。blocksize默认为8192。2.6版本:callback添加。2.7版本:rest添加。


[*]FTP.storlines(command, file[, callback])
  文本传输方式存储文件。command是适当的STOR命令:"STOR filename"。2.6版本:callback添加。


[*]FTP.transfercmd(cmd[, rest])
  在数据连接启动传输。如果传输处于active状态,发送EPRT或PORT命令,传输CMD命令,并接受连接。如果服务器是passive的,发送EPSV或PASV命令,连接再开始传输命令。无论哪种方式都返回套接字连接。
  如果有可选的rest,以rest为参数发送REST命令到服务器。rest通常是请求文件中的字节偏移量,告诉服务器重新启动时所要求的偏移发送文件的字节数,跳过最初的字节。但是请注意, RFC 959中只要求休息是包含在可打印范围从ASCII码33为ASCII码126个字符的字符串。transfercmd()方转换rest为字符串,但不检查字符串的内容。如果服务器不能识别REST命令,将引发异常error_reply。如果发生这种情况,只需不附加rest调用transfercmd() 。


[*]FTP.ntransfercmd(cmd[, rest])
  像transfercmd(),但返回元组,包含数据连接,预期数据大小。如果预期的大小不能计算,返回None。


[*]FTP.nlst(argument[, ...])
  返回NLST命令返回的文件名列表。可选参数argument是目录(默认为当前服务器的目录)。多多个参数可以用来传递非标准选项给NLST命令。


[*]FTP.dir(argument[, ...])
  通过LIST命令返回目录列表,打印到标准输出。可选参数argument是目录(默认为当前服务器的目录)。多个参数可以用来传递非标准选项给LIST命令。如果最后一个参数是函数,用来作为retrlines()的回调函数;默认打印到sys.stdout。此方法返回None。


[*]FTP.rename(fromname, toname)
  重命名文件。


[*]FTP.cwd(pathname)
  设置当前目录。


[*]FTP.mkd(pathname)
  创建新目录。


[*]FTP.pwd()
  返回当前目录。


[*]FTP.rmd(dirname)
  删除目录。


[*]FTP.size(filename)
  返回文件大小。不成功返回None。SIZE不标准,但是多数服务器支持。


[*]FTP.quit()
  发送QUIT命令到服务器并关闭连接。这是礼貌的方式来关闭连接,但是如果服务器返回错误给QUIT命令时可能会引发异常。这意味着在调用close()方法而呈现的FTP实例无用的后续调用(见下文) 。


[*]FTP.close()
  单方面关闭连接。不能多次关闭连接或重开连接。

FTP_TLS对象
  FTP_TLS继承了FTP,增加了如下:


[*]FTP_TLS.ssl_version:SSL版本,默认为TLSv1


[*]FTP_TLS.auth():使用TLS或SSL(使用何种处决于ssl_version)建立安全控制连接。


[*]FTP_TLS.prot_p():建立安全的数据连接。


[*]FTP_TLS.prot_c():建立明文数据连接。

附:模板



1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 import ftplib
4 import os
5 import socket
6
7 HOST = 'ftp.mozilla.org'
8 DIRN = 'pub/mozilla.org/webtools'
9 FILE = 'bugzilla-3.6.7.tar.gz'
10 def main():
11   try:
12         f = ftplib.FTP(HOST)
13   except (socket.error, socket.gaierror):
14         print 'ERROR:cannot reach " %s"' % HOST
15         return
16   print '***Connected to host "%s"' % HOST
17
18   try:
19         f.login()
20   except ftplib.error_perm:
21         print 'ERROR: cannot login anonymously'
22         f.quit()
23         return
24   print '*** Logged in as "anonymously"'
25   try:
26         f.cwd(DIRN)
27   except ftplib.error_perm:
28         print 'ERRORL cannot CD to "%s"' % DIRN
29         f.quit()
30         return
31   print '*** Changed to "%s" folder' % DIRN
32   try:
33         #传一个回调函数给retrbinary() 它在每接收一个二进制数据时都会被调用
34         f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
35   except ftplib.error_perm:
36         print 'ERROR: cannot read file "%s"' % FILE
37         os.unlink(FILE)
38   else:
39         print '*** Downloaded "%s" to CWD' % FILE
40   f.quit()
41   return
42
43 if __name__ == '__main__':
44   main()
  
页: [1]
查看完整版本: Python ftplib