🔑

SSH Connection Method using Authentication Keys

2023/05/25に公開

In SSH key authentication, first, the client generates a pair of public and private keys and copies the generated public key to the server. Then, when trying to connect via SSH, the server verifies the client's private key using the public key.

The specific steps are as follows:

1. Generate a pair of public and private keys on the client side

cd ~/.ssh
ssh-keygen -t rsa -b 4096

This will generate two files: ~/.ssh/id_rsa (private key) and ~/.ssh/id_rsa.pub (public key).

If you want to specify the file name, write it as follows:

ssh-keygen -t rsa -b 4096 -f id_rsa_file_name

2. Copy the public key (id_rsa.pub) to the server

ssh-copy-id -i ~/.ssh/id_rsa_file_name.pub username@your_server_ip

If you cannot connect via ssh at this time, you will need to copy it using a USB memory or something similar. You may also want to go through a cloud service like Google Drive.

Here, username is the username of the server, and your_server_ip is the IP address of the server. Next, connect to the server and perform the following operations:

cd ~/.ssh
cat id_rsa_file_name.pub >> authorized_keys
chmod 600 authorized_keys

By following the above steps, SSH key authentication is set up. As a result, you will be able to connect via SSH without having to input a password from the next time.

Please note that the private key file is very important and should be carefully protected so that it does not leak to others. Also, if you disable password-based authentication, keep in mind that you will not be able to connect if you lose your private key file.

3. Try connecting with the authentication key

ssh -i ~/.ssh/id_rsa_file_name username@hostname

For example, the username might be ubuntu, and the hostname might be 192.168.0.11.

Example:

ssh -i ~/.ssh/id_rsa_file_name ubuntu@192.168.0.11

4. Optional: Change the settings on the server side to disable login with a password in the ssh settings

This is a must for business purposes from a security standpoint, but it's up to you for personal development. Once you have confirmed that you can connect via ssh with the authentication key following the operations described above, let's prohibit connection by password.

sudo vi /etc/ssh/sshd_config

Change around line 58

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes   # Before change
PasswordAuthentication no    # After change

After editing, restart ssh

sudo systemctl restart ssh

Now, you should be able to connect via ssh with the authentication key.

Discussion