利用兩個腳本完成叢集中的所有電腦資料同步,當然也可以選擇使用 rsync 進行同步
目标:避免重複輸入不同的主機名, 不同的密碼
/root/bin/data_ssh.sh
#!/bin/bash
server=`grep -e -v "localhost|^#|^$" /etc/hosts | awk '{print $2}'`
echo -n "what is password: "
read pass
echo -n "command is: "
read command
for name in $server
do
/root/bin/data_auto_ssh.sh $name $pass $command
done
/root/bin/data_auto_ssh.sh
#!/usr/bin/expect -f
set host [lindex $argv 0 ]
set password [lindex $argv 1 ]
set command [lindex $argv 2 ]
set command1 [lindex $argv 3 ]
set command2 [lindex $argv 4 ]
set command3 [lindex $argv 5 ]
set command4 [lindex $argv 6 ]
set command5 [lindex $argv 7 ]
set command6 [lindex $argv 8 ]
set command7 [lindex $argv 9 ]
set command8 [lindex $argv 10 ]
set command9 [lindex $argv 11 ]
set timeout 10
spawn ssh root@$host $command $command1 $command2 $command3 $command4 $command5 $command6 $command7 $command8 $command9
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*password:" { send "$password\r" }
}
expect eof
用法
[root@test bin]# ./data_ssh.sh
what is password: 你的密碼
command is: ifconfig eth0 | grep mask | awk '{print $4}'
spawn ssh root@nginx_a ifconfig eth0 | grep mask | awk '{print $4}'
root@nginx_a's password:
mask:255.255.255.0
=================================
/root/bin/data_sync.sh
echo -n "source file is: "
read source
echo $source
echo -n "dest file is: "
read dest
echo $dest
/root/bin/data_auto_scp.sh $name $pass $source $dest
/root/bin/data_auto_scp.sh
set source [lindex $argv 2 ]
set dest [lindex $argv 3 ]
spawn scp -r $source root@$host:$dest
用法 (缺點,每次隻能夠傳輸一個檔案,待解決中, 也可以通過自動生成執行腳本方法解決)
如要傳輸整個目錄,可以填寫目錄名字,如 /root/bin
[root@test bin]# ./data_sync.sh
source file is: /root/bin/data_auto_ssh.sh
dest file is: /root/bin/
/root/bin/
spawn scp /root/bin/data_auto_ssh.sh root@nginx_a:/root/bin/
data_auto_ssh.sh