expect详解及自动登录脚本的实现
生活随笔
收集整理的這篇文章主要介紹了
expect详解及自动登录脚本的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
expect可以讓一些交互的任務自動完成,我們可以將一些交互過程寫入腳本,ssh登錄就是一個簡單的實現,下面將介紹expect的用法。
1 安裝
yum install -y expect2 語法介紹
expect - send
這兩個指令會配合使用,當expect接收到一個和預期字符串相匹配的輸入,會執行send指令,send會發出字符串或者對應的指令。
執行如下腳本
expect "yes\n" send "What you type in is $expect_out(buffer)" send "The correct input is $expect_out(0,string)" #note:$expect_out(buffer)儲存了所有對expect的輸入,$expect_out(0,string)儲存了所有相匹配值的輸入當你輸入為yes時,輸出結果為
yes What you type in is yes The correct input is yes當你輸入第一次不為所預期的字符串時,進程會繼續等待,直到你輸入為yes:
dd yes What you type in is dd yes The correct input is yesexpect也可像switch的語句一樣:
expect {"1\n" {send "one\n"}"2\n" {send "two\n"}"3\n" {send "three\n"} }spawn
spawn后面會加上一個命令,打開一個新的進程。
spawn ssh@root 192.168.1.1interact
執行完成后保持交互狀態,把控制權交給控制臺,這個時候就可以手工操作了。如果沒有這一句登錄完成后會退出,而不是留在遠程終端上。
3 自動登錄腳本示例
#!/usr/bin/expect set timeout -1 #設置超時時間,-1為用不超時 set ip "192.168.100.1" set passwd "root" set user "root" spawn ssh $user@$ip expect { "*yes/no" {send "yes\r";exp_continue} #exp_continue可以繼續執行下面的匹配 "*password" {send "$passwd\r"} } expect "login" send "pwd\r" #登錄成功執行pwd命令 interact轉載于:https://www.cnblogs.com/panyouming/p/9415158.html
總結
以上是生活随笔為你收集整理的expect详解及自动登录脚本的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联想电脑保修期(联想电脑保修期一般多长时
- 下一篇: 列表与for循环