我們有時可能會批量去操作服務器,比如批量在服務器上上傳某個文件,安裝軟件,執行某個命令和腳本,重啟服務,重啟服務器等,如果人工去一臺臺操作的話會特別繁瑣,并浪費人力。
這時我們可以使用expect,向目標服務器上發送指令去實現批量操作。
下面的例子將在centos上將一個文件,批量拷貝到其他服務商上,并執行相應的命令
1. 在centos上安裝expect
yum install expect
2. 編寫expect腳本 copyfilebatch.sh
下面的腳本將向內網IP為 192.168.0.102 至 192.168.0.112 的服務器分別拷貝一個rc.local文件,拷貝成功后,執行chmod命令,分別重啟服務器
#!/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 "#*"
#要執行的命令
send "chmod +x /etc/rc.d/rc.local\r"
send "reboot\r"
send "exit\r"
expect eof
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。