Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transfer a file using sftp in UNIX

Tags:

sftp

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?

like image 854
Robin clave Avatar asked Apr 04 '13 10:04

Robin clave


2 Answers

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.

EDIT

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..

Edit 2

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.

like image 94
Shimon Rachlenko Avatar answered Oct 24 '22 00:10

Shimon Rachlenko


Send commands through sftp on one line:

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.

like image 24
Eric Leschinski Avatar answered Oct 24 '22 00:10

Eric Leschinski