Today I will spend a lot of time dealing with python. I’m currently using updraft for backing up the WordPress websites, but this plugin has a very relevant weak spot for me. It is tied to the call of the website. This means that if a web page is not called, updraft will not run, which in turn means that:
- Either the page is not backed up at all
- The backup does not finish
- or the backup is not uploaded to the remote server
The last problem is the most important reason for me. Because it will not be uploaded if somebody visits the site sometime. That’s why I want to write a Python script that downloads the whole files locally. In the future, this script will be linked to a git server to save space, because then, only the changes are pushed …
hostname = 'ftpHost' username = 'ftpUser' password = 'ftpPass' start_directory = '/' backup_dir = './' import ftplib import os import datetime def get_files_directories(): dirlisting =  ftp_obj.retrlines('LIST',callback=dirlisting.append) files =  directories =  for l in dirlisting: lastspace = l.rindex(' ') file_name = l[lastspace+1:] if l == 'd' and file_name != '.' and file_name != '..': directories.append(file_name) elif l == '-': files.append(file_name) return files,directories def backup_directory(local_dir,remote_dir): os.chdir(local_dir) try: ftp_obj.cwd(remote_dir) print('In directory '+remote_dir) files,directories = get_files_directories() for f in files: print('Backing up '+f) try: ftp_obj.retrbinary('RETR '+f, open(f, 'wb').write) except ftplib.error_perm: print('Skipping '+f+' due to permissions') for d in directories: newremote = remote_dir+d+'/' newlocal = local_dir+'/'+d os.mkdir(newlocal) print(newlocal) backup_directory(newlocal,newremote) except: print('Skipping '+remote_dir+' due to permissions!!!!!') os.chdir(backup_dir) datestring = str(datetime.date.today()) os.mkdir(datestring) os.chdir(datestring) local_dir = os.getcwd() ftp_obj = ftplib.FTP(host=hostname, user=username, passwd=password) remote_dir = start_directory backup_directory(local_dir,remote_dir) ftp_obj.quit()
This script logs into the ftp server, creates a folder from the current day and goes through all folders on the ftp server to download everything. Now I just have to make sure that changes are detected and the changes are applied locally to the same folder to push the changes into a git repository.