python ftplib下载文件封装

原用于下载ftp中文路径图片封装代码

  1. 支持指定用户密码和端口
    ftp://ftpuser:ftppasswd@192.168.2.157:21/test.png
  2. 支持中文
    ftp://192.168.2.157/测试1/test.png

思路逻辑:

  1. ftp url分析是否有用户验证和端口指定
  2. 使用ftp.retrbinary下载文件,StringIO.StringIO()作缓存

直接上代码

 1 # coding:utf-8
 2 import sys
 3 import urlparse
 4 import ftplib
 5 import traceback
 6 import StringIO
 7 
 8 # used to down ftp file with auth and chinese character
 9 def ftpdown(url, timeout=3):
10     lasterr = ''
11     for i in range(3):
12         urlps = urlparse.urlparse(url)
13         if '@' not in urlps.netloc:
14             user = ''
15             passwd = ''
16             host = urlps.netloc
17             port = 21
18         else:
19             urlhead = urlps.netloc.split('@')
20             if len(urlhead) != 2:
21                 lasterr = 'url fromat err'
22                 continue
23             else:
24                 user, passwd = urlhead[0].split(':')
25                 if ':' not in urlhead[1]:
26                     host = urlhead[1]
27                     port = 21
28                 else:
29                     host, port = urlhead[1].split(':')
30 
31         try:
32             ftp = ftplib.FTP()
33             ftp.connect(host=host, port=port, timeout=timeout)
34             ftp.login(user=user, passwd=passwd)
35         except Exception:
36             print(traceback.format_exc())
37             continue
38         try:
39             buf = StringIO.StringIO()
40             ftp.retrbinary('RETR ' + urlps.path, buf.write)
41             ftp.close()
42             return buf.getvalue()
43         except Exception:
44             lasterr = traceback.format_exc()
45             continue
46     print('exception occurs when ftp get url[%s], err[%s]' % (url, lasterr))
47     return None

参考文档:https://www.cnblogs.com/kaituorensheng/p/4480512.html

原文地址:https://www.cnblogs.com/elephanyu/p/8889428.html