Wednesday, December 09, 2020

managing multiple SSH keys

 Let's say you have already generated an SSH key for GitHub, as instructed here:

https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Now your .ssh folder will be like this:

PHS015945:.ssh xd010$ ll

-rw-r--r--  1 xd010  staff   165B Dec  9 23:21 config

-rw-------  1 xd010  staff   411B Dec  9 23:12 id_ed25519

-rw-r--r--  1 xd010  staff   100B Dec  9 23:12 id_ed25519.pub

where config file will be like:

Host *

  AddKeysToAgent yes

  UseKeychain yes

  IdentityFile ~/.ssh/id_ed25519

Now, you want to ssh to your HPC server without a password. You will follow instructions like this http://www.linuxproblem.org/art_9.html, e.g. 

a@A:~> ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/a/.ssh/id_rsa): 
Created directory '/home/a/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/a/.ssh/id_rsa.
Your public key has been saved in /home/a/.ssh/id_rsa.pub.
The key fingerprint is:
3e:4f:05:79:3a:9f:96:7c:3b:ad:e9:58:37:bc:37:e4 a@A

Now append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:

a@A:~> cat .ssh/id_rsa.pub | ssh b@B 'cat >> .ssh/authorized_keys'
b@B's password: 

You will find that you are still asked to enter the password when you want to ssh to your HPC. Where's the problem?

Type "ssh -v yourname@HPCserver". You will find out it still reads the ~/.ssh/id_ed25519, instead of ~/.ssh/id_rsa. The problem is the config file. 

To fix this, you have to manually add another host there. Note that the "Host *" should be put at the end of the file. See explanation here: https://dev.to/yashsway/setting-up-multiple-ssh-profiles-to-manage-multiple-git-accounts-macos-3m7m

Host is a pattern matcher that is used to differentiate between these sets of configurations. Keep it the same as the HostName so it matches hosts in connections correctly without additional specification. If you want to use the personal_key as a fallback for every other URL, use an asterix * as the Host. The Host * configuration set is usually at the bottom of the config file, so it tests very configuration set until it gets to this one, if none of the previous Host patterns match.

Here is the new config:

$ cat config 

Host github.com

  AddKeysToAgent yes

  UseKeychain yes

  IdentityFile ~/.ssh/id_ed25519



Host *

  AddKeysToAgent yes

  UseKeychain yes

  IdentityFile ~/.ssh/id_rsa

Now the ssh to HPC will work without a password!

One more tip: instead of typing "ssh xd010@erisone.partners.org" every time, you can set an alias in .bash_profile, e.g. 

alias hpc='ssh -X xd010@erisone.partners.org'

No comments:

Post a Comment