我們有時(shí)可能會(huì)批量去操作服務(wù)器,比如批量在服務(wù)器上上傳某個(gè)文件,安裝軟件,執(zhí)行某個(gè)命令和腳本,重啟服務(wù),重啟服務(wù)器等,如果人工去一臺(tái)臺(tái)操作的話會(huì)特別繁瑣,并浪費(fèi)人力。
這時(shí)我們可以使用expect,向目標(biāo)服務(wù)器上發(fā)送指令去實(shí)現(xiàn)批量操作。
下面的例子將在centos上將一個(gè)文件,批量拷貝到其他服務(wù)商上,并執(zhí)行相應(yīng)的命令
1. 在centos上安裝expect
yum install expect
2. 編寫(xiě)expect腳本 copyfilebatch.sh
下面的腳本將向內(nèi)網(wǎng)IP為 192.168.0.102 至 192.168.0.112 的服務(wù)器分別拷貝一個(gè)rc.local文件,拷貝成功后,執(zhí)行chmod命令,分別重啟服務(wù)器
#!/usr/bin/expect -f
set password rootpassword
for {set i 102} {$i <= 112} {incr i} {
set ip "192.168.0.$i"
puts "$ip"
spawn ssh -o StrictHostKeyChecking=no $ip
set timeout 3
expect "root@$ip's password:"
set timeout 3
send "$password\r"
set timeout 3
send "exit\r"
spawn scp /home/install/rc.local root@$ip:/etc/rc.d/rc.local
set timeout 3
expect "root@$ip's password:"
set timeout 3
send "$password\r"
set timeout 3
send "exit\r"
spawn ssh root@$ip
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*password:" { send "$password\r" }
}
expect "#*"
#要執(zhí)行的命令
send "chmod +x /etc/rc.d/rc.local\r"
send "reboot\r"
send "exit\r"
expect eof
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。