Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5096724
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2013-08-16 11:43:51

 因为python脚本可以直接用文本工具打开修改,所以没有设置参数。使用的时候直接修改掉main中的连接下载参数即可。
修改一下,可以用来备份网站上的图片,数据库什么的。


  1. #!/usr/bin/python
  2. #coding=gbk
  3. '''
  4.     ftp自动下载、自动上传脚本,可以递归目录操作
  5. '''

  6. from ftplib import FTP
  7. import os,sys,string,datetime,time
  8. import socket

  9. class MYFTP:
  10.     def __init__(self, hostaddr, username, password, remotedir, port=21):
  11.         self.hostaddr = hostaddr
  12.         self.username = username
  13.         self.password = password
  14.         self.remotedir = remotedir
  15.         self.port = port
  16.         self.ftp = FTP()
  17.         self.file_list = []
  18.         # self.ftp.set_debuglevel(2)
  19.     def __del__(self):
  20.         self.ftp.close()
  21.         # self.ftp.set_debuglevel(0)
  22.     def login(self):
  23.         ftp = self.ftp
  24.         try:
  25.             timeout = 60
  26.             socket.setdefaulttimeout(timeout)
  27.             ftp.set_pasv(True)
  28.             print '开始连接到 %s' %(self.hostaddr)
  29.             ftp.connect(self.hostaddr, self.port)
  30.             print '成功连接到 %s' %(self.hostaddr)
  31.             print '开始登录到 %s' %(self.hostaddr)
  32.             ftp.login(self.username, self.password)
  33.             print '成功登录到 %s' %(self.hostaddr)
  34.             debug_print(ftp.getwelcome())
  35.         except Exception:
  36.             deal_error("连接或登录失败")
  37.         try:
  38.             ftp.cwd(self.remotedir)
  39.         except(Exception):
  40.             deal_error('切换目录失败')

  41.     def is_same_size(self, localfile, remotefile):
  42.         try:
  43.             remotefile_size = self.ftp.size(remotefile)
  44.         except:
  45.             remotefile_size = -1
  46.         try:
  47.             localfile_size = os.path.getsize(localfile)
  48.         except:
  49.             localfile_size = -1
  50.         debug_print('lo:%d re:%d' %(localfile_size, remotefile_size),)
  51.         if remotefile_size == localfile_size:
  52.              return 1
  53.         else:
  54.             return 0
  55.     def download_file(self, localfile, remotefile):
  56.         if self.is_same_size(localfile, remotefile):
  57.              debug_print('%s 文件大小相同,无需下载' %localfile)
  58.              return
  59.         else:
  60.             debug_print('>>>>>>>>>>>>下载文件 %s ... ...' %localfile)
  61.         #return
  62.         file_handler = open(localfile, 'wb')
  63.         self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
  64.         file_handler.close()

  65.     def download_files(self, localdir='./', remotedir='./'):
  66.         try:
  67.             self.ftp.cwd(remotedir)
  68.         except:
  69.             debug_print('目录%s不存在,继续...' %remotedir)
  70.             return
  71.         if not os.path.isdir(localdir):
  72.             os.makedirs(localdir)
  73.         debug_print('切换至目录 %s' %self.ftp.pwd())
  74.         self.file_list = []
  75.         self.ftp.dir(self.get_file_list)
  76.         remotenames = self.file_list
  77.         #print(remotenames)
  78.         #return
  79.         for item in remotenames:
  80.             filetype = item[0]
  81.             filename = item[1]
  82.             local = os.path.join(localdir, filename)
  83.             if filetype == 'd':
  84.                 self.download_files(local, filename)
  85.             elif filetype == '-':
  86.                 self.download_file(local, filename)
  87.         self.ftp.cwd('..')
  88.         debug_print('返回上层目录 %s' %self.ftp.pwd())
  89.     def upload_file(self, localfile, remotefile):
  90.         if not os.path.isfile(localfile):
  91.             return
  92.         if self.is_same_size(localfile, remotefile):
  93.              debug_print('跳过[相等]: %s' %localfile)
  94.              return
  95.         file_handler = open(localfile, 'rb')
  96.         self.ftp.storbinary('STOR %s' %remotefile, file_handler)
  97.         file_handler.close()
  98.         debug_print('已传送: %s' %localfile)
  99.     def upload_files(self, localdir='./', remotedir = './'):
  100.         if not os.path.isdir(localdir):
  101.             return
  102.         localnames = os.listdir(localdir)
  103.         self.ftp.cwd(remotedir)
  104.         for item in localnames:
  105.             src = os.path.join(localdir, item)
  106.             if os.path.isdir(src):
  107.                 try:
  108.                     self.ftp.mkd(item)
  109.                 except:
  110.                     debug_print('目录已存在 %s' %item)
  111.                 self.upload_files(src, item)
  112.             else:
  113.                 self.upload_file(src, item)
  114.         self.ftp.cwd('..')

  115.     def get_file_list(self, line):
  116.         ret_arr = []
  117.         file_arr = self.get_filename(line)
  118.         if file_arr[1] not in ['.', '..']:
  119.             self.file_list.append(file_arr)
  120.             
  121.     def get_filename(self, line):
  122.         pos = line.rfind(':')
  123.         while(line[pos] != ' '):
  124.             pos += 1
  125.         while(line[pos] == ' '):
  126.             pos += 1
  127.         file_arr = [line[0], line[pos:]]
  128.         return file_arr
  129. def debug_print(s):
  130.     print (s)
  131. def deal_error(e):
  132.     timenow = time.localtime()
  133.     datenow = time.strftime('%Y-%m-%d', timenow)
  134.     logstr = '%s 发生错误: %s' %(datenow, e)
  135.     debug_print(logstr)
  136.     file.write(logstr)
  137.     sys.exit()

  138. if __name__ == '__main__':
  139.     file = open("log.txt", "a")
  140.     timenow = time.localtime()
  141.     datenow = time.strftime('%Y-%m-%d', timenow)
  142.     logstr = datenow
  143.     # 配置如下变量
  144.     hostaddr = 'localhost' # ftp地址
  145.     username = 'test' # 用户名
  146.     password = 'test' # 密码
  147.     port = 21 # 端口号
  148.     rootdir_local = '.' + os.sep + 'bak/' # 本地目录
  149.     rootdir_remote = './' # 远程目录
  150.     
  151.     f = MYFTP(hostaddr, username, password, rootdir_remote, port)
  152.     f.login()
  153.     f.download_files(rootdir_local, rootdir_remote)
  154.     
  155.     timenow = time.localtime()
  156.     datenow = time.strftime('%Y-%m-%d', timenow)
  157.     logstr += " - %s 成功执行了备份\n" %datenow
  158.     debug_print(logstr)
  159.     
  160.     file.write(logstr)
  161.     file.close()



文章原链接:http://canlynet.iteye.com/blog/836996
阅读(3428) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~