bash 使用 sftp 下载文件的脚本

bash script which downloads a file with sftp

我需要使用密码建立 sftp 连接并下载文件。有一个 ip 限制,所以首先我应该建立一个 ssh 连接。我写了一个脚本,但在使用 ssh 连接后它卡住了。

注意:我也试过用 expect 脚本来做,但也没用。

#!/usr/local/bin/
ssh test@test1.t.com
lftp sftp://test2:123456@test2.com
get "file.xls"

编辑:您也可以在此处查看我的期望代码。

#!/usr/local/bin/expect -f
expect -c "
spawn ssh test@test1.t.com
expect \"test\@test1\:\~$\"
spawn sftp test2@test2.com
expect \"*assword:\"
send \"123456\r\"
expect \"sftp\>\"
send \"get file.xls\r\" 
expect \"sftp\>\" 
exit 1
";

我不确定您要在这里完成什么。首先,我将解决您的 expect 脚本中的问题。由于您的 shebang 行调用了 expect,因此您不需要将 expect 主体包装在对 expect 的调用中。这摆脱了所有的反斜杠。接下来,您有 2 个 spawn 调用,这会引发有关您的意图的问题。我假设您想通过 ssh 连接到 test1,然后从 test2 抓取文件,这样文件就存在于 test1 上。此假设将第二次生成更改为普通的 send 命令。

#!/usr/local/bin/expect -f

set shell_prompt "test@test1:~$"
set sftp_prompt "sftp>" 

spawn ssh test@test1
expect $shell_prompt
send "sftp test2@test2\r"
expect "*assword:"
send "123456\r"
expect $sftp_prompt
send "get file.xls\r" 
expect $sftp_prompt
send "exit\r"
expect $shell_prompt
send "exit\r"
expect eof

现在,您可以scp将文件传输到您的本地计算机。让我们将这 2 个步骤合并到一个 shell 脚本中:

#!/bin/sh

expect <<'EXPECT_SCRIPT'
    set shell_prompt "test@test1:~$"
    set sftp_prompt "sftp>" 

    spawn ssh test@test1
    expect $shell_prompt
    send "sftp test2@test2\r"
    expect "*assword:"
    send "123456\r"
    expect $sftp_prompt
    send "get file.xls\r" 
    expect $sftp_prompt
    send "exit\r"
    expect $shell_prompt
    send "exit\r"
    expect eof
EXPECT_SCRIPT

scp test@test1:file.xls .