[英]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.