Using multiple SSH keys for a single host with PuTTY and Pageant
I’ve been using SSH to access my various source code repositories for quite some time now. I’ve always used PuTTY and the related tools of Plink and Pageant in order to connect to my various online providers (mainly BitBucket and Github). Until now, I’ve only ever needed one SSH Key per provider (or “host”) however, I recently started a new job whereby I needed to connect to two different BitBucket accounts, using two different SSH Keys.
As the two SSH Keys are connecting to the same host, it’s not possible to simply load both of the keys into Pageant and go from there as only the first key loaded will be sent to a given host. If the account you’re trying to connect to uses the other SSH Key, Pageant will send the first (incorrect) key and your connection will fail.
The way to ensure the correct key is sent is by creating multiple “sessions” within PuTTY itself.
Here’s the steps to create a “session” within PuTTY (which Plink and Pageant will honor it you’re using the correct “host” alias – see later):
- Start PuTTY
- Type in the relevant “real” host name in the Host Name field (i.e. bitbucket.org or github.com)
- Navigate to the Connection > SSH > Auth node in the treeview.
- Specify the correct private key file in the “Private Key File for Authentication” section (this is the same key that you’d load into Pageant).
- Navigate back to the “Session” node in the treeview.
- Type a “host alias” name in the “Saved Sessions” box and click Save.
You can repeat the above steps for as many different keys you wish to add. You can have multiple “sessions” using the same Host Name, just give each of them a different “Saved Session” name.
Once PuTTY is configured in this way, you will continue to load Pageant and load in each of the keys that you’ll want “cached”, just as you did before.
The key to making this now work is in the Remote URL that you’ll use for your repositories.
Whereas the “standard” SSH URL would look like this:
ssh://git@bitbucket.org/craigtp/stampver.git
you simply replace the actual host (in the above example, it’s bitbucket.org) with the Saved Session name (aka “host alias”) that you entered in PuTTY (in the example from the animated gif on the right, I used “bitbucket-craig”). So you remote host URL for your source repository becomes:
ssh://git@bitbucket-craig/craigtp/stampver.git
Of course, this works for both Mercurial and Git repositories on any actual remote host. So long as you use the host alias, Pageant and the PLink program that acts as a “bridge” between Pageant and PuTTY will use the host alias in the URL to both look up the actual host to connect to and to identify the correct private key file to send for the given alias. This is the PuTTY/Pageant equivalent of OpenSSH’s IdentityFile, which performs the same function.