I'm creating own script for backup user's directories.
CentOS 6.5; Python 2.6.
Directories looks like:
# tree -L 2 -d /var/www/vhosts/
/var/www/vhosts/
├── freeproxy
│ └── freeproxy.in.ua
├── hudeem
│ └── hudeem.kiev.ua
├── profy
│ └── profy.kiev.ua
├── rtfm
│ └── rtfm.co.ua
├── setevoy
│ ├── forum.setevoy.kiev.ua
│ ├── postfixadmin.setevoy.org.ua
│ ├── setevoy.org.ua
│ └── webmail.setevoy.org.ua
├── worlddesign
│ └── worlddesign.org.ua
└── zabbix
└── zabbix.setevoy.org.ua
As script big enought, I'll post only three 'most important' functions. So please note, that they using some additional functions.
First - function to create backup directories:
# global const for user's directory
VHOSTSPATH = '/var/www/vhosts/'
def back_dir_create(user, day):
backdir = '/home/setevoy/backups/temp_new_test/'
# weekly are kept 4 last, daily - 7 copies
# thus - better have separate directories
if day == 'Sun':
type = '/weekly/'
else:
type = '/daily/'
dirname = ('%s%s%s%s-files/' % (backdir, user, type, time.strftime('%Y-%m-%d')))
if not os.path.exists(dirname):
print('Creating directory: %s' % dirname)
os.makedirs(dirname)
return(dirname)
Second - 'incremental' backup, for files changed last twenty-four hours:
def inc_backup(dir_to_backup, backupname):
now = time.time()
cutoff = 86400
print('Creating archive %s...' % backupname)
out = tarfile.open(backupname, mode='w:bz2')
# start walk via all files to find changed last 24 hours
for root, dirs, files in os.walk(dir_to_backup, followlinks=True):
for file in files:
file = os.path.join(root, file)
try:
filemodtime = os.stat(file).st_mtime
if now - filemodtime < cutoff:
if os.path.isfile(file):
print('Adding file: %s...' % file)
out.add(file)
print('File modified: %s' % time.ctime(os.path.getmtime(file)))
except OSError as error:
print('ERROR: %s' % error)
print 'Closing archive.'
out.close()
And both this function used in 'main' function:
def run_backup():
# here is two functions, not listed here
# both rerurns lists[] - with users
# like just username
# and dirs
# like /var/www/vhosts/username
userlist = arch_users_list(VHOSTSPATH)
userpaths = arch_users_path(VHOSTSPATH, userlist)
# day of week
curday = time.strftime('%a')
for hostdir, username in zip(userpaths, userlist):
os.chdir(hostdir)
print('\nWorking in: %s' % os.getcwd())
print('Under user: %s' % username)
# call first function, listed above
backup_dir = back_dir_create(username, curday)
if backup_dir:
virtual_hosts = arch_vhosts_names(hostdir)
for host in virtual_hosts:
archname = (backup_dir + host + '.tar.bz2')
# once in week I want have full backup
# other time - 'incremental'
if curday == 'Sun':
full_backup(host, archname)
else:
inc_backup(host, archname)
else:
print('Backup already present, skip.')
It works fine for now, but I'm newbie in Python, so - what can be improved here or fixed?