How to Use OpenSSH SFTP with a Custom RSA/DSA Key via Command Line


2 views

While OpenSSH's ssh and scp commands clearly support the -i option for specifying identity files, the sftp command handles this differently. Many developers assume the same syntax would work across all SSH tools, but SFTP requires a slightly different approach.

The most reliable way is to create or modify your SSH config file:

Host myserver
    HostName example.com
    User remoteuser
    IdentityFile ~/.ssh/custom_key
    IdentitiesOnly yes

Then simply run:

sftp myserver

For one-time connections without modifying config files, you can use:

sftp -o "IdentityFile=~/.ssh/custom_key" -o "IdentitiesOnly=yes" user@host

The SFTP protocol is actually a subsystem of SSH, and the client inherits SSH's authentication methods. The -o flag passes options directly to the underlying SSH connection, which is why we use SSH-style configuration rather than a dedicated SFTP flag.

  • Ensure your key has proper permissions (600)
  • Use IdentitiesOnly=yes to prevent fallback to default keys
  • For debugging, add -v flag to see authentication attempts

Here's how to automate SFTP transfers in scripts:

#!/bin/bash
SFTP_CMD="put local_file.txt /remote/path/"
sftp -b - -o "IdentityFile=custom_key" user@host << EOF
$SFTP_CMD
EOF

Using PowerShell with the native OpenSSH client:

sftp -o "IdentityFile=C:\Users\user\.ssh\custom_key" user@host

When working with OpenSSH's SFTP client, many developers encounter a limitation: while ssh and scp commands offer the -i option to specify authentication keys, the sftp man pages don't clearly document this capability.

Despite the documentation gap, OpenSSH's SFTP client actually supports the same -i option as other SSH utilities. Here's the basic syntax:

sftp -i /path/to/private_key user@hostname

For RSA key authentication:

sftp -i ~/.ssh/custom_rsa_key developer@sftp.example.com

For DSA key authentication:

sftp -i /etc/ssh/project_dsa_key deploy@fileserver.example.org

When connecting to non-standard ports:

sftp -i ~/keys/special_key -P 2222 admin@backup.example.net

Combining with other options:

sftp -i ./client_key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null user@test.example.com

If you receive permission errors:

chmod 600 /path/to/private_key

For debugging connection problems:

sftp -v -i debug_key user@problemhost.example

Always ensure your private keys have proper permissions (600) and never expose them in shared directories. Consider using ssh-agent for better key management:

ssh-add ~/.ssh/project_key
sftp user@host