6

I'm using Ubuntu. How can I use a private key in an ssh client for only one host? The private key is used for all hosts, every time I connect to any server, the private key authentication is used.

0

1 Answer 1

8

You need to create or edit your SSH configuration file at ~/.ssh/config.

For all the details, check man ssh_config. But basically, it consists of several entries like this:

Host example
    Hostname example.com
    User quber
    IdentityFile ~/.ssh/my_idfile

A Host line introduces each host, and the following lines are indented. The name on the Host line is a nickname (you will type ssh example instead of ssh [email protected].) If you don't want to use a nickname, you can use the full hostname:

Host example.com
    User quber
    IdentityFile ~/.ssh/my_idfile

Now ssh will automatically use the specified username and private key for this host, and only this host.

If you don't want the private key to be used for other hosts, make sure it is not named id_dsa, id_rsa, or the other files which are used by default for all hosts (the whole list is in man ssh). Give it a unique name, perhaps pertaining to the host it's for.

3
  • 1
    i created this config, but does't work Host vds <public_ip> IdentityFile ~/.ssh/id_rsa User root but when i connect to another server in local network ssh 192.168.1.4 Enter passphrase for key '/home/<User>/.ssh/id_rsa': Commented Apr 12, 2022 at 17:54
  • 2
    @quber See man 5 ssh_config where it describes IdentityFile. ~/.ssh/id_rsa is used by default (i.e. also for the other server in your case). Use a non-default name for the key you don't want to be used automatically. Then specify the renamed key in the config file like the answer says. I think the answer deliberately named the example key my_idfile, not id_rsa. Commented Apr 12, 2022 at 18:04
  • Additionally, the Host line can have multiple entries appended, space separated. Commented Apr 13, 2022 at 3:46

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.