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

  • -u "username:": Specifies the SFTP username. The colon (:) at the end of the username is crucial; it tells curl to expect an empty password so it does not prompt you for one.
  • --key ~/.ssh/id_rsa: Path to your private SSH key.
  • --pubkey ~/.ssh/id_rsa.pub: Path to your public SSH key. Note: The underlying library curl uses for SFTP (libssh2) often requires both the private and public keys to complete the handshake.
  • sftp://example.com/...: The protocol and the full path to the target file on the remote server.

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/