forked from yidao620c/python3-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathftp.py
More file actions
60 lines (48 loc) · 1.18 KB
/
ftp.py
File metadata and controls
60 lines (48 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: sample
Desc : 使用FTP下载示例
"""
import ftplib
import os
import socket
__author__ = 'Xiong Neng'
HOST = 'ftp.mozilla.org'
DIRN = 'pub/webtools'
FILE = 'bugzilla-LATEST.tar.gz'
def main():
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror) as e:
print('ERROR: connot reach "%s"' % HOST)
exit(1)
print('*** Connected to host "%s"' % HOST)
try:
f.login()
except ftplib.error_perm:
print('ERROR: connot login anonymously')
f.quit()
exit(1)
print('*** Logged in as "anonymous"')
try:
f.cwd(DIRN)
except ftplib.error_perm:
print('ERROR: cannot cd to "%s"' % DIRN)
f.quit()
exit(1)
print('*** Changed to "%s" folder' % DIRN)
try:
locFile = open(FILE, 'wb')
f.retrbinary('RETR %s' % FILE, locFile.write)
except ftplib.error_perm:
print('ERROR: cannot read file "%s"' % FILE)
os.unlink(FILE)
else:
print('*** Downloaded "%s" to CWD' % FILE)
finally:
locFile.close()
f.quit()
return
if __name__ == '__main__':
main()