Set up a user to connect to a Linux server with a private-public key pair

To secure a Linux server, disable password authentication on it. This way only those users can connect to it, who have access to an authorized private key.

To enable users to connect to a Linux server with a private-public key pair

Generate an RSA key pair

  1. In a Bash terminal on your workstation execute
    ssh-keygen
  2. Follow the prompts to specify the name of the key file pair. In most of the cases, you don’t need to protect the key with a password.
    1. If you don’t specify the file name, the key will be saved as ~/.ssh/id_rsa
    2. If you specify a file name, the key files will be saved in the current directory
  3. The public key file will get the “.pub” extension, the private file has no extension

Upload the public key to the Linux server

  1. Log into the server with the “ssh” command using a username and password
    ssh MY_USER_NAME@SERVER_IP_ADDRESS
  2. Add the public part of the key to the user configuration
    1. Switch to sudo mode, this command will ask for the password again
      sudo -i
    2. Navigate to the user home directory
      cd /home/USER_NAME/
    3. Add the public key to the user’s authorized_keys file. Open the file with a text editor and copy the public key into a new line.
      vi authorized_keys
    4. To test the configuration, on your workstation navigate to the directory where the new key is located, and log into the server with
      ssh -i MY_KEY_NAME MY_USER_NAME@SERVER_IP_ADDRESS

Turn off password authentication

  1. Make sure you can log in with the new key !!!
  2. Execute the command
    sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config

Leave a comment

Your email address will not be published. Required fields are marked *