shell expect SSH用法一例

本文重點解決兩個問題:shell

  1. 獲取SSH遠程執行命令的返回狀態
  2. expect執行SSH時進程中不顯示密碼明文

先上Shell 代碼:bash

export IP CMD SSH_PWD
expect << 'END'
# 關閉輸出
log_user 0
set timeout 30
# 從系統變量獲取數據
set ip "$env(IP)"
set cmd "$env(CMD)"
set pwd "$env(SSH_PWD)"
spawn ssh root@$ip "$cmd"
expect {
    "(yes/no)?"                           {send "yes\r";exp_continue}
    # 忽略大小寫
    -nocase "password:"                   {send "$pwd\r";exp_continue}
    # 登陸成功,打開輸出
    -nocase "authentication successful"   {log_user 1;exp_continue}
    # 登陸失敗
    -nocase "authentication fail"         {exit 222}
    -nocase "permission denied"           {exit 222}
    eof
}
puts $expect_out(buffer)
lassign [wait] pid spawnid os_error_flag value
# 系統錯誤
if {$os_error_flag == -1} {
    puts "os errno: $value"
} else {
    # 返回 CMD 執行結果
    exit $value
}
END
exitCode=$?
if [ $exitCode -eq 222 ]; then
    echo 'log error'
elif [ $exitCode -ne 0 ]; then
    echo 'cmd error'
fi

獲取執行結果的關鍵在於【wait】方法的使用:ssh

wait [args]spa

delays until a spawned process (or the current process if none is named) terminates.線程

wait normally returns a list of four integers. The first integer is the pid of the process that was waited upon. The second integer is the corresponding spawn id. The third integer is -1 if an operating system error occurred, or 0 otherwise. If the third integer was 0, the fourth integer is the status returned by the spawned process. If the third integer was -1, the fourth integer is the value of errno set by the operating system. The global variable errorCode is also set.code

【wait】:延遲直到一個spawn進程結束。返回4個數值:orm

  1. expect 進程 pid
  2. spawn 線程 id
  3. OS狀態值(-1:系統錯誤,0:正常)
  4. spawn命令返回值(OS值爲 -1時返回OS錯誤代碼,爲 0時返回CMD退出值)

參考:expect manHow to get the exit code of spawned process in expect shell script?進程

開頭的兩個問題都獲得瞭解決:ip

  • 使用 wait 獲取SSH 遠程執行命令的返回狀態,登陸失敗也能夠經過指定狀態碼(222)標識;
  • 使用 env 讀取外部變量到expect 變量中,從而 PS 不會顯示 密碼明文。
相關文章
相關標籤/搜索