我有一个简单的脚本,可以使用rsync通过ssh从远程服务器备份数据。
我有外部配置文件。在此配置文件中,我具有变量:OPTIONS,REMOTE_IP,SOURCE和DESTINATION。
现在,我需要添加更多的远程服务器,并开始对多个服务器使用单个脚本。我想用配置中的部分(例如[SERVER_01],[SERVER_02] ...)定义它。
脚本:
# You can provide external configuration file if you specify it with -c option
# Then if you haven't specified it, use one from ~/rsync_script/config.cfg
if [[ $1 == -c ]]; then
CONFIG_FILE=$2
else
CONFIG_FILE=~/rsync_script/config.cfg
fi
# Add constants from config file to script's environment
if [[ -f $CONFIG_FILE ]]; then
. $CONFIG_FILE
fi
# Create full path before running rsync, because rsync cannot mkdir with -p option
# Run rsync with parameters from config.cfg and put files to $DESTINATION/$REMOTE_IP/YYYY-MM-DD
if [[ -d $DESTINATION ]]; then
mkdir -p $DESTINATION$REMOTE_IP/$(date +"%A")
rsync -avx \
--timeout=30 \
$OPTIONS \
rsync@$REMOTE_IP:$SOURCE $DESTINATION$REMOTE_IP/$(date +"%F")
else
echo "failure"
fi
配置:
# Set extra options for rsync command
OPTIONS="--itemize-changes --log-file=changes.log"
# Set IP address of server the you want to backup
REMOTE_IP="192.168.11.123"
# Set the folder on remote server to backup
SOURCE="/home/rsync/somedata"
# Set the destination folder on local machine
DESTINATION="/backup/"
请给我建议解决此问题的最佳方法
欢迎任何代码注释和建议:)
谢谢
这是一个可能的情况。将您现有的rsync代码(if [[ -d $DESTINATION ...
)放入shell函数中,例如runbackup
,然后用. $CONFIG_FILE
读取文件并查找[SERVER_...]
节分隔符的循环替换执行该操作的部分。找到一个后,它将调用runbackup函数(第一个函数除外)。对于其他行,它eval
就像在每行上一样.
。为了确保在最后一节中调用runbackup,将一个虚拟[END]
节添加到输入中。
(cat $CONFIG_FILE; echo '[END]') |
while read line
do if [[ "$line" =~ ^\[([A-Z_0-9]+)\] ]]
then if [ -n "$OPTIONS" -a -n "$REMOTE_IP" ]
then echo "section $section"
runbackup
fi
section=${BASH_REMATCH[1]} # captured from =~ regex above
unset OPTIONS REMOTE_IP SOURCE DESTINATION
else eval $line
fi
done
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句