python 实现远端ftp文件上传下载

python 实现ftp上传下载

* 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验

* 运行示例

[root@vm172-31-16-11 software]# python file.txt 2d6c30dba93eda3f70f662a390d8e49c

 1      # -*- coding: utf-8 -*-
 2     
 3     from ftplib import FTP
 4     import time
 5     import tarfile
 6     import os
 7     import sys
 8     import ftplib
 9     import hashlib
10     
11     filename = sys.argv[1]
12     localpath = '/data/update/'
13     remotepath = '/server'
14     def ftpconnect(host, username, password):
15         ftp = FTP()
16     #    ftp.set_debuglevel(2)
17         ftp.connect(host, 21)
18         ftp.login(username, password)
19         print ftp.welcome
20         return ftp
21     def downloadfile(ftp, filename):    
22         if  os.path.exists(localpath):
23             pass
24         else:
25             os.makedirs(localpath, 0755)
26         bufsize = 1024
27         ftp.cwd(remotepath)
28         ftp.dir()
29         fp = open(localpath + filename,'wb')
30         ftp.retrbinary('RETR %s' % os.path.basename(filename), fp.write, bufsize)
31         fp.close()
32     
33     def getFileMD5():
34         filepath = localpath + filename
35         if os.path.exists(filepath):
36         f = open(filepath,'rb')
37         md5obj = hashlib.md5()
38         md5obj.update(f.read())
39         hash = md5obj.hexdigest()
40         f.close()
41         return str(hash).upper()
42         else:
43             print "\033[1;31;40mERROR:Get the %s MD5 failed\033[0m" % filepath
44             return None
45     
46     def file_exists():
47         filemd5 = getFileMD5()
48         downloadftpfile = localpath + filename
49         if os.path.exists(downloadftpfile) and filemd5 == sys.argv[2]:
50             print "\033[1;32;40m====================ftp down ok and md5 value is ok======================\033[0m"
51         elif os.path.exists(downloadftpfile) and filemd5 != sys.argv[2]:
52             print "\033[1;31;40m====================ftp down ok and md5 value is bad======================\033[0m"
53         else:
54             print "\033[1;31;40mERROR:The %s is not exists\033[0m" % downloadftpfile
55     
56     def uploalfile(ftp, remotepath, localpath):
57         bufsize = 1024
58         fp = open(localpath, 'rb')
59         ftp.storbinary('STOR ' + remotepath, fp, bufsize)
60     #    ftp.set_debuglevel(0)
61         ftp.close()
62     
63     def download():
64         try:
65             ftp = ftpconnect("x.x.x.x", "x.x", "x.x")
66             downloadfile(ftp, filename)
67             ftp.quit()
68             file_exists()
69         except ftplib.error_perm:
70             os.chdir(localpath)    
71             os.remove(filename)
72             file_exists()
73     if __name__ == "__main__":
74         download()
posted @ 2016-07-27 12:16  囍。  阅读(3442)  评论(0编辑  收藏  举报