19

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!

3 Answers 3

48

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!

1
  • 1
    i tried \ or \\ as SOMEDELIMTER, it doesn't work, use @ it is OK
    – netawater
    Commented Nov 5, 2021 at 8:27
12

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
2
  • 15
    does not work with sftp servers that only support sftp. error "exec request failed on channel 0"
    – Pieter
    Commented Nov 29, 2016 at 2:47
  • 2
    SCP is a different protocol and it is not available in all cases. So on SFTP only servers you will get error This service allows sftp connections only.
    – Martin
    Commented Nov 28, 2021 at 12:30
8

I don't know how sftp was configurable when this question was asked. Anyway, 6 years later, you can put sftp-commands like PUT into a file and then reference this file in your initial sftp-call. The makes the whole process completely non-interactive and easily configurable:

sftp -i /path/to/ssh-key -b /path/to/sftp-commands.txt root@remote:/root/dropoff

....Where sftp-commands.txt just contains

put test.txt; quit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.