溫馨提示×

Linux中expect命令如何處理輸出

小樊
164
2024-12-01 07:20:05
欄目: 智能運維

Expect是一個用于自動化交互式應用程序的工具,如登錄、文件傳輸等

  1. 使用spawn命令啟動交互式程序:
spawn <command>

例如,要啟動SSH會話,可以使用:

spawn ssh user@example.com
  1. 使用expect命令等待特定的字符串出現:
expect "<string>"

當Expect腳本檢測到指定的字符串時,它將自動發送相應的命令。例如,要等待SSH登錄提示符(通常是$%),可以使用:

expect "$"
  1. 使用send命令發送命令到交互式程序:
send "<command>\r"

\r是回車符,用于模擬用戶按下Enter鍵。例如,要輸入用戶名,可以使用:

send "username\r"
  1. 使用interact命令進入交互模式:
interact

在交互模式下,用戶可以直接與交互式程序進行交互,而無需腳本干預。要退出交互模式,可以按Ctrl+C兩次。

  1. 使用close命令關閉當前交互式程序:
close
  1. 使用變量和循環處理輸出: Expect支持使用變量和循環來處理輸出。例如,要存儲命令的輸出到一個變量中,可以使用lindex命令:
set output [lindex $expect_out(buffer) 0]

要循環處理輸出,可以使用while循環:

while {$output ne ""} {
    # 處理輸出的邏輯
    set output [lindex $expect_out(buffer) 0]
}

這是一個簡單的Expect腳本示例,用于自動登錄SSH服務器并執行命令:

#!/usr/bin/expect

set timeout 20
set username [lindex $argv 0]
set password [lindex $argv 1]
set command [lindex $argv 2]

spawn ssh $username@example.com
expect "$ "
send "$password\r"
expect "$ "
send "$command\r"
expect "$ "
interact

要運行此腳本,請將其保存為auto_ssh.exp,并確保它具有可執行權限(使用chmod +x auto_ssh.exp)。然后,可以通過以下方式運行腳本:

./auto_ssh.exp username password "command"

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女