Linux disable all users

How To Disable or Lock Linux User Account?

How can I disable some Linux account? By disabling it I do not want to remove the account and related files. Just user related operations will be prevented. If an user authentication occurs it will be not authenticated. We will use usermod command to lock user account.

Disable/Lock User Account with usermod Command

We will disable account with the following code.

  • usermod will change user account related attributes and information.
  • -L will lock given account and put ! in the user passwords database before encrypted password.
  • -e 1 will set expire date from 1/1/1970

Disable/Lock User Account with chage Command

chage command is use to set user account expiration time for password. If we set previous than the current date the given account will be locked automatically. We provide the date in YYYY-MM-DD format. In this example we will lock user ismail .

Disable/Lock User Account with passwd Command

We can also use passwd command in order to lock given user account. We will provide -l option which means lock. In this example we will lock user ismail

Disable/Lock User Account From /etc/shadow

/etc/shadow file stores the user password in encrypted format. If ! is added before hash value of the user password the user account will be disabled or locked. As an example we can lock user test with the following line. Attention to the ! at the begging of the password hash value.

Disable/Lock User Account From /etc/passwd

/etc/passwd file also store information about the user. An user account can be also locked from this file in two different ways.

Disable User Login with nologin

We can disable an user account login from the /etc/passwd file at the end of line like /bin/bash which specifies the user shell. We will change to the /bin/nologin which is not a login shell.

Disable User Login with nologin

Читайте также:  Как открыть командную строку windows server

Adding ! After Username

Another way is adding ! after username and before x like below.

Unlock/Enable User

After some time we may need to enable or unlock given user account there are different ways to unlock an user account. Here some of them with chage and passwd command.

Check User Lock Configuration

We will check the status of this account from configuration file. Is the account disabled?

We can also check the user configuration whether it is locked or not with the chage command like below.

How To Disable or Lock Linux User Account? Infografic

Источник

Отключение пользовательских аккаунтов в Linux

1. Введение

Системный администратор Linux должен уметь управлять пользовательскими аккаунтами. При этом можно добавлять или удалять пользовательские аккаунты, а можно просто временно или на постоянной основе отключить учетную запись, оставив при этом профиль пользователя и его файлы в целости и сохранности. В этой статье описаны несколько способов отключения пользовательских аккаунтов в Linux.

2. Редактирование файла shadow

Самый простой способ отключения пользовательского аккаунта — редактирование файла /etc/shadow, который отвечает за хранение зашифрованных паролей пользователей, перечисленных в файле /etc/passwd. Вот типичная запись пользовательского пароля в /etc/shadow:

Для отключения аккаунта достаточно просто добавить «*» или «!» перед зашифрованным паролем:

То же самое можно сделать с помощью команды:

Любой метод авторизации, использующий для аутентификации пользователя файл /etc/shadow, больше не будет работать, так как расшифровать пароль будет невозможно:

Для активации пользовательского аккаунта просто удалите «!» из файла /etc/shadow, или воспользуйтесь командой:

Важно помнить, что этот метод отключения пользовательских аккаунтов в Linux работает только для тех программ и команд, которые для аутентификации пользователей используют файл /etc/shadow. Например, если у пользователя уже есть ssh-ключ, он все равно сможет авторизоваться, несмотря на модификацию /etc/shadow.

3. Пользовательская оболочка nologin

Другой, и более безопасный способ отключения пользовательского аккаунта — заменить существующую программную оболочку пользователя на псевдооболочку, такую как /usr/sbin/nologin, которая при попытке авторизации выдает вежливое сообщение:

Для этого модифицируйте файл /etc/password, изменив запись пользователя:

После этого пользователь не сможет авторизоваться даже с правильным паролем:

4. Заключение

Оба описанных выше метода имеют свои преимущества и недостатки, и какой из них выбрать, решать вам. Получить более подробную информацию об описанных здесь командах и файлах можно из man-страниц:

Источник

UNIX / Linux : How to lock or disable an user account

There are several ways in which user account can be locked or disabled. The posts discusses few of the most widely used ways.

1. Lock the password

To lock a users account use the command usermod -L or passwd -l. Both the commands adds an exclamation mark (“!”) in the second field of the file /etc/passwd. For example :

2. Expire the user account

The commands passwd -l and usermod -L are ineffcient when it comes to disable/lock user accounts. These commands will not disallow authentication by SSH public keys (or other PAM modules other than pam_unix that may be enabled). Additionally, changing the shell to /bin/false or /sbin/nologin is unsatisfactory to us since this only affects interactive logins. So to completely disable user accounts you can user the command chage -E0. For example :

Читайте также:  Arch linux установка драйвера nvidia

Expiring an account via use of the 8th field in /etc/shadow (using “chage -E”) will block all access methods that use PAM to authenticate a user.

3. Changing the shell

We can also change the default shell of the user to /sbin/nologin so that the user do not get any login shell when he tries to login into the system.

You can check for the 7th and last field in /etc/passwd for the change of shell to /sbin/nologin.

Verify if the account is locked or disabled.

For each of the methods described above, you can verify if the user account is locked/disabled using below methods.

1. Check if the user account is locked.
Check for the flag *LK* in the below command output which indicates that the account is locked.

2. Check if the account has an expire date.
Check for the lines Password expires and Account expires to check if the account password is expired.

3. Check for non-interactive shell
Check if the user shell has been changed to a non-interactive shell like /sbin/nologin.

Источник

How to disable a user account in Linux

This article explains how to lock or disable a user account in Linux.

There are different methods of locking a user account in Linux. Each method is explained below.

Editing the /etc/passwd file by hand

This is the crudest form of disabling a user account in Linux.

Open a terminal and run the following command.

This command will open the /etc/passwd file in your default editor which is usually Vi if you haven’t explicitly set the EDITOR variable.

My /etc/passwd file is as shown below (truncated for brevity).

To disable a user’s account — for example user ‘ravi’ — replace shell ‘/bin/bash’ with ‘/sbin/nologin’.

Now save and close the file.

Alternately, you can also enter a ‘ ! ‘ (bang) or ‘ * ‘ (asterisk) just before the ‘x’ in the second field as shown below.

Save and exit the file.

A disabled user can still login through the network using SSH which is the vulnerability of the above method.

Use chage command

The chage command changes the number of days between password changes and the date of the last password change. This information is used by the system to determine when a user must change his/her password.

The trick to disabling a user account in Linux using chage is to set the expiry of the user account to a date previous to the current one.

So for example, if today’s date is October 13 2005, you can lock a user account by setting the expiry date to October 12 2005 or earlier.

Читайте также:  Почему ноутбук не загружает установочную флешку windows

. where the date is in YYYY-MM-DD format.

You can re-enable the user’s account by running the same command but changing the date to a value more recent than the current date.

Use the passwd command

This is by far the easiest way of locking or disabling a user account in Linux. To lock a user account, open a terminal and enter the following command.

Continuing with our previous example to lock out the user ‘ravi’, do the following as root / superuser.

And to unlock the account,

Check the logs for failed logins

All failed logins will be audited and logged to the file /var/log/faillog. To see who all have unsuccessfully tried to login to their account, try the following:

The above command will read the /var/log/faillog file for any failed login attempts by users. It contains a history of all failed login details. This file is used when you use PAM (Pluggable Authentication Modules) for enforcing password policies.

Источник

HowTO: Linux Disable a User Account Command

H ow do I disable a user account under Linux operating systems? How can I completely disable a user account Linux server?

You need to use the usermod command to lock and disable user account. The -L option lock user’s password by putting a ! in from of the the encrypted password. To disable user account set expire date to one or 1970-01-01.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Linux
Est. reading time N/A

Syntax

usermod -L -e 1
usermod -L -e 1970-01-01

Example

In this example, local disable a user account for raj user:
# usermod -L -e 1 raj
When raj try to login he will greeted with the following message on screen

However, ssh client will not show any message:
$ ssh raj@server1.cyberciti.biz
Sample outputs:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

You will see the following log entry in /var/log/secure or /var/log/auth.log file:

Use chage command to see current status of the user account:
# chage -l raj
Sample outputs:

See also
  • Help: Old Employees Accessing The Linux Server
  • man pages chage, passwd, usermod, and useradd

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Оцените статью