Sunday, September 4, 2011

[Linux] Simple sync/backup script.

Just polished my backup script including wake on lan. Just a simple script, but still essential to me.

#!/bin/bash

#function for syncing folders
function sync {
rsync -avrz /folders/to/sync user@host:/destination/folder
rsync -avrx /var/www/data/ ~/Dropbox/wiki/ #makes my wiki pages accessible remotely
}

#function for shutdown remote host, remember to change the rights for the poweroff command(eg. chmod u+s(Set the suid bit) poweroff)
function shutdown {
ssh user@host "poweroff"
}

#wol function, requires the wakeonlan package(on Ubuntu, apt-get install wakeonlan). Or you could use my python script(link).
function wol {
wakeonlan macaddress
}

#check if host is up(my rules: if server is up, only sync. If down start server, sync and then shutdown.
if ping -c 3 host
then
        sync
else
        wol
sync
shutdown
fi

exit 0

Note: Since we are using SSH for remote access it's a good idea to setup SSH login without password, follow this link

Note2: This is added to the crontab for automatic execution once a day.

Note3: I'm using hostname lookup instead of ip(which is assigned by my routers dhcp). This means that if my router suddenly changes the assigned ip(I know it's possible to reserve ip) the script is none dependend on ip. Use avahi-daemon and avahi-autoipd for this feature.

No comments:

Post a Comment