脚本专栏 
首页 > 脚本专栏 > 浏览文章

Shell脚本实现线上服务器之间对比文件是否一致

(编辑:jimmy 日期: 2024/11/15 浏览:3 次 )

工作中有时需要对比文件是否一致,通过以下脚本可以实现(比较简单):分享出来,希望能帮助到有同样需求的朋友~

复制代码 代码如下:
#!/bin/bash
#对比服务器上文件是否一样
# Richard shen 2012/07/08
LC_ALL='en_US.UTF-8'
basedir=`dirname $0`
HOST=$basedir/host.txt
PASSWD="abcd"   #密码
FILE=$basedir/file.txt  
LOG=$basedir/tmp.log
>$LOG
[ ! -f /usr/bin/nc ] && yum -y install nc
[ ! -f /usr/bin/expect ] && yum -y install expect
auto_smart_ssh () {
    expect -c "set timeout -1;
        spawn ssh -o StrictHostKeyChecking=no $2 ${@:3};
                 expect {
                         *assword:* {send -- $1\r;
                         expect {
                             *denied* {exit 2;}
                             eof
                                }
                         }
                  eof     {exit 1;}
                  }
                                  "
 #   return $"^#" ]] && continue
       let 'num++'
       if ! /usr/bin/nc -w 1 $host 22 > /dev/null; then
          echo " ssh connect failed." | tee -a $LOG
          continue
       else
          echo -e "\e[32m$host ($FILE) MD5 compared files...\e[0m"
          auto_smart_ssh $PASSWD root@$host md5sum $file | grep $file | grep -v StrictHostKeyChecking | tee -a $LOG
      fi
    done
echo "----------------------------------------------------------"
done

对比的IP地址写入host.txt,需要对比的文件(支持多个文件)写入file.txt
输出结果为:
复制代码 代码如下:
192.168.113.108 (./file.txt) MD5 compared files...
c84509bb3b109506935dba56b667a136  /data/server/www/apps/ad/fullcollumn.html
192.168.113.111 (./file.txt) MD5 compared files...
c84509bb3b109506935dba56b667a136  /data/server/www/apps/ad/fullcollumn.html
----------------------------------------------------------
192.168.113.108 (./file.txt) MD5 compared files...
d2c965f5222ff47432313c76863f428d  /data/server/www/apps/ad/sky.html
192.168.113.111 (./file.txt) MD5 compared files...
d2c965f5222ff47432313c76863f428d  /data/server/www/apps/ad/sky.html

上一篇:Shell脚本实现监控iptables规则是否被修改
下一篇:expect实现单台、多台服务器批量scp传输文件