Sunday, June 9, 2013

Automated online backup using FTP

I host my website on a hosted server with no shell access (I know it is pretty lame, but cuts down on my cost) and until I don't I have my server running with a Public IP address this problem will remain a problem.

Adding to this is the feature request that I get from others and myself to put some of the content from work/research away from the computers, somewhere in the Cloud. Since people have not gotten over the paranoia about Dropbox, and I too do not recommend them it, FTP way to hosted server is a sensible solution.

In case of a VPS, with shell access on the server a simple 'rsync' would do the job and crontab (one of the most beautiful pieces of software, ever) makes it a habit for the computer to do it as a routine.

Since all these are not happening, and simply because I do not have shell access to the server, I started looking at FTP as an option. Of course, FTP ain't secure, but I haven't yet worked the SFTP out. If one of you does it, do post it as comment.

Here's the script that will be automated using crontab.

#!/bin/bash
username="ftp_user@server"
domain="server"
password="ftp_user_password"

#Getting hold of current date in mm-dd-yy format to append to the backup
date=$(date +"%m-%d-%y")
#backing up a folder to upload
tar -cvzf /home/raghav/backup.tar.gz /home/raghav/backup/ 

#Here's the FTP portion of the code, which runs without interaction

ftp -n <<EOF
 verbose
 open $domain
 user $username $password
 put ~/backup.tar.gz $date-backup.tar.gz
 bye
EOF

Save this as ftp-backup.sh, or anything that makes sense to you. 
Test this code, and of course after making necessary changes with your FTP user name, password and folder to be backed up.

Change permissions, and making it an executable. Use 'chmod a+x ftp-backupto make it executable, and test it. If the script is working and has left a copy of the back up file on your server, now make it a routine task by making a crontab entry.

raghav@debian:~$ crontab -e

And make the following entry in your crontab, to run the backup script ftp-backup daily at 5PM
0 17 * * 1 /home/raghav/ftp-backup


Here's the daily backup (Except for on Saturday and Sundays) dumping archives to my FTP server.