Specify SSH Identity File for Curl

This article explains how to specify a private key (identity file) for public key authentication when using the curl command-line tool. You will learn the exact flags required to securely connect to SFTP or SCP servers using your SSH keys, along with practical command examples.

When transferring files over SFTP or SCP using curl, you can authenticate using SSH keys instead of passwords. To do this, you must explicitly point curl to your private key (the identity file) and, in most cases, your public key.

The Key Flags

To perform public key authentication, curl utilizes two primary command-line options:

Command Syntax

The basic syntax for an SFTP download using public key authentication is as follows:

curl --key ~/.ssh/id_rsa --pubkey ~/.ssh/id_rsa.pub sftp://username@example.com/path/to/file.txt -o local_file.txt

Handling Key Passphrases

If your private key is protected by a password (passphrase), you must provide it to curl. You can pass the passphrase using the -u (or --user) flag:

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

If you prefer not to leave your passphrase in the shell history, you can prompt for it by leaving the password field blank:

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

Key Points to Remember

  1. Protocol Support: Public key authentication in curl is only supported for SSH-based protocols, such as sftp:// and scp://.
  2. File Formats: Ensure your keys are in a compatible format (usually OpenSSH or PEM formats) supported by the underlying SSH library (libssh2 or libssh) that your version of curl was compiled with.