【问题标题】:bash script which downloads a file with sftp使用 sftp 下载文件的 bash 脚本
【发布时间】:2015-06-16 19:14:22
【问题描述】:

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

注意:我也尝试使用期望脚本执行此操作,但也没有用。

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

【问题讨论】:

  • 你有没有考虑过使用scp,它使用与ssh和sftp相同的协议??
  • @ryekayo test2 需要一个需要密码的 sftp 连接,scp 不起作用...
  • @klakson1345 :您能发布您的expect 代码,以便我们尝试找出问题所在吗?
  • @4ae1e 请告诉我如何使用需要密码连接的 scp
  • @Dinesh 你现在可以看到了,谢谢。

标签: shell unix ssh sh expect


【解决方案1】:

我不确定您究竟想在这里完成什么。首先,我将解决您的期望脚本中的问题。由于您的 shebang 行调用了期望,因此您无需将期望主体包装在对期望的调用中。这消除了所有的反斜杠。接下来,您有 2 个生成呼叫,这引发了有关您的意图的问题。我假设你想通过 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 .

【讨论】:

  • 感谢您将 expect 和 bash 结合起来的好例子
  • 你知道如何在期望
  • 在shell部分,将变量导出到环境export user=someone server=somewhere,然后在expect代码中,引用环境变量ssh $env(user)@$env(server)
猜你喜欢
  • 2012-07-29
  • 1970-01-01
  • 2014-06-21
  • 2019-11-02
  • 2010-11-29
  • 2016-05-27
  • 2015-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多