使用expect对多台机器进行批量操作

Standard

file:hostlist

192.168.3.100	password
192.168.3.101	password
192.168.5.200	password
192.168.5.201	password
192.168.8.160	password
192.168.8.161	password

file:execute.sh

#!/bin/sh
HOST_LIST="/tmp/hostlist"
ERROR_LIST="/tmp/errorlist"
if [ -f /tmp/hosts ];then
  grep -v -E '^#|^$' /tmp/hosts | awk '{print $1,$2}' > $HOST_LIST
fi
while read HOST PASS
do
  if [ -n $HOST ] && [ -n $PASS ];then
    if ! expect memcached_restart.exp $HOST $PASS;then
      echo "$HOST" >> $ERROR_LIST
      continue
    fi
  fi
done < $HOST_LIST
rm -f $HOST_LIST

file:memcached_restart.exp(将所有机器上memcached的CACHESIZE改为96并重启memcached)

#!/usr/bin/expect -f
set address [lindex $argv 0]
set password [lindex $argv 1]
 
log_file ./exprct.log
 
spawn ssh -p 419 root@$address
set timeout 100
expect "*(yes/no)*" { 
  send "yes\r"
  expect "password:" 
  send "$password\r"
} "password:" { send "$password\r" } "*host " {exit 1}
expect "]#"
##############################################################
###         Modify /etc/sysconfig/memcached & Restart
##############################################################
send "sed -i '/CACHESIZE/s/64/96/g' /etc/sysconfig/memcached\r"
send "/etc/init.d/memcached restart\r"
##############################################################
send "exit\r"
expect eof

file:check_slave_db.exp(检测所有机器上的同步是否正常)

#!/usr/bin/expect -f
set address [lindex $argv 0]
set password [lindex $argv 1]
 
log_file ./exprct.log
 
spawn ssh -p 419 root@$address
set timeout 100
expect "*(yes/no)*" { 
  send "yes\r"
  expect "password:" 
  send "$password\r"
} "password:" { send "$password\r" } "*host " {exit 1}
expect "]#"

##############################################################
###         Check Slave Status
##############################################################
#send "mysql -u root -ppasswd -h127.0.0.1 -e 'show slave status\\G' | egrep 'Running|Behind|Master_Host'\r"
send "echo \$\(ifconfig \| grep '192'\)\$(mysql -u root -ppasswd -h127.0.0.1 -e 'show slave status\\G' \| grep 'Seconds'
)\r"
#############################################################
 
send "exit\r"
expect eof

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.