如何使用bash从SFTP下载最新文件(连接使用密钥文件和密码)

问题描述 投票:0回答:1

我的主要问题是我无法从sftp下载最新文件。另外,我仅具有下载文件的权限。文件名示例:transaction_20200403060011_5e86xxxxxx.08595559.csv。下载所有文件:

   #!/usr/bin/expect
    spawn sftp -i /home/ubuntu/sc_sftp.txt [email protected] 
    expect "password:"
    send "xxx\n" 
    expect "sftp>"
    send "get *.csv\n"
    expect "sftp>"
    send "exit\n"
    interact

我只需要最新文件,所以我尝试将文件名保存为.txt文件并读取所需的文件名。使用bash命令可以正常工作。不幸的是,由于我使用了spawn和sftp命令,因此无法加载文件名。我的脚本不起作用:

#!/usr/bin/expect
spawn sftp -i /home/ubuntu/sc_sftp.txt [email protected] 
expect "password:"
send "xxx\n" 
expect "sftp>"
log_file -noappend RemoteFileList.txt
send "ls -1t\n"
expect "sftp>"
log_file
send "!sed -i '' '/ls -1/d' ./RemoteFileList.txt\n"
expect "sftp>"
send "!sed -i '' '/sftp>/d' ./RemoteFileList.txt\n"
expect "sftp>"
send "bye\n"
interact
set $file `(head -2 RemoteFileList.txt | tail -1)`
spawn sftp -i /home/ubuntu/sc_sftp.txt [email protected] 
expect "password:"
send "xxx\n" 
expect "sftp>"
send "get $file\n"
interact  

和错误:

can't read "file": no such variable
    while executing
"set $file `(head -2 RemoteFileList.txt | tail -1)`"
    (file "./s.sh" line 16)

添加这些命令后:

send "ls -1t\n"
expect -re "(.+)\r\nsftp>"
send " $expect_out(0,string)"
expect "sftp>"
send "exit\n"
interact

我有:

sftp> ls -1t
file1.csv
file2.csv
file3.csv
sftp>   ls -1t
file1.csv
file2.csv
file3.csv
sftp>
sftp> file1.csv
Invalid command.
sftp>
sftp> file2.csv
sftp>
sftp> file3.csv
sftp>
sftp> sftp>exit
Invalid command.

有人可以帮我这个吗?

sftp expect
1个回答
0
投票

这是期望的更乏味的方面之一。您将执行以下操作:

send "ls -1t\n"
expect -re "(.+)\r\nsftp>"

现在这些括号的内容(将是命令“ ls -1t”,后跟实际结果)存储在数组变量$expect_out(1,string)中-逗号周围没有空格。

期望使用\r\n作为换行符。

如果需要帮助解析结果,请在此处发布。

© www.soinside.com 2019 - 2024. All rights reserved.