Linux Administrator

How to Setup Automated Remote Backup Using FTP Commands and Cron Job?

The File Transfer Protocol (FTP) is used to transfer files between two computers over a network and Internet. FTP service is very important to ensure the transfer of files can be done. For some servers, though not provide FTP service, FTP client is necessary to be installed so that the client can send files to an FTP server if required.

In Linux Operating System cron daemon is used to schedule jobs and commands at regular interval. One can execute any script file containing as a jobs at specified date and time. Following script will use standard Linux FTP commands to place one system’s backup file to other remote system.

Here, the script is working in a cron job which uploads backup file at every 6 hours, then it will overwrite older backup file. If anyone wants to have backup every hour, he/she has to make changes accordingly in crontab file.

Here I am going to make a script called “remote_backup_day.sh”

# vim remote_backup_day.sh
#!/bin/sh
# Put FTP server details here
SERVER="Remote FTP server"
USERNAME="FTP user"
PASSWORD="FTP password"

# local directory containing source backup file
SOURCEFILES="/home/mybackup"

# remote server directory path in which backup needs to be put in
BACKUPDIRCTORY="/rsystem/backupdir/"

# login to remote server
ftp -n -i $SERVER <<EOF
user $USERNAME $PASSWORD
cd $ BACKUPDIRCTORY

mput $ SOURCEFILES/*.tar.gz
quit
EOF

You can also make another file using same code given above and give a name to that file as: remote_backup_night.sh as it will put backup to remote system at midnight.
Both the script should have executable permissions, like:

# chmod +x remote_backup_day.sh
# chmod +x remote_backup_night.sh

Now we have to setup a cron job to run above script at regular intervals.

You need to edit your crontab file. Enter the following command:

# crontab -e

Following lines should append to available code as there may be a chance to have some another job running in the crontab file.

0 12 * * * remote_backup_day.sh >>/tmp/backup.log 2>&1
0 0 * * * remote_backup_night.sh >>/tmp/backup.log 2>&1

Save and close the file.

To store the output of cron commands, we have used /tmp/backup.log file.

Please use crontab –l command to confirm crontab job uses above code or not.

In the above script /home/mybackup folder contains tar.gz files. One has to write a separate script to generate those source backup file.
Thank you! for visiting Look Linux.

If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com. To become an author at Look Linux Submit Article. Stay connected to Facebook.

About the author

mm

Santosh Prasad

Hi! I'm Santosh and I'm here to post some cool article for you. If you have any query and suggestion please comment in comment section.

Leave a Comment