Disable password-based SSH login and restrict SSH access to key-based authentication on Linux and Mac
Linux
Upload the public key to the taget server
At first, please confirm that you’ve already generated a pair of keys.
If you obtained a pair of keys, please skip to the second part.
1 | # The pair of keys are often stored in this directory |
Then, you could upload your public key to the target server.
1 | ssh-copy-id -f -i /path/to/pub/file -p port user@domain.or.ip |
Modify the sshd
configuration
The configuration file of sshd
in Linux locates at /etc/ssh/sshd_config
.
sshd
service is responsible for controlling the ingress flow.(Server)ssh
service is responsible for controlling the egress flow.(Client)
Modify manually
Use vim
or nano
to edit the configuration file.
1 | sudo nano /etc/ssh/sshd_config |
Find the following specific line and modify.
1 | # Disable the password-based login |
Modify by sed
1 | sudo sed -i 's/^#*PasswordAuthentication[[:space:]]*.*$/PasswordAuthentication no/' /etc/ssh/sshd_config |
Restart the sshd
service
1 | # Restart the sshd service to make it work |
MacOs
The steps for macOS are similar to those for Linux, although the location of the configuration file may differ slightly.
Upload the public key to the taget server
As with Linux, you can use the ssh-copy-id
command to upload the public key.
Modify the sshd
configuration
In macOS, the configuration file is typically located at /private/etc/ssh/sshd_config
.
Modify manually
Use vim
or nano
to edit the configuration file.
1 | sudo nano /private/etc/ssh/sshd_config |
Then, follow the same instructions as for Linux to make the necessary changes.
Modify by sed
On macOS, the usage of the sed command is slightly different. You need to add ‘’ -e to make edits.
1 | sudo sed -i '' 's/^#*UsePAM[[:space:]]*.*$/UsePAM yes/' /private/etc/ssh/sshd_config |
Restart the sshd
service
1 | sudo launchctl stop com.openssh.sshd |
By following the above steps, you can effectively enhance the security of your server and avoid potential security threats.