SSH Keys for Windows to Linux Host

SSH Keys for Windows to Linux Host

02/02/2023

A quick tutorial for my future self to generate keys for an ssh connection between a windows machine to a linux host.

Generate Keys

The first step is to generate your keys using:

ssh-keygen

You can use this with no flags to generate a basic RSA key but you can use different types via the -t flag.

Make sure to note both the location and passphrase of your key. Usually the key is stored in the user’s directory in the SSH folder in Windows.

Now open a bash emulator (Git Bash is good) and copy the public key to your host:

cat ~/.ssh/id_rsa.pub | ssh <user>@<host> "cat >> ~/.ssh/authorized_keys"

Here I have copied my id_rsa.pub public key to the host and put it in my user’s .ssh folder.

You can alter the command from above to create the .ssh directory if it doesn’t already exist on the host:

cat ~/.ssh/id_rsa.pub | ssh <user>@<host> "mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys"

Create SSH Agent

Now that you have your private key on your local machine and the public key on the host, it’s useful to add the key to an ssh agent which removes the need to enter your password every time you ssh into the host.

To create and start an SSH Agent on Windows, open up a PowerShell window as administator:

Get-Service ssh-agent | Set-Service -StartupType Automatic -PassThru | Start-Service

To avoid restarting, run this command to start the service:

start-ssh-agent.cmd

Add Your Key to the SSH Agent

Now in a fresh cmd window, you can run the ssh-add command along with the location of your key.

ssh-add C:/Users/<user>/.ssh/id_rsa

You will be prompted to enter your passphrase and then you are good to go.

Test it out by shelling into the host. If all is well, you shouldn’t be prompted for a password.