我們有時可能會批量去操作服務器,比如批量在服務器上上傳某個文件,安裝軟件,執行某個命令和腳本,重啟服務,重啟服務器等,如果人工去一臺臺操作的話會特別繁瑣,並浪費人力。
這時我們可以使用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 " set timeout 3 send "exit " 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 " set timeout 3 send "exit " spawn ssh root@$ip expect { "*yes/no" { send "yes "; exp_continue} "*password:" { send "$password " } } expect "#*" #要執行的命令 send "chmod +x /etc/rc.d/rc.local " send "reboot " send "exit " expect eof }
[月球人 ] CentOS使用expect批量遠程執行腳本和命令已經有502次圍觀