Linux terminal all users

Как посмотреть пользователей Ubuntu

Иногда возникает необходимость посмотреть всех зарегистрированных в системе Linux пользователей. Например, для того чтобы узнать не зарегистрирован ли кто лишний в системе, или изменить данные/группу одного из пользователей.

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

Как посмотреть список пользователей в терминале

Сперва рассмотрим как посмотреть пользователей ubuntu в терминале Linux, так как это наиболее универсальный способ, который работает почти во всех дистрибутивах. В операционной системе Linux есть специальный файл в котором хранится информация обо всех пользователях. Это /etc/passwd. Записи в файле имеют следующий синтаксис:

имя_пользователя пароль ид ид_группы группа домашний_каталог оболочка

Надо заметить, что вместо пароля теперь записывается буква X это было сделано для безопасности. Все пароли пользователей хранятся теперь в другом файле. Остается только набрать команду и вы узнаете список пользователей linux:

users1

Пользователи с ID меньше 1000 — системные, они были созданы во время установки некоторых сервисов для более безопасной их работы. Этих пользователей трогать не следует. В этом примере в системе вручную зарегистрирован только один пользователь — Sergiy.

В файле /etc/passwd слишком много лишних данных, если вам нужны только имена пользователей, можно отфильтровать вывод:

users2

Так вы можете посмотреть всех пользователей Ubuntu. С зарегистрированными пользователями разобрались. Но намного интереснее посмотреть какие пользователи сейчас активны в системе, и какие команды они выполняют. Для этого есть утилита w:

users

Здесь выводятся все выполняемые пользователями команды. Если пользователь сейчас выполняет в терминале несколько команд, то будет отображено два пункта для одного пользователя.

Кроме того, вы можете посмотреть историю входов пользователей в систему. Для этого есть команда last, она выводит информацию на основе лога /var/wtmp:

users3

Дату последнего входа для каждого пользователя вы можете посмотреть с помощью команды lastlog:

users4

Если пользователь никогда не входил, команда так и скажет, в противном случае мы увидим дату последнего входа.

Список пользователей в GUI

В Ubuntu зарегистрированными в системе пользователями можно управлять с помощью параметров системы. Откройте утилиту и выберите в самом низу пункт Учетные записи. Здесь уже не будут отображаться системные пользователи. В панели слева — непосредственно сам список, а справа можно изменить данные и настройки:

users

Для KDE есть более интересная утилита управления пользователями — KUser:

users1

Здесь так же как и в терминале отображены все пользователи, в том числе системные. Можно менять различные данные, в том числе пароли, основную и дополнительную группы и т д.

users2

Как видите, только в терминале вы можете посмотреть более подробную информацию, проверить даты входа и точно узнать не используют ли систему другие люди.

Выводы

Теперь вы знаете как посмотреть список пользователей Ubuntu. Это не очень сложно, но нужно только понять основы того как это работает. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to List All Users in a Linux System?

In the Linux system, it is a critical administrative task to manage users, add them, remove users, or assign new user privileges. In Linux, numerous users can simultaneously work on the same system. But security measures must be made to stop breaching other users’ private data. Information related to the local users is stored in the path “/etc/passwd”. In which, every row indicates the data of a single user that may contain the name of the user, user Id, directory of the user, and login details. When it comes to the listing of the user in Linux, there are multiple ways to list them, we will discuss some of these in this tutorial.

Читайте также:  Поменять графическую оболочку линукс

Prerequisites

To list users, we must have Linux running on our system and also access to the terminal to perform this task.

Method 1: Using the Cat Command

Cat command is the short form of concatenation, it is used to read the data of the file without opening it. In this, we will use the cat command to list all users in Linux. Additionally, it is used to make a new file and put data in it.

Syntax:

The given data below is the syntax to use the “cat” command where file_name represents the name of the file that has to be read.

To list the user using the “cat” command, we will first launch the terminal.

After that, we will run the command:

In the command above, we have used the “cat” command along with the file name “etc/passwd” which is the one in which all of the user’s data is stored. After running this command and by pressing enter, we get the output as shown in the snippet below which includes the list of the users that are stored in the file. As we discussed above, each row indicates the details of the single user.

If we only want to see the number of users that are allowed to use the system, we can just write the following command:

In the command listed above, we used the “wc” command along with the “cat” command. “wc” is the one that is used to count the line, word, or bytes of the file. In our case, we are going to list the number of rows that are storing the single user data. That is why we have passed “-l” which means the lines are counted. After running the command above, we obtained the number of users whose data is stored in the file that in our case is “47”.

Method 2: Using “less” or “more”

The other method to list the users from any file is “less” or “more”. Less and more are the terminal pagers commands that allow us to read the files line by line or to read them page by page.

Syntax:

Below is the syntax to use the “less” command to list the users from any file.

In the snippet, we have successfully executed the list of the users that are stored in the /etc/passwd file. The less command can also be used to read the list of users. It will display the users until it reaches the end of the terminal by scrolling the terminal using the down button, we can display the remaining data of the file.

Using the “more” command to list the users, below is the syntax to use the “more” command.

This command has some limited functionalities. It will display some of the percentages of the file like in the snippet below. It displayed about 47% of the data of the file by pressing the “enter” key we can display the data to some percentage, so we have to press the “enter” key until the 100% of it is not displayed.

Читайте также:  Linux погода в терминале

Text Description automatically generated

Method 3: awk Command

In this, we will discuss another method to list the users of the system which is an “awk” command. The awk command is useful only when we have to display the name of the user neglecting the other details that are stored in the file related to any user.

Syntax:

Below is the syntax to use the awk command to enlist the user’s name.

In the syntax, colon “:” is used to separate the input that is given by the awk. After that, it prints the first value of each row where –F is a file along with the argument which is responsible for reading the file and then displaying it as an output. The /etc/passwd is the file name that we want to read.

Text Description automatically generated

If you have multiple pages in a single file and you want to read the file page by page by writing the following command, you can perform this task.

In the above syntax, less will enable us to read the file page by page if multiple pages exist.

Method 4: Using the getent Command

The “getent” command is most similar to the “cat” command as we can display the complete details of the users along with the technical details. The “getent” is also responsible for displaying the complete details of the users.

Syntax:

The syntax for writing the getent command is given below. In this syntax, we just passed the name of the file along with the “getent” command.

After running the command, the whole file data is executed as shown in the below screenshot.

Text Description automatically generated

Conclusion

In this guide, we introduced the listing of the users that are using the same system at the same time. It is an administrative task to manage multiple users at a time. We also examined some of the techniques that are employed to enlist the users on Ubuntu 20.04. As we know it is necessary to manage the users but first, it is important to know the users who are using the system so it would be made secure for others to prevent data breaches between all of the users.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

How to List Users in Linux

User management is a critical Linux system administration task. In large organizations, having insight into who has access to the system is crucial to correctly add users, remove users, and assign new user privileges.

This tutorial will show you how to list users on a Linux-based system. The guide provides four listing methods and explains essential concepts related to user administration.

How to list users in Linux.

Listing Users in Linux

Linux stores information about local users in the /etc/passwd file. Each line in the file contains information about a single user, including their username, user ID number (UID), home directory, and the login shell.

The following sections present multiple ways to access the data in /etc/passwd and list users on Linux distributions.

The commands used in the tutorial are:

Note: To display a list of the logged-on users and the information such as boot time, processes, hostnames, and more, use the who command.

Читайте также:  Linux path usr local bin

List Users with cat Command

The cat command provides a straightforward way to list the contents of the /etc/passwd file.

The system outputs the entire file with all the users on the system.

The output of the cat command used on passwd file.

To view the number of users only, pipe the output of the previous command to the wc command and make it count the number of lines:

The number of lines in /etc/passwd corresponds to the total number of users.

Counting the number of lines in the passwd file with the cat and wc commands.

List Users with Terminal Pagers less and more

On systems with many users, it is useful to limit the /etc/passwd file output displayed at once. Use a terminal pager command, such as less or more , to browse through the file content line by line or page by page.

To open /etc/passwd using less , enter:

The first page of the file appears in the output. The list stops when it reaches the end of the terminal screen. Use the keyboard to navigate through the file.

Using the less command to control the amount of output on the screen.

Use more to get a similar result. This command is older and has a more limited set of functionalities:

Using the more command to control the amount of output on the screen.

List Users with awk Command

Use the awk command to list the usernames only, without additional information about each user. Since the data fields in /etc/passwd are separated by a colon symbol, the following syntax tells awk to output only the first field in each line:

Displaying only the usernames using the awk command.

Combine awk and less for a page-by-page view of the results.

List Users with getent Command

The getent command searches and displays system database entries. The searchable databases are listed in the /etc/nsswitch.conf file. By default, the file includes the passwd database.

List the entire contents of the passwd database by typing:

The output is the same as the output of the cat command.

The ouput of the getent passwd command.

However, you can use getent to look up specific users. To do so, use the following syntax:

If the user exists on the system, the command shows the related passwd entry line.

Searching the passwd base by username using the getent command to list users in Linux.

Listing Normal and System users in Linux

Linux-based systems have two types of users — system and normal users.

  • System users are entities created by the system to run non-interactive processes, i.e., the processes that run in the background and do not require human interaction. The most important system user is root, which possesses administrative privileges.
  • Normal users are human users created by root or another user with root privileges. Each normal user has a login shell and a home directory to store their files.

Both system and normal users in Linux have a unique user ID (UID) to identify them. System users have UIDs in the range from 0 (root user) to 999. Normal users typically receive UIDs from 1000 onwards, with each newly created user receiving the next smallest unused UID.

To check the UID range for normal users, use the grep command to search for the information stored in /etc/login.defs :

grep -E '^UID_MIN|^UID_MAX' /etc/login.defs

The output in this example shows that the smallest UID a normal user can receive is 1000, and the largest is 60000.

Using the grep command to check the smallest and largest UID a normal user can receive.

Use getent to search the passwd database by UID:

The output shows the user entry related to the UID.

Searching the user according to their UID using getent.

Use UIDs in combination with getent to search for users in a range:

The command now lists all the users within the specified UID range.

Searching the passwd database by providing a UID range, using getent to list users in Linux.

This guide showed you how to list all Linux users, search for users, and find the number of Linux users in any Linux distribution.

Источник

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