依賴
apt install tcl expect
測試遠程登陸獲取ifconfig
# cat action.exp
#!/bin/expect # 指定解釋器
set ip [lindex $argv 0] # 獲取執行時的參數
set pwd [lindex $argv 1]
set timeout 3 # 指定expect的超時時間
spawn ssh -p33322 jeff@$ip # 與後面的expect eof對應,指定一個運行過程
expect {
"yes/no" {send "yes\r" ;exp_continue} # expect指定當輸出結果中包含yes/no的時候,輸入yes
"password" {send "$pwd\r"}
}
expect "#" # 指定當登入成功後,命令輸入前包含#號時再執行下面操作,如果在超時時間過了後依舊沒有出現,則會退出
send "ifconfig |grep -E '10|175' \r" # send命令輸入遠程執行的命令
send "exit\r" # 退出遠程ssh
expect eof # 退出expect交互環境
運行
expect ./action.exp 10.0.2.53 password