Transfer a file or a password over SFTP in a Bash script
Introduction
Connecting over sftp in bash is very simple: sftp user@domain.
If key authentication is configured for you then the sftp> prompt appears right away
If it is not configured, then you need to enter the password.
Suppose you need to transfer a file, and to do it from a script rather than by typing commands from the keyboard.
This task can puzzle a beginner, but if you use
expect
everything should work out.
Expect
expect is a language not identical to
bash
, therefore it needs
a separate script
We will call this script from the main bash script
#!/bin/bash
# The part of your bash script before the sftp transfer
# Call the script in the expect language
./expect_sftp_script
# The part of your bash script after the sftp transfer
Now let us turn directly to the script in the expect language
Note that the first line must be
#!/usr/bin/env expect
and not #!/bin/bash
That is exactly why the two scripts cannot be combined in one file
#!/usr/bin/env expect
# connect to the server
spawn sftp root@server
expect "sftp>"
# You can start sending commands
send "lcd /opt/input"
# After each command we simulate pressing Enter
send \n
expect "sftp>"
send "cd /tmp"
send \n
expect "sftp>"
send "put $test_file_sftp"
send \n
expect "sftp>"
send "exit"
Passing arguments
From a bash script you can pass variables into the expect script
Let us call the expect script with one argument
#!/bin/bash
# The part of your bash script before the sftp transfer
# Call the script in the expect language
# As the first argument we pass 1
./expect_sftp_script 1
# The part of your bash script after the sftp transfer
#!/usr/bin/env expect
set arg_from_bash [lindex $argv 0]
spawn sftp root@server
expect "sftp>"
send "lcd /opt/input"
send \n
expect "sftp>"
send "cd /tmp"
send \n
expect "sftp>"
send "put $arg_from_bash"
send \n
expect "sftp>"
# Close the connection
send "exit"
| Bash | |
| Bash Scripting | |
| -eq -gt …: Comparison operators | |
| if else: Conditional operators | |
| while loop | |
| date | |
| Newline | |
| Arithmetic operations | |
| Errors Bash |
Article author: Andrei Olegovich