I want to transfer a .png file from a directory on my computer to a directory on a remote server.
I have to use SFTP to secure the file and transfer mode. And I already have a UNIX script (.ksh) file to copy the files in the normal mode. How do I implement the transfer in SFTP mode?
Use sftp
instead of whatever command you are using in your .ksh script. See sftp man for reference.
You may also want to look at scp
secure copy - scp man.
sftp
is mostly for interactive operations, you need to specify host you want to connect to:
sftp example.com
you will be prompted for username and passsword, and the interactive session will begin..
Although it can be used in scripts, the scp
is much more easy to use:
scp /path/to/localfile user@host:/path/to/dest
you will be prompted for password..
Both scp
and sftp
use ssh
as underlying protocol, see this and this
The best way to setup them to run from scripts is to setup passwordless authentication using keys. See this and this. I use this extensively on my servers.. After you setup keys, you can run
scp -i private-key-file /path/to/local/file user@host:/path/to/remote
sftp -oIdentityFile=private-key-file -b batch-file user@host
If you want to authenticate with password, you may try the expect
package. The simplest script may look like this:
#!/usr/bin/expect
spawn sftp -b batch-file user@host
expect "*?assword:*"
send "pasword\n"
interact
See this, this and this for more info.
Make a file and save it as my_batch_file:
cd /root
get blah.txt
bye
Run this to execute your batch file:
eric@dev /home/el $ sftp [email protected] < my_batch_file
Connecting to 10.30.25.15...
Password:
sftp> cd /root
sftp> get blah.txt
Fetching /root/blah.txt to blah.txt
sftp> bye
The file is transferred
That moved the blah.txt
from remote computer to local computer.
If you don't want to specify a password, do this:
How to run the sftp command with a password from Bash script?
Or if you want to do it the hacky insecure way, use bash and expect:
#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "
You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With