How to Use Curl with SFTP and Private Key

This article explains how to authenticate with an SFTP server using the curl command-line tool and an SSH private key. You will learn the exact command syntax required to securely connect, how to handle public key dependencies, and how to manage passphrase-protected keys for both downloading and uploading files.

The SFTP Private Key Command

To authenticate and download a file from an SFTP server using an SSH private key, use the following command structure:

curl -u "username:" --key ~/.ssh/id_rsa --pubkey ~/.ssh/id_rsa.pub sftp://example.com/path/to/remote/file.txt

Parameter Breakdown


Handling Passphrase-Protected Keys

If your private key is encrypted with a passphrase, curl will fail unless you provide it. Use the --pass flag to pass the passphrase securely:

curl -u "username:" --key ~/.ssh/id_rsa --pubkey ~/.ssh/id_rsa.pub --pass "your_key_passphrase" sftp://example.com/path/to/remote/file.txt

Uploading a File Using Private Key

To upload a local file to the SFTP server instead of downloading one, add the -T (upload) flag to the command:

curl -T "localfile.txt" -u "username:" --key ~/.ssh/id_rsa --pubkey ~/.ssh/id_rsa.pub sftp://example.com/remote/path/