Creating SSH keys on CentOS
Start by generating a new 4096 bits SSH key with your email address as a comment:
ssh-keygen -t rsa -b 4096 -C "your_email@domain.com"
Or no comment as following:
ssh-keygen -t rsa -b 4096
You will be prompted to specify the file name:
Output:
Enter file in which to save the key (/home/yourusername/.ssh/id_rsa):
If you don't want to use a passphrase just press Enter
.
Just press Enter
whent it ask questions until it finish.
The whole interaction looks like this:
To verify your new SSH key pair is generated, type:
$ ls ~/.ssh/id_*
Output
/home/yourusername/.ssh/id_rsa /home/yourusername/.ssh/id_rsa.pub
Copy the Public Key to CentOS Server
Now that the SSH key pair is generated, the next step is to copy the public key to the server you want to manage.
The easiest and the recommended way to copy the public key to the remote server is by using a utility called ssh-copy-id
. On your local machine terminal type:
$ ssh-copy-id remote_username@server_ip_address
You will be prompted to enter the remote_username's password:
Output
remote_username@server_ip_address's password:
Type the password, and once the user is authenticated, the public key ~/.ssh/id_rsa.pub
will be appended to the remote user ~/.ssh/authorized_keys
file. The connection will be
closed.
Output
Number of key(s) added: 1Now try logging into the machine, with: "ssh 'username@server_ip_address'"
and check to make sure that only the key(s) you wanted were added.
If the ssh-copy-id
utility is not available on your local computer, use the following command to copy the public key:
$ cat ~/.ssh/id_rsa.pub | ssh remote_username@server_ip_address "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
Login to your server using SSH keys
After completing the steps above, you should be able to log in to the remote server without being prompted for a password.
To verify it, try to login to your server via SSH :
$ ssh remote_username@server_ip_address
If you haven’t set a passphrase for the private key, you will be logged in immediately. Otherwise, you will be asked to enter the passphrase.
Disabling SSH Password Authentication
To add an additional layer of security to your remote server, you can disable SSH password authentication.
Follow the steps below to disable SSH password authentication:
-
Log into your remote server
-
Open the SSH configuration file
/etc/ssh/sshd_config
vi /etc/ssh/sshd_config
- Search for the following directives and modify as it follows:
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no # This line is optional
- Once you are done save the file and restart the SSH service by typing:
systemctl restart sshd
At this point, the password-based authentication is disabled.