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

vim autoftp

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

ftphost= IP_Address
EMAIL=me@my.com
DIRTOBACKUP=/var/www/html
BACKUPDIR=/home/backup
LOGFILE=$BACKUPDIR/autoftp.log

hostname=`hostname`
file=$hostname-backup-`date +%Y-%m-%d-%H-%M`.tgz
time=`date +%Y-%m-%d-%H:%M:%S`
cd $BACKUPDIR
echo "###################################################"> $LOGFILE
echo "# Start Date&Time $time       #">> $LOGFILE
echo "###################################################">> $LOGFILE
echo "#              Backup Process Started             #">> $LOGFILE
echo "###################################################">> $LOGFILE
echo [$time] $file created >> $LOGFILE
tar cpzf $file $DIRTOBACKUP
time=`date +%Y-%m-%d-%H:%M:%S`
echo [$time] backup compressed now sending to ftp server >> $LOGFILE

ftp -v << EOF
open $ftphost
binary
put $file
quit
EOF
#if your mail client is not setup, you can skip, email backup reports, by commenting it with hash sign #
mail -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:

chmod +X autoftp

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

vim ~/.netrc

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

Final step add to crontab

crontab -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)

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

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

Check the crontab is ok?

crontab -l -u root

Make sure crontab service is running

service crontab status

That’s it ! Enjoy auto ftp backups 🙂