kalor

导航

 

需求描述:备份所有线上服务器squid、httpd、mysql、nginx的配置文件

环境:在公司内网采用expect+shell脚本模式,进行批量备份。expect脚本通过ssh登录服务器,从本地copy一份shell脚本到服务器上,然后执行脚本将配置文件遍历出来传到指定服务器进行备份。

1、expect脚本batch_backupconf.exp

#!/usr/bin/expect
set timeout 30
set target_host [lrange $argv 0 0]
set target_port [lrange $argv 1 1]
set source_host sphinx1906.phpdba.com
set source_port 9191
set login_name root
set password 123456

spawn ssh $target_host -p $target_port -l $login_name -i /root/.ssh/id_rsa

expect {
        "*(yes/no)?"         {
                send  "yes\r"
                exp_continue
        }
        "*assword:"      {
                send "$password\r"
        }
}

expect "#"
send "uname\n"
expect "Linux"
send_user "Now you can do some operation on this terminal\n"
expect "#"
send "scp -P $source_port $source_host:/root/chen-123/expect/backup_conf.sh 
        \/root/ \n"
exec sleep 15
send_user "开始执行代码 \n"
send "sh backup_conf.sh $target_host \n"
expect {
        "*(yes/no)?"    {
                send  "yes\r"
                exp_continue
        }
        "*assword:"     {
                send "$password\r"

        }
}
exec sleep 5
expect "#"
send "rm -f backup_conf.sh \n"
send_user "\nThis is $source_host!\n操作完成!\n"
exec sleep 1
exit

2、shell脚本backup_conf.sh

#!/bin/sh
if [ $# != 1 ];then
        echo "请传参数!"
        exit 1;
fi

for i in `find /opt/phpdba/ -maxdepth 4 -type f -regex ".*\.\(com\|conf\|cnf\)" 
          \-print|grep -E 'httpd\.conf|nginx\.conf|squid\.conf|*\.com|*\.cnf'`;
       do        
        tmp=`echo "$i"|sed s#/#_#g`        
        echo $i
        scp -Pxxx $i xxx.xxx.xxx.xxx:/opt/phpdba/backup_conf/$1_${tmp}
         \`date +%Y%m%d%H`
done

3、batch_backupconf.sh

#!/bin/sh
cat iplist_all|while read line
do
        host_ip=`echo "$line"|awk -F'\t' '{print $1}'`
        host_port=`echo "$line"|awk -F'\t' '{print $2}'`
        echo $host_ip"->"$host_port
        /usr/bin/expect batch_backupconf.exp $host_ip $host_port
done

4、iplist_all
192.168.0.9 22
192.168.0.213 22
192.168.0.114 29622
192.168.0.116 29622

posted on 2014-05-04 14:51  kalor  阅读(1001)  评论(0编辑  收藏  举报