简体   繁体   English

如何使用期望从 SFTP 服务器捕获 sftp ls 命令的 output?

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

I've been struggling since the last three days to write a bash script which automates the downloading of files from an SFTP server.自过去三天以来,我一直在努力编写 bash 脚本,该脚本可自动从 SFTP 服务器下载文件。 I've built the structure of the program, have tested it in snippets but this is what I'm stuck on.我已经构建了程序的结构,并在片段中对其进行了测试,但这就是我坚持的。

I log into the SFTP server thus:我因此登录到 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

I want to loop over the output of the ls command to decide which file to download.我想遍历ls命令的 output 来决定下载哪个文件。 I tried redirecting the output to a text file and then picking up the file names from there, but it stores the "sftp>" prompts and other irrelevant information as well.我尝试将 output 重定向到一个文本文件,然后从那里获取文件名,但它也存储了“sftp>”提示和其他不相关的信息。 How can I store the clean ls output of expect and loop over it?如何存储干净的ls expect并循环遍历它?

Use -b switch to pass a script with the commands ( ls ), instead of feeding them in standard input. 使用-b开关来传递带有命令( ls )的脚本,而不是将它们输入标准输入中。

This way the sftp will run in a batch mode without prompts. 这样, sftp将在没有提示的情况下以批处理模式运行。

There is example how to catch all filenames to list: 有一个示例如何捕获所有要列出的文件名:

#!/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