Skip to content

Instantly share code, notes, and snippets.

@wencan
Created June 16, 2014 03:27
Show Gist options
  • Save wencan/e525fde6f810d004389c to your computer and use it in GitHub Desktop.
Save wencan/e525fde6f810d004389c to your computer and use it in GitHub Desktop.
update_files_from_ftp.py
#coding:utf-8
import ftplib
import time
import os.path
FTP_USER = ''
FTP_PWD = ''
REMOTE_HOST = 'ftp.debian.org'
REMOTE_DIR = 'debian/tools'
REMOTE_FILES = ('loadlin.exe', 'loadlin.txt')
LOCAL_DIR = 'D:'
LOCAL_FILES = ('loadlin.exe', 'loadlin.txt')
need_enter = False
try:
print('connect to %s... ...' % (REMOTE_HOST,))
ftp = ftplib.FTP(REMOTE_HOST)
print('login to %s... ...' % (REMOTE_HOST,))
ftp.login(FTP_USER, FTP_PWD)
print(ftp.getwelcome())
print('open %s/%s' % (REMOTE_HOST, REMOTE_DIR))
ftp.cwd(REMOTE_DIR)
for remote_file in REMOTE_FILES:
#remote file
remote_filepath = REMOTE_HOST + '/' + REMOTE_DIR + '/' + remote_file
#local file
idx = REMOTE_FILES.index(remote_file)
local_file = LOCAL_FILES[idx]
local_filepath = LOCAL_DIR + '/' + local_file
#
need_copy = False
try:
#remote last time
cmd_out = ftp.sendcmd('MDTM ' + remote_file)
status, mdtm = cmd_out.split(' ', 2)
#print('%s/%s/%s: %s, %s' % (REMOTE_HOST, REMOTE_DIR, remote_file, status, mdtm))
#remote last time
rlt = time.strptime(mdtm, '%Y%m%d%H%M%S')
#local last datetime
llt = time.gmtime(os.path.getmtime(local_filepath))
#compare the file was last modified time
need_copy = llt < rlt
#Compare file size
if not need_copy:
cmd_out = ftp.sendcmd('SIZE ' + remote_file)
status, _size = cmd_out.split(' ', 2)
rs = int(_size)
ls = os.path.getsize(local_filepath)
need_copy = rs != ls
except ftplib.error_perm as e:
print(e)
except os.error as e:
print(e)
need_copy = True
#copy file
if need_copy:
print('copy file %s to %s... ...' % (remote_filepath, local_filepath))
ftp.retrbinary('RETR ' + remote_file, open(local_filepath, 'wb').write)
except ftplib.all_errors as e:
need_enter = True
print(e)
raise
else:
pass
finally:
try:
ftp
except NameError:
pass
else:
print('close connection')
ftp.quit()
if need_enter:
raw_input('ENTER to continue')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment