How To Disable User Logins On Linux
In this tutorial, we will cover the various methods used to block user logins on Linux and their differences.
2. The nologin Command
We can use the nologin command to prevent a user from logging in. It prints a message and exits with a non-zero status code to indicate failure. We can change a user’s login shell with the usermod command’s -s flag.
As an example, let’s use it to prevent a user called baeldung from logging in:
Now, if we try to use su to log into the account, we see an error indicating that logins have been disabled.
We can also modify the error message by modifying the /etc/nologin.txt file:
3. The false Command
The false command is a simple command we use to return a non-zero status code indicating failure. Let’s run it and check its status code:
false is the opposite of the true command, which always returns a zero status code, indicating success:
We can use them in Bash while statement to repeatedly execute code:
The first code block is never executed since false always indicates failure, while true always indicates success:
While it is not the false command’s primary purpose, we can still use it for preventing user logins, just like we did with the nologin command. However, false does not print an error message and immediately exits the shell, which can cause confusion:
This means that we cannot customize error messages as we did with nologin in the previous section.
4. The passwd Command
We can use the passwd command’s -l flag to lock a user account, preventing logins:
Now when we try to login, su will treat all passwords as invalid. We can unlock the account with sudo passwd -u baeldung. This method is similar to the false command since it doesn’t allow us to display a descriptive message.
5. The usermod Command
Similar to the passwd command, we can use the usermod command with the -L or -U flags to lock/unlock a user account:
In this article, we learned about various commands used to block user logins on Linux and their differences. Usually, the nologin command is preferred to other methods like false or passwd since it allows us to set a custom message explaining why the account was locked.