How to Upload SSH Key From Windows to Linux Server

by Felix Kinaro About 2 min reading time

Prerequisites

To follow this guide successfully, you will need to have the following in place:

Generate New SSH Key

The ssh-keygen command can be used to generate different types of SSH keys such as RSA, ed25519, DSA and ECDSA. In this guide, we will generate an ed25519 key pair for use.

    PS> ssh-keygen -t ed25519 -C "Specific detail about this key"

During the key generation, enter a password to protect the private key from unauthorized use. Follow the prompts to specify the location in case you need to store it in a different location.

Create Directories on the Linux Host

Before we can upload our key, we need to ensure that the directories exist. Log in to your Linux server using the password to create the directories.
The next set of commands will run on the Linux server.

  1. First, check if the ssh keys directory exists:
$ ls -lha | grep ".ssh"

The above command will list all contents of your home directory including hidden files. If the directory does not exist the result will be empty.
2. Create the ssh directory

$ mkdir ~/.ssh
  1. Set the correct permissions
$ sudo chmod 0640 .ssh

This assigns the owner read and write access, read-only access to the group and no access to other users.

  1. Create the authorized keys file:
$ touch ~/.ssh/authorized_keys

Enable the SSH Agent on Windows

SSH agent is a key manager for SSH keys. It stores your keys in memory and in an unencrypted state ready for use by ssh.

Enable automatic startup:


PS> Get-Service -Name sshd | Set-Service -StartupType Automatic

Start the service manually

PS> Start-Service sshd

Add the SSH key you generated:

PS> ssh-add.exe .ssh\id_ed25519

Enter the passphrase when prompted.

Copy the SSH Key From Windows

To copy the SSH public key, we rely on the cat command in PowerShell. It is an alias for the Get-Content PowerShell command.

PS> cat ~/.ssh/id_ed25519.pub | ssh [email protected] "cat >> ~/.ssh/authorized_keys" 

Breakdown of the command:

  1. Use the cat command to get the contents of our public key and pass that to the ssh command:
cat ~/.ssh/id_ed25519.pub | ssh [email protected]
  1. Pass the content to the cat command on the Linux server and redirect it to a file. The >> are output redirection to append the output of the previous command to a file on disk.

Once this is done, you can now proceed to login without a password:

PS> ssh [email protected]

Conclusion

You have successfully set up password-less login from Windows to a Linux host. Go ahead to disable password login to harden your server.

Subscribe to receive weekly articles

Your data is handled by Buttondown.