настройка бэкапов на удаленный сервер через rsync

Всё подчистую содрал отсюда: http://www.linux.com/articles/113847

Ставим rsync на оба сервера:

 cd /usr/ports/net/rsync
make install clean

Проверяем как это работает вручную поверх ssh:

rsync -avz -e ssh /src/files/ mschedrin@192.168.1.1:/destination/backup/dir

Теперь надо автоматизировать процесс. Создадим пользователя backup на машине, которая будет принимать бэкапы. Теперь сгенерим ключик для авторизации ssh на одном из компов которые будут делать бэкапы. Только обязательно оставить пустой passphrase:

ssh-keygen -t dsa -b 1024 -f ~/rsync-key

Далее копируем сгенеренные ключики и на машину, которая будет принимать бэкапы.

scp ~/rsync-key.pub user@remotehost:~

Теперь надо положить публичный ключик в authorized_keys:

mkdir ~/.ssh
chmod 700 ~/.ssh
mv ~/rsync-key.pub ~/.ssh/
cd ~/.ssh/
touch authorized_keys
chmod 600 authorized_keys
cat rsync-key.pub >> authorized_keys

Такс, теперь проверяем как оно работает с сервера который будет отправлять бэкапы:

ssh -i ~/rsync-key/rsync-key backup@<ip of backup server>

Чтобы ограничить айпишники с которых можно подрубаться и какие команды можно выполнять подключившемуся юзеру, модифицируем authorized_keys следующим образом:

from=”192.168.1.1″, command=”/home/user/validate-rsync.sh” ssh-dss Aо3AAAB3NzaC1kc3MAAACBAJbW…

Вот пример скрипта validate-rsync.sh:
#!/bin/sh
# Author: Brice Burgess – bhb@iceburg.net
# rbackup.sh — secure backup to a remote machine using rsync.

# Directories to backup. Separate with a space. Exclude trailing slash!
SOURCES="/etc /root /usr/local/etc /usr/local/data /mnt/hdd2/mon2"

# IP or FQDN of Remote Machine
RMACHINE=88.201.*.*

# Remote username
RUSER=backup

# Location of passphraseless ssh keyfile
RKEY=/root/scripts/backup/rsync-key

# Directory to backup to on the remote machine. This is where your backup(s) will be stored
# Exclude trailing slash!
RTARGET="/mnt/1/backups/zabbix"

# Your EXCLUDE_FILE tells rsync what NOT to backup. Leave it unchanged, missingor
# empty if you want to backup all files in your SOURCES. If performing a
# FULL SYSTEM BACKUP, ie. Your SOURCES is set to «/», you will need to make
# use of EXCLUDE_FILE. The file should contain directories and filenames, one per line.
# An example of a EXCLUDE_FILE would be:
# /proc/
# /tmp/
# /mnt/
# *.SOME_KIND_OF_FILE
EXCLUDE_FILE=""

# Comment out the following line to disable verbose output
VERBOSE="-v"

#mysql backups.
#Section added by Michael Schedrin
DATABASES="zabbix"
MYSQL_USER="root"
MYSQL_PASSWORD="***"
TMPPATH="/tmp"
REMOTESQLPATH="mysqlbackups"

#######################################
########DO_NOT_EDIT_BELOW_THIS_POINT#########
#######################################

if [ ! -f $RKEY ]; then
echo "Couldn't find ssh keyfile!"
echo "Exiting"
exit 2
fi

if ! ssh -i $RKEY $RUSER@$RMACHINE "test -x $RTARGET"; then
echo "Target directory on remote machine doesnt exist or bad permissions." $RTARGET
echo "Exiting"
exit 2
fi

echo "Verifying Sources"
for source in $SOURCES; do
echo "Checking $source"
if [ ! -x $source ]; then
echo "Error with $source!"
echo "Directory either does not exist, or you do not have proper permissions."
exit 2
fi
done

if [ -f $EXCLUDE_FILE ]; then
EXCLUDE="-exclude-from=$EXCLUDE_FILE"
fi

echo "Sources verified. Running rsync."
for source in $SOURCES; do

# Create directories in $RTARGET to mimick source directory hiearchy
if ! ssh -i $RKEY $RUSER@$RMACHINE "test -d $RTARGET/$source"; then
ssh -i $RKEY $RUSER@$RMACHINE "mkdir -p $RTARGET/$source"
fi

/usr/local/bin/rsync $VERBOSE $EXCLUDE -a -delete -e "ssh -i $RKEY" $source $RUSER@$RMACHINE:$RTARGET$source

done

#creating directory for mysql backups
if ! ssh -i $RKEY $RUSER@$RMACHINE "test -x $RTARGET/$REMOTESQLPATH"; then
ssh -i $RKEY $RUSER@$RMACHINE "mkdir -p $RTARGET/$REMOTESQLPATH"
fi

for sqldb in $DATABASES; do
#making sql dumps
file=$TMPPATH/$sqldb.sql.gz
echo backing up $file
..
/usr/local/bin/mysqldump -u$MYSQL_USER -p$MYSQL_PASSWORD $sqldb | gzip > $file
/usr/local/bin/rsync $VERBOSE $EXCLUDE -a -delete -e "ssh -i $RKEY" $file $RUSER@$RMACHINE:$RTARGET/$REMOTESQLPATH
rm $file
done

exit 0

На директорию куда будут делаться бэкапы должны быть разрешения 700. Вот у меня всё заработало.
Теперь надо бы еще сделать дамп mysql базы. Скриптик выглядеть будет вот так, у меня вроде заработало:

#!/bin/sh
# Author: Brice Burgess – bhb@iceburg.net
# rbackup.sh — secure backup to a remote machine using rsync.

# Directories to backup. Separate with a space. Exclude trailing slash!
SOURCES=”/etc /root /home/mschedrin /home/limsoft /home/timcrew /home/appelsets /scripts /var/tftp /var/named /usr/http /usr/local/etc”

# IP or FQDN of Remote Machine
RMACHINE=192.168.1.1

# Remote username
RUSER=backup

# Location of passphraseless ssh keyfile
RKEY=/root/rsync-key/rsync-key

# Directory to backup to on the remote machine. This is where your backup(s) will be stored
# Exclude trailing slash!
RTARGET=”/usr/backups/lumpy/daily/”

# Your EXCLUDE_FILE tells rsync what NOT to backup. Leave it unchanged, missingor
# empty if you want to backup all files in your SOURCES. If performing a
# FULL SYSTEM BACKUP, ie. Your SOURCES is set to “/”, you will need to make
# use of EXCLUDE_FILE. The file should contain directories and filenames, one per line.
# An example of a EXCLUDE_FILE would be:
# /proc/
# /tmp/
# /mnt/
# *.SOME_KIND_OF_FILE
EXCLUDE_FILE=””

# Comment out the following line to disable verbose output
VERBOSE=”-v”

#mysql backups.
#Section added by Michael Schedrin
DATABASES=”billing mysql ping verlihub”
MYSQL_USER=”***”
MYSQL_PASSWORD=”***”
TMPPATH=”/tmp”
REMOTESQLPATH=”mysqlbackups”

#######################################
########DO_NOT_EDIT_BELOW_THIS_POINT#########
#######################################

if [ ! -f $RKEY ]; then
echo “Couldn’t find ssh keyfile!”
echo “Exiting…”
exit 2
fi

if ! ssh -i $RKEY $RUSER@$RMACHINE “test -x $RTARGET”; then
echo “Target directory on remote machine doesn’t exist or bad permissions.” $RTARGET
echo “Exiting…”
exit 2
fi

echo “Verifying Sources…”
for source in $SOURCES; do
echo “Checking $source…”
if [ ! -x $source ]; then
echo “Error with $source!”
echo “Directory either does not exist, or you do not have proper permissions.”
exit 2
fi
done

if [ -f $EXCLUDE_FILE ]; then
EXCLUDE=”–exclude-from=$EXCLUDE_FILE”
fi

echo “Sources verified. Running rsync…”
for source in $SOURCES; do

# Create directories in $RTARGET to mimick source directory hiearchy
if ! ssh -i $RKEY $RUSER@$RMACHINE “test -d $RTARGET/$source”; then
ssh -i $RKEY $RUSER@$RMACHINE “mkdir -p $RTARGET/$source”
fi

/usr/local/bin/rsync $VERBOSE $EXCLUDE -a –delete -e “ssh -i $RKEY” $source/$RUSER@$RMACHINE:$RTARGET/$source/

done

#creating directory for mysql backups
if ! ssh -i $RKEY $RUSER@$RMACHINE “test -x $RTARGET/$REMOTESQLPATH”; then
ssh -i $RKEY $RUSER@$RMACHINE “mkdir -p $RTARGET/$REMOTESQLPATH”
fi

for sqldb in $DATABASES; do
#making sql dumps
file=$TMPPATH/$sqldb.sql.gz
echo backing up $file…
/usr/local/bin/mysqldump -u$MYSQL_USER -p$MYSQL_PASSWORD $sqldb | gzip > $file
/usr/local/bin/rsync $VERBOSE $EXCLUDE -a –delete -e “ssh -i $RKEY” $file $RUSER@$RMACHINE:$RTARGET/$REMOTESQLPATH
rm $file
done

exit 0

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s