Since my NAS at home also acts as DHCP server, the obvious idea was to back up my PC and my laptop whenever they're switched on. Sadly, the documentation on how to do this from dhcpd.conf (instead of watching log files and reacting to log messages) is quite hidden, so here it is: I found the "execute" keyword (see the dhcp-eval manpage), and I found Tim Gustafson, which allowed me to pull it off (although, since I only have the two computers, I opted for a execute statement each and hardcoded the client IP in the call to the backup script. So I don't know if the address parsing stuff he does is correct.)
So the host statements for me look just like this:
host laeggerli-wifi {
hardware ethernet 00:22:69:aa:bb:cc;
fixed-address 172.23.5.19;
on commit {
execute("/usr/local/sbin/dhcp-run-backup", "commit", "laeggerli");
}
}
And the script to start dirvish is similarly simple, except that it needs to fork to the background to make sure dhcpd is not blocked. The sleep 600 is based on the theory that if I'm on my way out in the morning and need to check mail quickly, that will be less than 10 min, whereas when I'm still online after 10 min, there's a good chance that the back up will go through. Obviously, this could be improved...
#! /bin/bash
# called by dhcpd.conf
# arguments:
# $1 -> "commit" if called from dhcpd.conf, fork into background
# -> "run" if called internall from first instance
# $2 -> client host
if [ "$1" == "commit" ]; then
# fork to background
$0 run "$2" >> /var/log/dhcpbackup.log 2>&1 &
exit 0
fi
if [ "$1" != "run" ]; then
echo error
exit 1
fi
# figure out which host:
host="$2"
if [ "$host" != "laeggerli" -a "$host" != "faehrimaa" ]; then
echo "Unknown host: $2"
exit 1
fi
# did backup already run today?
d=`date +%Y%m%d`
if [ -d "/srv/backup/${host}_home/$d" ]; then
exit 0
fi
# wait 10min before actually running the backup
# (if computer still runs after 10min, it'll likely run for longer...
sleep 600
ping -n -w 3 $host >/dev/null 2>&1 || exit 0
agentpid="/var/run/dirvish/ssh-agent-$host.pid"
[ -f "$agentpid" ] && \
kill $(< "$agentpid") 2>/dev/null
mkdir /var/run/dirvish >/dev/null 2>&1
eval `ssh-agent` >/dev/null 2>&1
echo $SSH_AGENT_PID > "$agentpid"
ssh-add /etc/dirvish/ssh-key >/dev/null 2>&1
/usr/sbin/dirvish --vault ${host}_home
/usr/sbin/dirvish --vault ${host}_root
/usr/sbin/dirvish-expire --quiet --vault ${host}_home
/usr/sbin/dirvish-expire --quiet --vault ${host}_root
kill $SSH_AGENT_PID
rm "$agentpid"
(I don't claim any rights on any of it, it's trivial enough.)
Comments