#!/usr/bin/expect
set timeout 30
spawn ssh -l root 192.168.0.2
expect "password:"
send "mypaasword\r"
interact
搜索expect相關(guān)文章,你多半會(huì)遇到上述這段代碼示例,具體我就不一行行講述了,請(qǐng)參加:
https://www.centos.bz/2013/07/expect-spawn-linux-expect-usage/
expect作用
expect用來(lái)實(shí)現(xiàn)不需人工干預(yù)的情況下,自動(dòng)的和交互式任務(wù)進(jìn)行通信。
比如,在不輸入密碼的情況下執(zhí)行一段腳本ssh一臺(tái)遠(yuǎn)端機(jī)器,本文開(kāi)頭那段代碼就是干這個(gè)的。
工作原理
expect等待輸出中輸出特定的字符,然后自動(dòng)做出響應(yīng)
基礎(chǔ)知識(shí)
expect命令可以接受一個(gè)字符串參數(shù)或者一個(gè)正則(-re),用來(lái)匹配該參數(shù)
$expect_out(buffer)存儲(chǔ)了所有對(duì)expect的輸入,<$expect_out(0,string)>存儲(chǔ)了匹配到expect參數(shù)的輸入
如下程序表示,當(dāng)expect從標(biāo)準(zhǔn)輸入等到hi
和換行時(shí),向標(biāo)準(zhǔn)輸出發(fā)送所有對(duì)expect的輸入,再發(fā)送expect參數(shù)hi
匹配到的輸入
#!/usr/bin/expect
expect "hi\n"
send "you typed <$expect_out(buffer)>"
send "but I only expected <$expect_out(0,string)>"
運(yùn)行如下:
[root@xxx test]# expect exp.sh
test1 #input
test2 #input
hi #input
you typed <test1 #output
test2 #output
hi #output
>but I only expected <hi #output
分支匹配
根據(jù)不同的輸入,做出不同的響應(yīng)
#!/usr/bin/expect
expect "morning" { send "good morning\n" } \
"afternoon" { send "good afternoon\n" } \
"evening" { send "evening\n" }
執(zhí)行輸出如下:
[root@xxx test]# expect exp.sh
morning #input
good morning #output
向expect傳遞參數(shù)
expect接收參數(shù)的方式和bash腳本的方式不太一樣,bash是通過(guò)$0 ... $n 這種方式,而expect是通過(guò)set <變量名稱(chēng)> [lindex $argv <param index>]
例如set username [lindex $argv 0]
,表示將調(diào)用該expect腳本的第一個(gè)參數(shù)($argv0)賦值給變量username
兩種特殊情況eof和timeout
- eof,一般用于判斷spawn啟用的進(jìn)程是否執(zhí)行完畢
#!/usr/bin/expect
spawn echo "test"
expect {
"ename:" {send "All\r"}
eof {send_tty "eof, will exit.\n";exit}
}
interact
執(zhí)行上述腳本,spawn啟用的進(jìn)程極短時(shí)間內(nèi)返回eof,expect向終端輸出eof, will exit.
[root@xxx test]# expect exp.sh
spawn echo test
test
eof, will exit.
如果沒(méi)有eof {send_tty "eof, will exit.\n";exit}
這一行,運(yùn)行程序,會(huì)報(bào)錯(cuò)
spawn_id: spawn id exp6 not open
while executing
"interact"
因?yàn)榇藭r(shí)spawn啟動(dòng)的進(jìn)程已退出
- timeout,當(dāng)expect期待匹配的字符在設(shè)置的超時(shí)時(shí)間內(nèi)沒(méi)匹配上時(shí),執(zhí)行timeout分支的邏輯
#!/usr/bin/expect
set timeout 5
expect {
"ename:" {send "All\r"}
timeout {send_tty "timeout, will exit.\n";exit}
}
上述腳本,執(zhí)行輸出:
[root@xxx test]# expect exp.sh #exec and don't input anything
timeout, will exit. #wait for 5 seconds, output
常用其他命令
Expect中最常用的命令:send,expect,spawn,interact。
send:用于向進(jìn)程發(fā)送字符串
expect:從進(jìn)程接收字符串
spawn:?jiǎn)?dòng)新的進(jìn)程
interact:允許用戶(hù)交互
expect和send一般成對(duì)搭配使用,spawn用來(lái)啟用新的進(jìn)程,spawn后續(xù)的expect用來(lái)和spawn啟用的新進(jìn)程交互,interact可以理解為暫停自動(dòng)交互,從而讓用戶(hù)可以手動(dòng)干預(yù)交互過(guò)程,比如自動(dòng)ssh到遠(yuǎn)程機(jī)器,執(zhí)行interact后,用戶(hù)可以手動(dòng)輸入命令操作遠(yuǎn)程機(jī)器
Reference
http://www.cnblogs.com/lzrabbit/p/4298794.html
http://hf200012.iteye.com/blog/1866167
http://blog.csdn.net/leexide/article/details/17485451