expect -- 自動登錄ssh 堡壘機

 常用命令:

# 命令行參數 
# $argv,參數數組,使用[lindex $argv n]獲取,$argv 0爲腳本名字
# $argc,參數個數
set username [lindex $argv 1]  # 獲取第1個參數
set passwd [lindex $argv 2]    # 獲取第2個參數
 
set timeout 30 # 設置超時
 
# spawn是expect內部命令,開啓ssh連接
spawn ssh -l username 192.168.1.1
 
# 判斷上次輸出結果裏是否包含“password:”的字符串,如果有則立即返回,否則就等待一段時間(timeout)後返回
expect "password:"
 
# 發送內容ispass(密碼、命令等)
send "ispass\r"
 
# 發送內容給用戶
send_user "$argv0 [lrange $argv 0 2]\n"
send_user "It's OK\r"
# 執行完成後保持交互狀態,控制權交給控制檯(手工操作)。否則會完成後會退出。
interact

自動登錄ssh 

#!/usr/bin/expect -f  
set ip [lindex $argv 0 ]         # 接收第1個參數,作爲IP
set username [lindex $argv 1 ]   # 接收第2個參數,作爲username
set mypassword [lindex $argv 2 ] # 接收第3個參數,作爲密碼
set timeout 10                   # 設置超時時間 
 
spawn ssh $username@$ip       # 發送ssh請求
expect {                      # 返回信息匹配 
"*yes/no" { send "yes\r"; exp_continue}  # 第一次ssh連接會提示yes/no,繼續  
"*password:" { send "$mypassword\r" }    # 出現密碼提示,發送密碼  
} 
interact        # 交互模式,用戶會停留在遠程服務器上面

參考:http://xstarcd.github.io/wiki/shell/expect.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章