簡體   English   中英

如何使用期望從 SFTP 服務器捕獲 sftp ls 命令的 output?

[英]How to capture the output of sftp ls command from an SFTP server using expect?

自過去三天以來,我一直在努力編寫 bash 腳本,該腳本可自動從 SFTP 服務器下載文件。 我已經構建了程序的結構,並在片段中對其進行了測試,但這就是我堅持的。

我因此登錄到 SFTP 服務器:

/usr/bin/expect <<EOD
spawn sftp $ftp_server
expect "password:"
send "$password\r"
expect "sftp>"
send "ls\r"
expect "sftp>\r"
send "exit\r"
EOD

我想遍歷ls命令的 output 來決定下載哪個文件。 我嘗試將 output 重定向到一個文本文件,然后從那里獲取文件名,但它也存儲了“sftp>”提示和其他不相關的信息。 如何存儲干凈的ls expect並循環遍歷它?

使用-b開關來傳遞帶有命令( ls )的腳本,而不是將它們輸入標准輸入中。

這樣, sftp將在沒有提示的情況下以批處理模式運行。

有一個示例如何捕獲所有要列出的文件名:

#!/bin/sh
# the next line restarts using expect \
    LC_TYPE=C exec expect -f "$0" -- "$@"

# do not show sftp output by default 
log_user 0

set ftp_server 127.0.0.1
set password pass
set sftp_prompt {sftp> }

spawn -noecho sftp $ftp_server

expect "password:"
send "$password\r"

expect $sftp_prompt

# 'ls -1' will show filenames line by line
send "ls -1\r"

# ignore echo of command from sftp
expect -re {ls -1\r?\n}

# init empty list for filename collecting
set files {}

expect -re {([^\r\n]+)\r?\n} {
    # catch each filename line by line and put it to list 'files'
    lappend files $expect_out(1,string)

    # run current 'expect' again to catch next filename
    exp_continue
} -ex $sftp_prompt {
    # catch sftp prompt to break
}

# loop over example :)
foreach f $files {
    puts $f
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM