FTP automation on Linux

 

Ever wanted FTP backups and automation for keeping backups of important file on off-peak time. I always love automation, so machines can do things automatically and help humans 🙂

Ok lets start, create a shell script

1vim autoftp

Now paste this script and adjust the parameters of ftp host, email address, backup directory, folder to backup.

01ftphost= IP_Address
02EMAIL=me@my.com
03DIRTOBACKUP=/var/www/html
04BACKUPDIR=/home/backup
05LOGFILE=$BACKUPDIR/autoftp.log
06 
07hostname=`hostname`
08file=$hostname-backup-`date +%Y-%m-%d-%H-%M`.tgz
09time=`date +%Y-%m-%d-%H:%M:%S`
10cd $BACKUPDIR
11echo "###################################################"> $LOGFILE
12echo "# Start Date&Time $time       #">> $LOGFILE
13echo "###################################################">> $LOGFILE
14echo "#              Backup Process Started             #">> $LOGFILE
15echo "###################################################">> $LOGFILE
16echo [$time] $file created >> $LOGFILE
17tar cpzf $file $DIRTOBACKUP
18time=`date +%Y-%m-%d-%H:%M:%S`
19echo [$time] backup compressed now sending to ftp server >> $LOGFILE
20 
21ftp -v << EOF
22open $ftphost
23binary
24put $file
25quit
26EOF
27#if your mail client is not setup, you can skip, email backup reports, by commenting it with hash sign #
28mail -s "Backup Report" $EMAIL < $LOGFILE

Save the file in any place you like, in this example I am saving it to my home directory, i.e. /home/bshafiq/autoftp
Give execute permission to newly created shell script by doing this:

1chmod +X autoftp

For providing FTP authentication details, “.netrc” text file with ip userid password details in user root folder
like this:-

1vim ~/.netrc

and paste details like this:-
machine IP_Address login Your_UserID password Your_Super_Strong_Password

Final step add to crontab

1crontab -e -u root

(Change root with anyother user of your choice, but the user must have access to the folders we want to backup and where we put the backup)

10 1 * * * /home/bshafiq/autoftp > /dev/null

(It will auto backup on 1am daily, adjust the time as your want)

Check the crontab is ok?

1crontab -l -u root

Make sure crontab service is running

1service crontab status

That’s it ! Enjoy auto ftp backups 🙂