PDA

View Full Version : Script to regularly download backups from remote server



Fli
02-23-2015, 01:21 PM
# Script to download backups to local server
# - delete old backups
# - kills all locally runnign rsync before running rsync
# - send an email notiffying that this script finished running

# sleep some time so todays backup is started to be made
sleep 5

# variables
$yesterday="date -d \"1 day ago\" \"+%Y-%m-%d\""
$today="date \"+%Y-%m-%d\""
ip_cp="1.2.3.4" # remote server IP (source of backups)
ip_cp_path="/backup/$today"
ip_cp_pathdest="/remote_serv_backup/"
speed="5000" # max. transfer speed in kb
sshport="22"
maill="[email protected]"
sshkeysetup="yes"

# optional SSH access key setup
if [ "$sshkeysetup" == "yes" ];then
echo "-----------------------
Can we run ssh-keygen & ssh-copy-id now? Key will be sent to $ip_cp server so this remote server knows he should allow incoming connections of this local server.
y (yes, start) or any key (no, exit)"
read kgcp
if [ "$kgcp" == "y" ];then
ssh-keygen
ssh-copy-id -i ~/.ssh/id_rsa.pub "$ip_cp -p $sshport"
sleep 3
echo "Listing remote authorized_keys file now..." && sleep 3
ssh -p $sshport $ip_cp 'cat ~/.ssh/authorized_keys;exit'
echo "SSH key setup finished, hope that successfully.. Now Bakcup script continuing..." && sleep 9
fi

# list remote server bakcp dir contents (maybe for purpose to check if some bakcup is there)
# rmtservbckpdircontents="$(ssh -p $sshport $ip_cp 'ls -A1 $ip_cp_pathdest;exit')"
# if [[ "$rmtservbckpdircontents" == *"$today"* ]];then

# delete local backup files not modiffied more than 720 hours (30 days)
tmpwatch -m 720 $ip_cp_pathdest

# make sure no rsync is already running (kill all locally running rsync)
pkill -f "rsync"

# rsync backups from remote server
/bin/nice -n 19 /usr/bin/ionice -c2 -n7 rsync -au --size-only --progress --bwlimit=$speed -e "ssh -p $sshport" root@$ip_cp:$ip_cp_path $ip_cp_pathdest

echo "Backups downloader script located on $(hostname) finished. This script is probably located in /etc/cron... or /root" | mail -s "Backups downloader - $(hostname)" $maill

If you need script that not download backups from remote server, but upload local server bakcups to remote server, please check this topic (http://internetlifeforum.com/linux-forums/2526-how-backup-files-linux-server-server-automatically-cronjob/) for slightly better written script.

Script mentioned in this topic generating ssh access key and upload it to remote server (from which backups wlll be downloaded). After first run, edit script and change "sshkeysetup="yes"" to no so only backups are made on next runs.