How to check List users in Linux | Complete Guide for Beginners
Now, what will you do if you want to see available users in your Linux system/server?
This article is all about to list users in Linux using some other commands and tricks.
Get a list users in Linux from /etc/passwd file
User information is saved in /etc/ passwd file. this file contains one line for each user account. you can easily get list users from /etc/password file using acombination of cat command and grep command.
This command will show all fields and content of this file, The first field of the line consist username. other fields contain the following information
- User name
- Encrypted password (x means that the password is stored in the /etc/shadow file)
- User ID number (UID)
- User’s group ID number (GID)
- Full name of the user (GECOS)
- User home directory
- Login shell (defaults to /bin/bash)
If you want to display only first field ( usrname) form passwd file then use awk or cut command.
$awk -F: ‘< print $1>’ /etc/passwd
$cut -d: -f1 /etc/passwd
If you want save users list linux in file then use following command.
This method is useful when your boss Linux to send a list of users of system/server. I save the output into users.txt and userlist.txt
To see the data from the file use cat command.
$awk -F: ‘< print $1>’ /etc/passwd >users.txt
$cut -d: -f1 /etc/passwd >userslist.txt
$cat users.txt
File is created in current directory name users.txt, if you want to save another location give the full path instead of users.txt
More formated awk command to retrieve the username and other information from /etc/ passwd file
Use getent command to see list users
Getent is a utility used to fetch data entries form databases supported by the Name Service Library. In Linux, this data basese is configured into /etc/ nsswitct.conf file including passwd datase.
To get users list linux by type the follwoing syntax.
$getent passwd | awk -F: ‘< print $1>’
$getent passwd | cut -d: -f1
To Check total users on your system in numbers use the following command
$getent passwd | wc -l
Total users on my systems are 53 only.
Check the existence of a user in the Linux system
If you have very long list of users, some time may be 1000 (It is possible, because big server has 1000s users). a will you know user exists in your system/server or not?
For example, Your hr madam asks “please check john user is exist on your system, having following problem to log in system”
You can use the following command to check whether a user exists in the system or not.
$ getent passwd | grep john
If the user exists the command above will print the user’s login information. If there is no output that means the user doesn’t exist means the user doesn’t exist.
Vijay user is exist on this system so it gvie the result. And john user doesn’t exist on this system so no result. See example below:
Normal users and System Users
There is no technical difference between normal user and system users. System user is being created default at the time of installation process and have nologin shell.
In other hand normal user is created by system administrator.
UID is the numeric value for each user, difined in file /etc/ passwd. When you run useradd command to create user in linux, user select automatically UID for /etc/login.defs. lol
$ grep “^UID_MIN” /etc/login.defs
$ grep UID_MIN /etc/login.defs
To check the minimume and maximume user ID’s values on your system. You can use following command:
$grep -E ‘^UID_MIN|^UID_MAX’ /etc/login.defs
Above result, you can see that all normal users have UID between 1000 and 60000.
Following command will be used to list all normal users in your Linux system:
In the above result, all users have been created by me in last tutorial How to crea te user in linux.
Some advanced commands and outputs
Conclusion
In this tutorial, you learned how to list users in the Linux system, filter them using different methods. and what are the main differences between system users and normal Linux users?
The same commands apply for any Linux distribution, including Ubuntu, CentOS, RHEL, Debian and Linux Mint.
3 способа узнать список пользователей в Linux
Сегодня разные операционные системы имеют возможность использовать несколько пользователей, каждый со своими настройками и пользовательскими конфигурациями, чтобы облегчить совместную работу администраторов и операторов в одной системе.
Linux,очень силен в этом вопросе, поскольку позволяет нескольким пользователям одновременно работать в системе независимо. Он может даже позволить одному пользователю открывать несколько сеансов даже из разных мест для работы в системе.
Вот некоторые советы и рекомендации для как узнать всех пользователей Linux.
Список всех пользователей в Linux
Допустим, вы хотите создать пользователя sudo в Linux. Наверное, самое первое, что нужно знать, это как узнать, какие пользователи уже есть в моей системе. Есть несколько способов получить список пользователей в Linux.
1. Показать пользователей в Linux, используя cat /etc/passwd
Эта команда позволяет сисопам перечислять пользователей, которые локально хранятся в системе. Это даст список в структурированном виде, как:
Структура в приведенном выше выводе выглядит так:
- Имя пользователя
- Зашифрованный пароль ( x означает, что пароль хранится)
- Идентификационный номер пользователя (UID)
- Идентификационный номер группы пользователя (GID)
- ФИО
- Домашний каталог пользователя
- Оболочка входа пользователя (по умолчанию — оболочка bash)
Почему так много пользователей? Какие из них «настоящие»?
Список показывает намного больше пользователей, чем вы ожидали, потому что в нем также перечислены все пользователи системы.
Теперь, если вы хотите отличить обычных пользователей от системных пользователей, вы можете обратиться к номеру идентификатора пользователя (UID).
Обычно обычный пользователь имеет UID, больший или равный 1000. Это дает вам подсказку, что пользователь с UID> = 1000 является обычным пользователем, а пользователи с UID <1000 являются системными пользователями.
Вы также заметите, что у некоторых пользователей есть «nologin» в конце их строки. Это означает, что эти пользователи не могут войти в систему. Эти пользователи также называются псевдопользователями.
2. Просмотр пользователей с помощью getent passwd
Эта команда выдаст вам вывод, аналогичный «less /etc/passwd», однако на самом деле он запрашивает файл конфигурации функциональных возможностей переключателя службы имен GNU (находится в /etc/nsswitch.conf).
Это conf включает passwd, поэтому он будет отображаться очень похоже, но если вы используете LDAP для аутентификации, он также будет включать это.
3. Список пользователей Linux с compgen
Если вы просто хотите , чтобы перечислить все имена пользователей без какой — либо дополнительной информации, вы можете использовать CompGen команду с -u опцией.
Вывод будет выглядеть так:
Несколько советов о перечислении пользователей в Linux
Вы только что увидели три способа просмотра пользователей в Linux. Вот несколько советов, которые помогут вам при работе с списком пользователей.
Список только имена пользователей
У вас уже есть команда compgen для этого, но вам не нужно постоянно ее помнить.
Если мы хотим получить только список имен пользователей в системе, вы можете использовать команду awk или команду cut для фильтрации вывода двух других команд, которые мы видели ранее.
Любой из них даст нам отфильтрованный список пользователей, показывая только самый первый столбец с именем пользователя:
Проверьте, существует ли имя пользователя в системе
Это может быть полезно, если вы хотите знать, существует ли конкретное имя пользователя в системе:
Список всех подключенных пользователей
Если вы хотите знать какие пользователи в настоящее время вошли в вашу систему Linux, вам нужно использовать простую команду who и это немедленно выведет список текущих имен пользователей с активным сеансом в вашей системе.
В этом случае в списке появится не только список подключенных имен пользователей, но и то, как они подключены, с момента, когда они подключены и откуда они подключены.
В самом первом столбце будет указано, какое это имя пользователя.
Во втором столбце будет указано, к какому типу соединения это относится: если оно обозначено знаком «: X», где X — число, это означает, что используется графический интерфейс пользователя (GUI) или сеанс рабочего стола, например Gnome, XDE и т. д. ; если терминал отображает «pts/X», где X — число, это означает, что это соединение, установленное по протоколу SSH (командная строка).
В третьем столбце будет указано, с каких пор этот сеанс был подключен к серверу (дата и время). В четвертом и последнем столбце будет указано место, откуда он подключен. Если удаленно, будет отображаться IP-адрес, с которого установлено соединение, если локально (например, GUI), будет отображаться «(: X)», где X — это число сеанс в этом случае и будет соответствовать число во втором столбце для этой строки.
Как видите, перечисление пользователей в Linux совсем не сложно. Он состоит из простых команд, которые выводят всю информацию для вас, что бы вы ни хотели сделать или получить эту информацию, это то, что вам нужно отфильтровать в зависимости от того, что вы хотите проверить в системе.
How to List All Users or User Groups in Linux
Knowing how to list all user groups on Linux is a significant stride towards sustaining ownership and permissions. Since you can use several commands to list user groups, the command you choose depends on the depth of details you want to see.
For example, use the compgen command if you are only interested in names. On the other hand, you can customize the getent command to view extensive information about user groups.
This tutorial explains user management, listing users and their groups using several commands.
These commands should apply to any Linux distribution, including Ubuntu, CentOS, Debian, Linux Mint, and others.
Table of Contents
How Linux Manages Users
First, you should understand the basics of user management, such as creation, privileges, and deletion.
Creation
You can create a user using either useradd command
OR
adduser command to collect more information about the user, such as password, room number, and phone number.
Adding a user to the system appends the user details to the /etc/passwd file.
A user that can log into the system is referred to as a normal user. Otherwise, the created user is a system user whose accounts are for automation tasks.
Supply the -r option to create a systems user.
Privileges
Another point worth remembering is Linux creates a user when you first install it. That user is a superuser and has all the privileges on systems management. The user is often referred to as the root or superuser and is assigned a special directory and group called the root.
Other users created after that are assigned the home directory from where they can store personal data such as media, docs, and videos. The normal users have limited permissions than the root user.
Each of the user’s default group is their username. For example, doe we created above belongs to the doe group. Linux keeps the groups’ data in the /etc/group file. You can find the default configuration details in the /etc/default/useradd file.
Deletion
You can delete a user using the userdel command.
Now you should find out how to list all users and their groups.
List all users
Show Names Only
Use the compgen command with the -u option to list all users on Linux.
OR
Run the cut command on the /etc/passwd file.
Show Details
The most straightforward way to list all users is to cat the /etc/passwd file.
You can use the less command to view a shorter portion of the output page or more for longer.
Use the top/bottom arrow keys or the enter key on your keyboard to navigate the page and the q key to quit the navigation.
Alternatively, you can use the getent command to list all users.
OR
Reveal a specific user’s details by specifying their username.
Here is what the colon separated values mean:
The first part, doe, is the uid (user id). x is a representation of the user’s hashed password. The first 1002 denotes that doe is a normal user. A system user would have a reading of less than 1000. The second 1002 is the gid (group id).
The next part, /home/doe, shows the user’s home directory. The last part, /bin/bash, denotes the shell assigned to the user.
Now that you understand how Linux manages users, groups and how to list users, you know how to list the user groups.
List All Groups
Display Group Names Only
Use the compgen command with the -g option to list all group names.
Alternatively, you can sieve the names from the result of the getent command using the awk or cut command.
Show Group Details
You can list all user groups on Linux by navigating the /etc/group using the cat , more , or less commands.
OR
OR
Alternatively, you can use the getent command with the group option.
Assume you want to count the groups. You can do that by piping the getent ‘s result into the wc command.
Say you want to see the user groups created with the users in section 1 of this tutorial. Since they occupy the last part of the page, you can pipe the result of getent group into the tail command.
Lastly, you may want to list a particular group’s members. All you do is append the group name to the getent command.
List a Specific User’s Groups
Apart from listing user groups of all users, you could narrow it down to groups belonging to a particular user. The groups command plays a massive role in listing a user’s groups.
By default, Linux creates a user with the same uid as gid. The resulting group is called the primary group and can be reassigned.
Run the groups command to list all the groups of the logged-in user.
OR
Use the groups command with the username to list the current user’s groups, whether they are not logged into them.
Alternatively, you can list a particular user’s groups using the id command.
OR
Conclusion
The primary commands to list all user groups are compgen and getent . Alternatively, you can use the cat , more , less , id , and groups commands, as illustrated in this tutorial.
Как посмотреть список пользователей в системе Linux
В системе Линукс может быть зарегистрировано множество пользователей. Иногда их список требуется для ознакомления. Для каких целей это необходимо? К примеру, чтобы проверить, не находится ли в системе кто-нибудь лишний. Подобная информация также нужна в том случае, если возникает необходимость изменить группу и другие данные для конкретного юзера Linux.
И если опытные пользователи открывают список на раз, да еще и знают уйму альтернативных способов, то новички зачастую теряются в данном вопросе. Для неопытного владельца Линукс это может стать настоящей проблемой. Но главное, что она решаема! Остаётся лишь узнать, как это делается.
В данном материале мы уделим внимание двум основным способам поиска списка пользователей в системе. Этого будет вполне достаточно для новичка.
Способ №1: через терминал
Так как дистрибутивы Линукс могут отличаться между собой, целесообразно рассматривать универсальные способы поиска нужной информации. Одним из таких способов является просмотр списка пользователей посредством терминала.
В отличие от Windows в системе Linux данные о пользователях хранятся в специальном файле.
Чтобы прочитать системный файл, потребуется открыть его любым редактором или утилитой cat.
После этого на экране отобразится список пользователей Линукс. Ознакомьтесь с ним внимательнее.
Возле каждого юзера указан его персональный ID. Если ID меньше 1000, то пользователь системный. Они должны оставаться в данном списке для более безопасной работы некоторых установленных сервисов. Удалять этих пользователей не нужно.
Информация в открывшемся окне будет подана в развернутом и детальном виде, что не всегда удобно для поиска конкретных данных. Если нужно посмотреть только имена юзеров системы, следует применить один простой трюк:
С помощью этой команды осуществляется фильтрация лишней информации. В открывшемся списке видны пользователи, зарегистрированные в системе Линукс.
Теперь немного усложним задачу: посмотрим список активных юзеров и узнаем, какие команды они выполняют в текущий момент времени.
Для этих целей нужно запустить утилиту:
На экран выведутся выполняемые команды для каждого активного пользователя. А чтобы получить информацию относительно сеансов пользователей, потребуется применить команду данного вида:
История входов доступна для ознакомления!
Чтобы посмотреть дату последнего сеанса пользователей системы, задайте в терминале:
Способ №2: с помощью специальных программ
Данный способ подходит для операционных систем Линукс с графической оболочкой. Например управление пользователями в Ubuntu может осуществляться через параметры системы.
Произведите запуск утилиты и найдите для дальнейшей работы пункт под названием «Учетные записи». В открывшемся окне не будет системных юзеров. Тем не менее, в левом блоке можно увидеть сам перечень пользователей, а в правом блоке – внести все необходимые коррективы в настройки.
Если потребуется аналогичная утилита для KDE, рекомендуем воспользоваться проверенной и надежной программой под названием «KUser». С её помощью новичок быстро научится управлять пользователями системы Linux (менять пароли и группы, вносить изменения в данных и прочее).
KUser откроет список, в котором содержатся все пользователи, включая системных юзеров Линукс.
Если данный способ просмотра списка не удовлетворяет ваши запросы в полной мере, отдайте предпочтение выводу подробной информации через терминал компьютера.