一、命令 except 實例詳解
1. 介紹 expect 使用場景
expect可以讓我們實現自動登錄遠程機器,並且可以實現自動遠程執行命令。當然若是使用不帶密碼的密鑰驗證同樣可以實現自動登錄和自動遠程執行命令。但當不能使用密鑰驗證的時候,我們就沒有辦法了。所以,這時候只要知道對方機器的賬號和密碼就可以通過expect腳本實現登錄和遠程命令。
使用之前先安裝 expect 軟件
yum install -y expect
2. 自動遠程登錄,登陸后不退出
#! /usr/bin/expect set user "root" set host "192.168.11.102" set passwd "123456" spawn ssh $user@$host expect { "yes/no" { send "yes\r"; exp_continue} "assword:" { send "$passwd\r" } } interact
3. 登錄后執行命令,然后退出
#!/usr/bin/expect set user "root" set host "192.168.11.18" set passwd "123456" spawn ssh $user@$host expect { "yes/no" { send "yes\r"; exp_continue} "password:" { send "$passwd\r" } } expect "]*" send "touch /tmp/12.txt\r" expect "]*" send "echo 1212 > /tmp/12.txt\r" expect "]*" send "exit\r"
4. 還可以傳遞參數
#!/usr/bin/expect set user [lindex $argv 0] set host [lindex $argv 1] set passwd "123456" set cm [lindex $argv 2] spawn ssh $user@$host expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect "]*" send "$cm\r" expect "]*" send "exit\r"
執行:
[root@localhost ~]# ./test.expect root 192.168.11.18 2
5. 自動同步文件
#!/usr/bin/expect set passwd "123456" spawn rsync -av root@192.168.11.18:/tmp/12.txt /tmp/ expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect eof
6. 指定 host 和要同步的文件
#!/usr/bin/expect set passwd "123456" set host [lindex $argv 0] set file [lindex $argv 1] spawn rsync -av $file root@$host:$file expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect eof
執行:
[root@localhost ~]# ./test.expect 192.168.11.18 /tmp/12.txt
二、構建文件分發系統
1. 需求背景
對於大公司而言,肯定時不時會有網站或者配置文件更新,而且使用的機器肯定也是好多台,少則幾台,多則幾十甚至上百台。所以,自動同步文件是至關重要的。
2. 實現思路
首先要有一台模板機器,把要分發的文件准備好,然后只要使用expect腳本批量把需要同步的文件分發到目標機器即可。
3. 核心命令
rsync -av --files-from=list.txt / root@host:/
4. 文件分發系統的實現
rsync.expect
#!/usr/bin/expect set passwd "123456"
set host [lindex $argv 0] set file [lindex $argv 1] spawn rsync -av --files-from=$file / root@$host:/
expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect eof
rsync.sh
#!/bin/bash for ip in `cat ip.list` do
echo $ip ./rsync.expect $ip list.txt done
5. 自動批量執行腳本命令
cat exe.expect
#!/usr/bin/expect set host [lindex $argv 0] set passwd "123456"
set cm [lindex $argv 1] spawn ssh root@$host expect { "yes/no" { send "yes\r"} "password:" { send "$passwd\r" } } expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
cat exe.sh
#!/bin/bash for ip in `cat ip.list` do
echo $ip ./exe.expect $ip "w;free -m;ls /tmp"
done
三、擴展 expect 語法介紹
shell腳本需要交互的地方可以使用 Here 文檔是實現,但是有些命令卻需要用戶手動去就交互如passwd、scp。對自動部署免去用戶交互很痛苦,expect能很好的解決這類問題。
1. expect的核心是spawn expect send set
spawn:調用要執行的命令
expect:等待命令提示信息的出現,也就是捕捉用戶輸入的提示:
send:發送需要交互的值,替代了用戶手動輸入內容
set:設置變量值
interact:執行完成后保持交互狀態,把控制權交給控制台,這個時候就可以手工操作了。如果沒有這一句登錄完成后會退出,而不是留在遠程終端上。
expect eof:這個一定要加,與 spawn 對應表示捕獲終端輸出信息終止,類似於 if....endif
expect 腳本必須以 interact 或 expect eof 結束,執行自動化任務通常 expect eof 就夠了。
2. 設置 timeout
設置 expect 永不超時
set timeout -1
設置 expect 300 秒超時,如果超過 300 沒有 expect 內容出現,則推出
set timeout 300