How to Login with SSH Keys
Logging in with SSH keys is a more secure and convenient way to access a remote server compared to using passwords. SSH keys provide stronger authentication and eliminate the need to remember and transmit passwords over the network. To log in with SSH keys, follow these steps:
- Generate SSH Key Pair:
If you don’t have an SSH key pair, generate one on your local machine. Use the
ssh-keygencommand to create a new key pair. You can run the following command to generate an SSH key:
ssh-keygen -t rsa -b 4096
This command generates a new RSA key with a bit length of 4096 (you can choose a different length if you prefer).
- Copy the Public Key:
Once the key pair is generated, the public key (usually found in
~/.ssh/id_rsa.pub) needs to be copied to the remote server. You can do this manually or by using the
ssh-copy-idcommand. Here’s an example of how to use
user with your username and
remote_server_ip with the IP address or hostname of the remote server. This command will prompt you for your password on the remote server.
ssh-copy-id is not available, you can manually copy the content of your public key (found in
~/.ssh/id_rsa.pub) to the
~/.ssh/authorized_keys file on the remote server. You can use
ssh and a text editor to do this:
Once logged in, use a text editor like
vim to open the
Paste your public key at the end of the file, save, and exit.
Change permissions for the .ssh directory:
chmod 700 ~/.ssh
Change permissions for the authorized_keys file:
chmod 600 ~/.ssh/authorized_keys
- Configure SSH on the Remote Server:
Ensure that the SSH server on the remote server is configured to allow key-based authentication. You can do this by editing the SSH configuration file. Open the file
/etc/ssh/sshd_configon the remote server:
sudo nano /etc/ssh/sshd_config
Make sure the following options are set like this:
PubkeyAuthentication yes PasswordAuthentication no
These settings enable public key authentication and disable password authentication. Save and exit the file.
- Restart SSH Service on Remote Server:
After making changes to the SSH configuration, restart the SSH service on the remote server:
sudo systemctl restart sshd
- Test SSH Key Authentication:
On your local machine, try to log in to the remote server using your SSH key:
You should be able to log in without entering a password. If everything is configured correctly, you’ll be prompted for your SSH key’s passphrase (if you set one during key generation).
By using SSH keys for authentication, you significantly enhance the security of your SSH connections. Make sure to keep your private key secure and do not share it with anyone. If your private key is compromised, an attacker could potentially gain unauthorized access to your remote server.