################
expect:
################
[set timeout 10]:設置超時時間,單位s,timeout -1永不超時
[ spawn ssh root@ip ]:是進入expect環境後纔可以執行的expect的內部命令。主要功能是給ssh運行進程加個殼,用來傳遞交互指令。
[ expect "password:"]:判斷上次輸出結果是否包含"password:"的字符串,如果有立即返回,否則就等待一段時間,就是set timeout 10的時間。
[ send "yes\r"]:執行交互動作,與手動輸入一樣。
[ interact ]:保持交互狀態,留在遠程終端
[ $argv ]:參數數組,[ lindex $argv n],n從0開始
################
#!/usr/bin/expect ##shell類型
set ip [lindex $argv 0] ##接受第一個參數
set password [lindex $argv 1] ##接受第二個參數
set timeout 10 ##設置超時時間,單位s,timeout -1爲永不超時
spawn ssh root@ip ##發送ssh請求
expect{ ##返回匹配信息
"*yes/no" {send "yes\r";exp_continue} ##第一次ssh連接會提示yes/no,繼續
"*password:"{send "$password\r"} ##出現密碼提示,發送密碼
}
interact ##交互模式,用戶會停留在遠程服務器上
#!/usr/bin/expect
set ip [lindex $argv 0]
set password redhat ##登錄密碼爲redhat(已知密碼的情況)
set timeout 10
spawn ssh root@ip
expect{
"*yes/no" {send "yes\r";exp_continue}
"*password:"{send "$password\r"}
}
interact
#!/usr/bin/expect
set ip [lindex $argv 0]
set password redhat
set timeout 10
spawn ssh root@ip
expect{
"*yes/no" {send "yes\r";exp_continue}
"*password:"{send "$password\r"}
}
expect "#*" ##登錄後
send "pwd\r" ##執行密令pwd,查看當前路徑
send "exit\r" ##退出
expect eof