How to Disable Root Login in Linux
sudo
(super user do) privileges. You should only disable the root user if you have an existing non-root user with sudo
privileges to handle all administrative operations.This guide explains how to disable root login in Linux and allow only sudo users to perform administrative tasks.
Prerequisites
Before proceeding, ensure that you have:
- Access to a Linux instance as a non-root user with
sudo
privileges.
Disable Root SSH Login
Secure Shell (SSH) enables remote access to a Linux system using a valid username-password combination or SSH keys. Disabling root SSH login blocks all connection attempts from the root user and only permits non-root users to access the system. Follow these steps to disable root SSH login:
Step 1: Open SSH Configuration File
Use a text editor, such as nano
, to open the /etc/ssh/sshd_config
file.
$ sudo nano /etc/ssh/sshd_config
Step 2: Modify the PermitRootLogin Directive
Locate the following directive and change its value from yes
to no
to prevent root login via SSH.
PermitRootLogin no
Step 3: Save and Close the File
After making the changes, save and exit the file.
Step 4: Restart the SSH Service
To apply the updated configuration, restart the SSH service using the following command:
$ sudo systemctl restart ssh
Disable Access to the Root User Shell
Blocking access to the root user shell prevents direct root login and the use of the sudo su
command. This ensures that administrative tasks are performed by users with sudo
privileges, without needing direct root access.
Step 1: Edit the /etc/passwd File
Open the /etc/passwd
file using a text editor:
$ sudo nano /etc/passwd
Step 2: Change the Root User Shell
Modify the root user shell by replacing /bin/bash
with /sbin/nologin
:
root:x:0:0:root:/root:/sbin/nologin
Step 3: Prevent Further Changes
Enable the immutable attribute to prevent any modifications to the /etc/passwd
file:
$ sudo chattr +i /etc/passwd
Create a Custom Message of the Day (MOTD)
A Message of the Day (MOTD) displays important information upon login. You can create a custom message instructing users to use sudo
for administrative tasks instead of accessing the root shell.
Step 1: Open the MOTD File
Use a text editor to edit the /etc/motd
file:
$ sudo nano /etc/motd
Step 2: Add a Custom Message
Insert the following text into the file:
Welcome to the server
Note: The root account is disabled. Use sudo to execute commands and perform administrative tasks.
Verify That Root Login is Disabled
To ensure that root login is fully disabled, perform the following tests:
Test 1: Attempt Root Login Using sudo su
$ sudo su
Expected output: This account is currently not available.
Test 2: Attempt SSH Login as Root
$ ssh root@Server-IP
Expected output: Permission denied.
Conclusion
By following these steps, you have successfully disabled the root user login in Linux. This enhances security by ensuring that only authorized sudo users can perform administrative tasks.