For security reasons, it is recommended to disable SSH login for root user. In this article, we will share the manual steps as well as automation script to perform it.
Following steps should work for AlmaLinux, CloudLinux, Rocky Linux, RedHat Linux, CentOS operating systems.
Manual Steps to disable SSH login for root user
1. Create a new sudo user
- Log in as root via SSH.
- Add a new user using the following command:
adduser newusername
- Set the password of the new username:
passwd newusername
- Add the user to the
wheel
group (this gives sudo access on CentOS/CloudLinux/AlmaLinux/Rocky Linux/RHEL):usermod -aG wheel newusername
- Verify sudo privileges:
su - newusername
- Try a sudo command:
sudo whoami
It should return root
.
2. Disable root login over SSH
- Edit the SSH config file:
nano /etc/ssh/sshd_config
- Find and modify or add the following line:
PermitRootLogin no
- Also ensure:
PasswordAuthentication yes # If you're using password login (optional)
- Restart SSH service:
systemctl restart sshd
Important: Keep your current SSH session open while testing the new user’s login in a second terminal. If anything fails, you can still revert.
Here is a bash script to automate the process of:
- Creating a new sudo user
- Disabling root SSH login
- Restarting the SSH service
#!/bin/bash
# Exit immediately if a command exits with a non-zero status
set -e
# Prompt for username
read -p "Enter the new sudo username: " NEW_USER
# Create the new user
adduser "$NEW_USER"
# Set user password
echo "Set password for $NEW_USER:"
passwd "$NEW_USER"
# Add user to the wheel group for sudo access
usermod -aG wheel "$NEW_USER"
echo "User $NEW_USER added to 'wheel' group for sudo access."
# Backup SSH config
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
# Disable root SSH login
sed -i 's/^#*PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
# Restart SSH service
systemctl restart sshd
echo "SSH service restarted. Root login is now disabled."
echo "Setup complete. Test logging in with:"
echo "ssh $NEW_USER@$(hostname -I | awk '{print $1}')"
How to Use the script
- Save the script:
nano setup_sudo_user.sh
- Paste the script content and save (Ctrl+O, Enter, Ctrl+X)
- Make it executable:
chmod +x setup_sudo_user.sh
- Run the script:
./setup_sudo_user.sh
That’s it!