Click to Visit Homepage : zzyzz.top


FTP - File Transfer Protocol

 1 FTP - File Transfer Protocol
 2     FTP 实际上使用了两个 TCP 链接. 一个作为控制信道用, 主要传输一些指令和响应,
 3     比如 ACK 或 错误码. 另一个链接是数据信道, 用来传输文件和一些诸如目录列表的
 4     信息等.
 5 
 6     from ftplib import FTP, all_errors
 7     FtpServerAddr = ''
 8     user = ''
 9     PW = ''
10     acct = ''
11 
12     FH = FTP(FtpServerAddr)
13     FH.login(user, PW, acct) # 不带参数表示 anonymous 登入
14 
15     FH.getwelcome()  # 获取问候语
16     FH.pwd()         # 获取当前工作目录
17     FH.cwd()         # 更换工作目录
18     FH.retrlines('cmd', 'callable')    # 以 ASCII 模式下载, 文件被一行一行的传输.
19                                        # 一般 callable 是一个保存文件到本地的函数,
20                                        # 省略 callable, 数据将被打印到屏幕.
21                                        # cmd = 'RETR filename'
22     FH.retrbinary('cmd', 'callable', 'blocksize', 'rest')
23                                        # 以二进制模式下载数据
24         # If optional rest is given, a REST command is sent to the server,
25         # passing rest as an argument. rest is usually a byte offset into
26         # the requested file, telling the server to restart sending the file’s
27         # bytes at the requested offset, skipping over the initial bytes.
28         # Note however that RFC 959 requires only that rest be a string containing
29         # characters in the printable range from ASCII code 33 to ASCII code 126.
30         # The method, therefore, converts rest to a string, but no check is performed
31         # on the string’s contents. If the server does not recognize the REST command,
32         # an error_reply exception will be raised. If this happens, simply call method
33         # without a rest argument.
34 
35     FH.storbinary('cmd', 'FH', 'blocksize', 'callable', 'rest')
36                                        # 对应 socket 的 read() 方法, 二进制模式.
37                                        # cmd = 'STOR filename'
38     FH.storlines('cmd', 'FH', 'callable')
39                                        # 对应 socket 的 readline() 方法, ACSII 模式.
40                                        # cmd = 'STOR filename'
41     FH.nlst()                          # 获取路径下的条目
42     FH.dir()                           # 获取路径下的条目及相信信息, ls - la / dir
43 
44     FH.delete('filename')              # 删除 filename 文件
45     FH.rmd('dirname')                  # 删除 dirname 目录
46     FH.mkd('dirname')                  # 建立 dirname 目录
47     FH.rename('fromname', 'toname')    # 重命名
48     FH.quit()        # 断开 FTP 链接
49 
50 Error Handling,
51     ftplib.all_errors 包含累所有的有可能由 fitplib 产生的异常.
52     可以在 try: except 代码块中通过 ftplib.all_errors 来捕捉
53     处理可能发生的错误.
54 
55 Reference,
56     Python doc,
57         https://docs.python.org/3/library/ftplib.html

 

posted @ 2017-12-29 18:44  zzYzz  阅读(491)  评论(0编辑  收藏  举报


Click to Visit Homepage : zzyzz.top