I'm looking for a way to set a specific SSH key while logging to a remote host with a particular username. Is this possible within the SSH config file?

For example:

Use key "id_rsa-test" for username "testuser":

ssh testuser@host1
ssh testuser@host2
ssh testuser@host3

Use key "id_rsa" for all other users.

ssh root@host1
ssh admin@host2
ssh user@

Is there a way to configure this?


Thank you @xhienne (comment link) for your suggestion.

Adding the following to ssh_config appears to have solved the problem:

Match User testuser
  IdentityFile ~/.ssh/id_rsa-test

This block should be placed above Host * to send id_rsa-test ahead of id_rsa for testuser.

  • You're welcome. You may even accept your own answer. – xhienne Jul 27 '17 at 1:42

Assuming you're using OpenSSH you can configure your ~/.ssh/config file for each, then you won't have to specify a user either, you can create your own name:

host host1
    User testuser
    IdentityFile ~/.ssh/id_rsa-test

then when you do ssh host1 it will do that automatically, or, since you will use host1 as other users too you can do

host test-host1
    User testuser
    IdentityFile ~/.ssh/id_rsa-test
    Hostname host1

then do ssh test-host1

and you can do the same for each host you want.

Any host that isn't matched by an entry in your ssh_config(5) file will use the default behavior--or use the defaults that are specified in ssh_config at the global setting, i.e., not inside a host block

ssh_config doesn't support matching on usernames, but you could write a shell script to detect that for you. Here's a fragile one in bash that assumes your username/host is always the first argument and will break if it is not:

ssh() {
    if [[ "$1" =~ ^testuser@ ]]; then
        command ssh -i ~/.ssh/id_rsa-test "$@"
        command ssh "$@"
  • Is it possible to use host * and / or create a rule that can match the username? Assuming there are lots of hosts, making it inefficient to create configs for each. – user2248259 Jul 27 '17 at 0:50
  • @user2248259 I don't know of a way to use the username as part of the pattern to match in ssh_config. I suppose you could always try writing a shell function to check the username and add appropriate arguments as desired if no one else has a config-based answer and you don't want to have different host entries for each – Eric Renouf Jul 27 '17 at 0:57
  • @user2248259 I provided a fragile example shell function that could try to help with this situation – Eric Renouf Jul 27 '17 at 1:03
  • 1
    @Eric, you mean ssh -i, right? Not ssh -I. Moreover, in ssh_config, the Match directive allows to check against the user part. – xhienne Jul 27 '17 at 1:26
  • @xhienne yes, I did mean that, and I didn't know that about the match directive! – Eric Renouf Jul 27 '17 at 1:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.