Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SFTP to send file with bash script

Tags:

file

bash

sftp

send

I'm using key authentication, so password is not an issue. I have a file whose name I know and I simply want to send it to another machine over sftp.

I tried searching but couldn't find this (seemingly simple) question anywhere. Perhaps my Google-fu is simply failing me today.

In short: I'm on my local machine, want to send a file (test.txt) to a remote machine. Authorized keys are already provided. Basically I want to automate these three steps:

sftp root@remote:/root/dropoff
put test.txt
quit

Is there a simple bash command I can use to automate this? The only option I've seen is using a bash script to perform the put/quit and using the -b option to run it. Is there anything cleaner than that? (I'm not interested in using any other applications/tools.)

Thanks!

like image 910
Bing Avatar asked Jul 31 '12 16:07

Bing


People also ask

How do I sftp a Unix shell script?

To initiate an SFTP connection, use sftp command with a username and remote host's name or IP. Default TCP port 22 should be open for this to work or else explicitly specify the port using -oPort flag. I'm connecting to an SFTP server with IP 192.168. 1.231 .


2 Answers

I know this is an old one, but you can also pass arguments to a command with a Here Document

You can put the following into a script:

# The following is called a HERE document
sftp <user>@<remote> << SOMEDELIMITER 
  put test.txt
  ... # any commands you need to execute via sftp
  quit
SOMEDELIMITER

each additional command will be fed into the command preceeding the << and SOMEDELIMTER can be anything you want it to be.

scp is a great option, however sftp was the only tool I was able to get working when pushing from linux to windows and you're stuck using FreeSSHD in service mode!

like image 122
Mike McMahon Avatar answered Sep 28 '22 11:09

Mike McMahon


You said that you are not interested in other tools, but scp is a much better choice for unattended file transfers. Here is an scp example:

scp test.txt root@remote:/root/dropoff
like image 21
jordanm Avatar answered Sep 28 '22 10:09

jordanm