linux Two Servers Realize Automatic File Synchronization

  • 2021-08-21 22:03:34
  • OfStack

Boot or restart on server B (172.17. 166.11) will automatically pull all files in the specified directory on server A (172.17. 166.10)

1. Create trust between server B and server A

(1) Execute ssh-keygen-t rsa 1 carriage return on server B
(2) Execute ssh-copy-id-i 172.17. 166.10 Enter the password for server A on server B
(3) Perform ssh 172.17. 166.10 on the server B to verify whether you can log on to the server A without secret

2. On the server B

Create the directory structure as follows


[root@w-11 home]# tree shell
shell
 --  logs ---- Directory 
 Off-  pull_170.sh ---- Script 

The script is as follows:


#!/bin/bash
#pull_
#author:whz
#date:20200805
# Nonexistent variable terminates script execution 
set -o nounset
# Execution error terminates script execution 
set -o errexit
# define restricted path
PATH="/bin:/usr/bin:/sbin:/usr/sbin"
# adirname - return absolute dirname of given file
adirname() { odir=`pwd`; cd `dirname $1`; pwd; cd "${odir}"; }
MYNAM=`basename "$0"`
MYDIR=`adirname "$0"`
MYLOG_PATH="${MYDIR}/logs"
MYLOG="${MYLOG_PATH}/${MYNAM}_`date +%F`.log"
echo "`which rsync` -avtW --progress --delete root@172.17.166.10:/home/iis/ /home/iis/" >> ${MYLOG}
`which rsync` -avtW --progress --delete root@172.17.166.10:/home/iis/ /home/iis/ >> ${MYLOG}
exit 0

3. crontab plan on server B

crontab -e
@reboot /home/shell/pull_10.sh

Above, done.


Related articles: