Sometimes it is necessary to disable user logins to a system. If you are doing maintenance and want to keep the system state clean for example. In this quick tip we will show you how to disable logins to a Linux system.

If you ever looked at an /etc/passwd file chances are you have seen a user shell set to /usr/sbin/nologin. This tells the system that that user does not have access to interactively login to the system. This is a good way to block logins for a specific user, but another file called /etc/nologin exists to block any non-root user from logging in.

Blocking All non-root Users from Logging Into a System

To block all non-root users from logging into the system you can simply create the /etc/nologin file.

sudo touch /etc/nologin

This will block any user. As soon as they authenticate the connect will be closed. This often confuses users, so it is a good idea to add a message. Simply add the message you want displayed to the file. You can open the file in your favorite text editor like vi, nano, or emacs and start typing. Or you can echo the message into the file like so:

echo "System down for maintenance, try again later" | sudo tee /etc/nologin

NOTE: You cannot use normal redirection with sudo, so we used the tee command instead.

Now when a user tries to login, they will receive the message and the connection will be closed.

$ ssh stacy@UbuntuDev
stacy@UbuntuDev's password:
System down for maintenance, try again later
Connection closed by UbuntuDev port 22

That is much more polite.

Unblock Logins

To unblock, or allow logins again, simply delete the /etc/nologin file.

sudo rm /etc/nologin

Block Specific User from Logging in Interactively

You can use the nologin shell to block interactive shell access for a specific user. This comes in handy if you only want to allow the user FTP access or similar.

The nologin shell is located at different paths for different systems.

For Ubuntu it is located in /usr/sbin/nologin

For Fedora it is located in /sbin/nologin

You can find where it is located by using the which command:

$ which nologin
/usr/sbin/nologin

To set the users shell to nologin, you can use the usermod command. Here we will set the "stacy" users shell to nologin.

usermod -s /usr/sbin/nologin stacy

Unblock Specific User from Logging in Interactively

To unblock or re-enable a user to login via an interactive shell, simply set their shell back to bash (or whatever shell you wish).

To set the "stacy" users shell back to bash:

usermod -s /bin/bash stacy

If you use "usermod -s" without any arguments the system will use the default shell for the user.

Conclusion

Now you should know how to disable user logins to a system. We covered disabling all user logins as well as settings for specific users. Feel free to sound off in the comments.