Skip to content

Instantly share code, notes, and snippets.

@dustinlennon
Last active February 16, 2025 13:15
Show Gist options
  • Save dustinlennon/05ea86d2061222915080102c335f6f77 to your computer and use it in GitHub Desktop.
Save dustinlennon/05ea86d2061222915080102c335f6f77 to your computer and use it in GitHub Desktop.
Mirror directory structures on remote and local machines.
#!/bin/bash
#
# Mirror directory structures on remote and local machines.
#
# This requires "mirror" accounts with sudo privileges having NOPASSWD for
# /usr/bin/rsync. This enables rsync to read/write files not owned by the
# mirror. The corresponding sudoers entry (visudo sudoers):
#
# mirror ALL=(ALL) NOPASSWD: /usr/bin/rsync
#
# Mirrored files are stored in /backup/mirror/<HOSTNAME>/<...> on the local
# machine. Note that /backup could be a mounted external hard drive.
#
# To run regularly, set up the user crontab in the mirror account, (crontab -e):
#
# 0 3 * * * /home/mirror/.local/bin/backup
#
#
# CONTACT INFO
# author: Dustin Lennon
# email: dustin.lennon@gmail.com
#
#
#
# Set the location of the log file.
# LOGFILE=/home/mirror/logs/backup.log
#
# Set the name of the local machine
# LOCALHOST=192.168.1.103
timestamp() {
if [ $# -lt 1 ]; then
echo syntax error: usage: timestamp tag
return 1
fi
tag=$1 && shift
while read line; do
ts=$(printf '%(%Y-%m-%d %H:%M:%S)T')
echo "[${ts}] [${tag}] $line"
done
}
logger() {
if [ $# -lt 1 ]; then
echo syntax error: usage: logger tag ...
return 1
fi
tag=$1 && shift
args=( "$@" )
cmd=$(printf "%q " "${args[@]}")
LOGFILE=${LOGFILE:=/tmp/backup.log}
eval $cmd | timestamp $tag | tee $LOGFILE
}
remote_mirror() {
if [ $# -lt 2 ]; then
echo syntax error: usage: remote_mirror host rooted_directory
return 1
fi
host=$1 && shift
rooted_directory=$1 && shift
logger "remote_mirror" \
echo "$host $rooted_directory"
logger "rsync" \
sudo \
rsync -av \
-e "sudo -u mirror ssh" \
--relative \
--delete \
--rsync-path="sudo rsync -a" \
${host}:${rooted_directory} /backup/mirror/${host}
}
local_mirror() {
if [ $# -eq 0 ]; then
echo syntax error: usage: local_mirror rooted_directory
return 1
fi
rooted_directory=$1 && shift
host=${LOCALHOST:="localhost"}
logger "local_mirror" \
echo "$rooted_directory"
logger "rsync" \
sudo \
rsync -av \
--relative \
--delete \
${rooted_directory} /backup/mirror/${host}
}
REMOTEHOST=192.168.1.102
remote_mirror $REMOTEHOST /etc
remote_mirror $REMOTEHOST /var/lib
remote_mirror $REMOTEHOST /home/dustin
remote_mirror $REMOTEHOST /home/deploy
remote_mirror $REMOTEHOST /media/streaming
local_mirror /etc
local_mirror /home/dnlennon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment