Upload a file by command line via sftp.
Monday, June 16th, 2014
If you want to upload a file by commandline via SFTP, you may end up on this StackOverflow page. The answer there is WRONG. Those are not using the SFTP subsystem, they use SSH and process output redirection. Using scp will result in an error if the server only allows the SFTP subsystem:
This service allows sftp connections only.
Instead, use this:
$ echo "put system.log" | sftp upload@sftp.example.com:logs/ Connected to example.com. Changing to: /home/upload/logs/ sftp> put system.log Uploading system.log to /home/upload/logs/system.log system.log 100% 61 0.1KB/s 00:00
to upload a local file “system.log
” to the remote SFTP host in the logs/
directory. You can also use wildcards.
The above command generates some output you may not want. In that case you can use the -q switch and redirect output to /dev/null:
$ echo "put system.log" | sftp -q upload@sftp.example.com:logs/ > /dev/null Connected to example.com
As you can see, this still generates a little output. To fix this, we have to use batch mode:
$ cat batch.txt put *.log $ sftp -q -b batch.txt upload@sftp.example.com:logs/ > /dev/null $
Batch mode requires the use of a passwordless private key. If you don’t want to load it into a key agent (for automated scripts, etc), you can use the “-o IdentityFile
” option:
$ sftp -q -b batch.txt -o IdentityFile=key.rsa upload@sftp.example.com:logs/ > /dev/null