bash script which downloads a file with sftp

百般思念 提交于 2019-12-23 04:19:10

问题


I need to make a sftp connection with a password and download a file. There is an ip restriction so first of all i should make a ssh connection. I wrote a script but it stucks after connecting with ssh.

Note: i also tried doing it with an expect script but it also didn't work.

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

Edit: You can also see my expect code here.

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

回答1:


I'm not sure exactly what you're trying to accomplish here. First, I'll address the problems in your expect script. Since your shebang line invokes expect, you don't need to wrap the expect body in a call to expect. That gets rid of all the backslashes. Next, you have 2 spawn calls, which raises questions about you're intent. I'm going to assume that you want to ssh to test1, then grab the file from test2 so the file exists on test1. This assumption changes the 2nd spawn to a plain send command.

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

Now, you can scp the file to your local machine. Let's put those 2 steps into one shell script:

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


来源:https://stackoverflow.com/questions/29572089/bash-script-which-downloads-a-file-with-sftp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!