Linux find user uid

Содержание
  1. Как узнать id пользователя Linux
  2. Как узнать id пользователя в Linux
  3. Выводы
  4. Все, что вам нужно знать о UID в Linux
  5. Что такое UID в Linux?
  6. Как найти UID пользователя в Linux?
  7. Как изменить UID пользователя в Linux?
  8. Linux / Unix id Command Examples
  9. Purpose
  10. id command syntax
  11. Linux / Unix id command examples
  12. Display your own UID and GID
  13. How do I find a specific user’s UID?
  14. How do I find a specific user’s GID?
  15. How do I see the UID and all groups associated with a user name?
  16. Find out all the groups a user belongs to…
  17. Display a name instead of a UID/GID
  18. How do I display real ID instead of the effective ID for specified user?
  19. 📑 Команда id — найти UID пользователя или GID
  20. синтаксис команды id
  21. Показать свой собственный UID и GID
  22. Как найти UID конкретного пользователя?
  23. Как найти GID конкретного пользователя?
  24. Как увидеть UID и все группы, связанные с именем пользователя?
  25. Как узнать все группы, к которым принадлежит пользователь…
  26. Отображать имя вместо UID / GID
  27. Параметры команды id
  28. Смотрите также
  29. Everything Important You Need to Know About UID in Linux
  30. What is UID in Linux?
  31. How to find the UID of a user in Linux?
  32. How to change UID of a user in Linux?
  33. How does UID associate with different system resources? [for advanced users]
  34. UID and files
  35. UID and processes

Как узнать id пользователя Linux

Иногда возникает необходимость узнать id пользователя Linux. Это может понадобиться, если вы хотите вручную добавить группу для пользователя или вам нужно выполнить другие операции с файлами /etc/passwd или /etc/shadow.

В этой небольшой заметке мы поговорим о том, как посмотреть id пользователя с помощью различных команд в Linux.

Как узнать id пользователя в Linux

Самый простой способ посмотреть идентификатор текущего пользователя — использовать команду id, она выводит не только сам UID, но и идентификатор группы пользователя, а также основные группы этого пользователя:

Первым выводится именно id пользовтеля. Если вам нужно узнать информацию о другом пользователе, вы можете передать его имя в параметры утилиты:

Когда необходимо вывести только id пользователя:

id -u имя_пользовтеля

Если вам надо узнать только id группы определенного пользователя, то используйте опцию -g:

id -g имя_пользователя

Есть ещё несколько способов посмотреть id. Например, для текущего пользователя его можно найти в переменной окружения UID:

Ещё один вариант — утилита getent:

getent passwd имя_пользователя

Или смотрим содержимое файла /etc/passwd с помощью команды grep:

grep имя_пользователя /etc/passwd

Здесь первый цифровой параметр — это сам id, а второй, который расположен за двоеточием, — это GID.

Выводы

В этой небольшой статье мы рассмотрели, как узнать id пользователя Linux. Если у вас остались вопросы, спрашивайте в комментариях!

Источник

Все, что вам нужно знать о UID в Linux

Главное меню » Операционная система Linux » Все, что вам нужно знать о UID в Linux

Что такое UID в Linux?

UID обозначает идентификатор пользователя. UID – это номер, назначенный каждому пользователю Linux. Это представление пользователя в ядре Linux.

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

Вы можете найти UID в файле /etc/passwd. Это тот же файл, который можно использовать для составления списка всех пользователей в системе Linux.

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

Третье поле здесь представляет идентификатор пользователя или UID.

Обратите внимание, что в большинстве дистрибутивов Linux UID 1-500 обычно зарезервирован для системных пользователей. В Ubuntu и Fedora UID для новых пользователей начинаются с 1000.

Например, если вы используете команду useradd или adduser для создания нового пользователя, он получит следующий доступный номер после 1000 в качестве своего UID.

Как найти UID пользователя в Linux?

Вы всегда можете положиться на файл /etc/passwd, чтобы получить UID пользователя. Это не единственный способ получить информацию UID в Linux.

Команда id в Linux отобразит UID, GID и группы, к которым принадлежит ваш текущий пользователь:

Вы также можете указать имена пользователей с помощью команды id, чтобы получить UID любого пользователя Linux:

Как изменить UID пользователя в Linux?

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

Читайте также:  Как запустить восстановление системы windows 10 через флешку

Вы можете изменить UID, изменив пользователя с помощью команды usermod следующим образом:

Вы должны иметь привилегию суперпользователя для выполнения вышеуказанной команды.

Вы помните концепцию прав доступа и владения файлами в Linux? Право собственности на файл определяется UID пользователя-владельца.

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

Что вы можете сделать, это вручную обновить владельца файлов, связанных со старым UID пользователя_2.

Вот и все. Мы надеемся, что теперь у вас есть лучшее представление об UID в Linux. Не стесняйтесь задавать свои вопросы, если таковые имеются.

Как профессиональный пользователь Linux, если вы думаете, что мы пропустили какое-то важное понятие об UID, пожалуйста, дайте мне знать в разделе комментариев.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Linux / Unix id Command Examples

I am a new Linux and Unix system user. How do I find out the user and groups names and numeric IDs of the current user or any users on my server? How can I display and effective IDs on the system using command line options? In Linux, how do I find a user’s UID or GID?

To find a user’s UID (user ID) or GID (group ID) and other information in Linux/Unix-like operating systems, use the id command.

id command details
Description Get user identity
Category N/A
Difficulty Easy
Root privileges No
Est. reading time 5m
Table of contents
  • » Syntax
  • » Examples
  • » Show your own UID and GID
  • » Display a user’s UID
  • » Display a user’s GID
  • » See groups associated with a user
  • » Display a name instead of a UID/GID
  • » Display real ID instead of the effective ID
  • » SELinux show security context
  • » Unix — Show process audit UID
  • » EUID and UID shell variables
  • » Determining root privileges in a script
  • » Options
  • » Related media
  • » See also

Purpose

Displays the system identifications of a specified user.

id command syntax

The basic syntax is:

id
id [UserNameHere] id [options] id [options] [UserNameHere]

By default id command shows the the user and group names and numeric IDs, of the calling process i.e. the current user who runs the id command on screen. If a login name or user ID ( [UserNameHere] ) given on command line, the user and group IDs of that user are displayed.

Linux / Unix id command examples

Let us see how to find a user’s UID or GID on Linux or Unix-like operating systems using 13 id command practical examples. First, open the Terminal application and then type:

Display your own UID and GID

Type the command:
id
Sample outputs:

Fig. 01: id command in action

How do I find a specific user’s UID?

In this example, find a vivek user’s UID, type:
id -u
id -u vivek
Sample outputs:

How do I find a specific user’s GID?

In this example, find a vivek user’s GID, run:
id -g
id -g vivek
Sample outputs:

How do I see the UID and all groups associated with a user name?

In this example, find the UID and all groups associated with a user called ‘root’, enter:
id
id root
Sample outputs:

Find out all the groups a user belongs to…

In this example, display the UID and all groups associated (secondary groups) with a user called ‘vivek’, run:
id -G
id -G vivek
Sample outputs

Display a name instead of a UID/GID

By default, id command displays number for the -G , -g and -u options. You can force id command to display the name of the UID or GID instead of the number for the -G , -g and -u options by passing the -n option as follows:
id -ng
id -nu
id -nG
id -nG vivek
Sample outputs:

How do I display real ID instead of the effective ID for specified user?

You can show the real ID for the -g , -G and -u options instead of the effective ID by passing the -r option:

Источник

📑 Команда id — найти UID пользователя или GID

Чтобы найти UID пользователя (ID пользователя) или GID (идентификатор группы) и другую информацию в Linux/Unix-подобных операционных системах, используйте команду id.

Эта команда полезна для поиска следующей информации:

  • Получить имя пользователя и реальный идентификатор пользователя
  • Найти UID конкретного пользователя
  • Перечислите все группы, к которым принадлежит пользователь
  • Показать UID и все группы, связанные с пользователем
  • Отображение контекста безопасности текущего пользователя
  • Эффективное имя пользователя Linux или Unix и эффективный идентификатор пользователя (UID)
  • Имя действующей группы пользователей Linux или Unix и идентификатор эффективной группы (GID)

Цель

Отображает системные идентификаторы указанного пользователя.

синтаксис команды id

По умолчанию команда id показывает имена пользователей и групп и числовые идентификаторы вызывающего процесса, то есть текущего пользователя, который запускает команду id на экране. Если имя пользователя или идентификатор пользователя ([UserNameHere]) указаны в командной строке, отображаются идентификаторы пользователя и группы этого пользователя.

Показать свой собственный UID и GID

Как найти UID конкретного пользователя?

В этом примере найдите UID пользователя vasia, введите:

Как найти GID конкретного пользователя?

В этом примере найдите GID пользователя vasia, запустите:

Как увидеть UID и все группы, связанные с именем пользователя?

В этом примере найдите UID и все группы, связанные с пользователем с именем «root», введите:

Как узнать все группы, к которым принадлежит пользователь…

В этом примере отобразите UID и все группы, связанные (вторичные группы) с пользователем с именем «vasia», запустите:

1000 20 12 61 79 80 81 98 33 100 204 398 399

Отображать имя вместо UID / GID

По умолчанию команда id отображает число для опций -G, -g и -u. Вы можете заставить команду id отображать имя UID или GID вместо номера для опций -G, -g и -u, передав опцию -n следующим образом:

Как отобразить реальный идентификатор вместо эффективного идентификатора для указанного пользователя?

Вы можете показать действительный идентификатор для параметров -g, -G и -u вместо эффективного идентификатора, передав опцию -r:

Параметры команды id

Опция Назначение OS
-g Показать только эффективный идентификатор группы ALL
-G Показать все идентификаторы группы ALL
-u Показать только эффективный идентификатор пользователя ALL
-n Показать имя вместо числа, для -u или -g ALL
-r Показать действительный идентификатор вместо действующего, с -u или -g ALL
-Z Показать только контекст безопасности текущего пользователя SELinux SELinux
-A Показать идентификатор пользователя аудита процесса и другие свойства аудита процесса Только Unix-like.

Смотрите также

man id — Страница руководства по команде id

Источник

Everything Important You Need to Know About UID in Linux

What is UID in Linux?

UID stands for user identifier. A UID is a number assigned to each Linux user. It is the user’s representation in the Linux kernel. The UID is used for identifying the user within the system and for determining which system resources the user can access. This is why the user ID should be unique.

You can find UID stored in the /etc/passwd file. This is the same file that can be used to list all the users in a Linux system.

Use a Linux command to view text file and you’ll see various information about the users present on your system.

The third field here represents the user ID or UID.

UID and GID in /etc/passwd File in Linux

Do note that in most Linux distributions, UID 1-500 are usually reserved for system users. In Ubuntu and Fedora, UID for new users start from 1000.

For example, if you use adduser or useradd command to create a new user, it will get the next available number after 1000 as its UID.

In Linux, UID 0 and GID 0 is reserved for the root user.

How to find the UID of a user in Linux?

You can always rely on the /etc/passwd file to get the UID of a user. That’s not the only way to get the UID information in Linux.

The id command in Linux will display the UID, GID and groups your current user belongs to:

You can also specify the user names with the id command to get the UID of any Linux user:

How to change UID of a user in Linux?

Suppose you had several users on your Linux system. You had to delete a user because he/she left the organization. Now you want its UID to be taken by another user already on the system.

You can change the UID by modifying the user using usermod command like this:

You need to have superuser privilege to execute the above command.

Do you remember the file permission and ownership concept in Linux? The ownership of a file is determined by the UID of the owner user.

When you update the UID of a user, what happens to the files owned by this user?While all the files in the home directory of user_2 will have their associated UID changed, you’ll have to manually update the associated UID of other files outside the home directory.

What you can do is manually update the ownership of the files associated with the old UID of the user_2.

How does UID associate with different system resources? [for advanced users]

UIDs are unique to one another and thus they can also be used to identify ownership of different system resources such as files and processes.

UID and files

I hope you are familiar with the file permission concept in Linux. When you’re creating a file, you’re the owner of this file. Now you can decide who gets to do what with this file. This is part of Linux’s DAC mechanism where each file is left at its owner’s discretion.

You can read a file’s ownership by using either ls or stat command. Let’s do it with the popular ls command and check the ownership of either the binary sleep or passwd .

As you can see, the file /usr/bin/sleep belongs to root:

Let’s force it to map the ownership with UID instead of username:

Here’s fun information. Your operating system doesn’t understand «usernames». Whenever a program needs to work with usernames or needs to print such, it refers to the /etc/passwd file to extract the information.

You don’t have to take my words for it. See it yourself with strace program which prints all the system calls made by a program.

What you are trying to see is whether ls command is trying to read the /etc/passwd file or not.

UID and processes

Processes have owners too, just like files. Only the owner (or the root user) of a process can send process signals to it. This is where the UID comes into play.

If a normal user tries to kill a process owned by another user, it will result in error:

Only the owner of the process or the root can do this.

A process must be regulated. Regulated as in you need to have a way to limit or know how much a process is allowed to do. This is determined by its UID(s).

There are three types of UIDs associated with a process.

  1. Real UID: Real UID is the UID that a process adopts from its parent. In easier terms, whoever starts a process, the UID of that user is the real UID of the process. This is helpful in identifying who a process really belongs to. This is essential especially when the effective UID is not the same as the real UID which I’m going to talk about next.
  2. Effective UID: This is what mostly determines what permissions a certain process really has. While a user can start the process, it can run with a different user’s available permissions. The command passwd is one example of this. This program edits the file /etc/shadow , which is root owned. Therefore, a normal user shouldn’t be able to run this command or change his/her password. Luckily, the binary runs with an effective UID of 0 (i.e. root), which enables it to have enough privilege to edit the /etc/shadow file. Real and effective UIDs are mostly the same except in the case of SUID bit enabled binaries.
  3. Saved UID: UID that’s available at a process’s disposal. This one is not normally used, but is still there in case the process knows it’s not going to perform any privileged work, so it can change its effective UID to something that’s unprivileged. This reduces the surface of an unintentional misbehavior.

That’s it. I hope you have a better idea about UID in Linux now. Don’t hesitate to ask your questions, if any.

As a pro Linux user, if you think I missed some important concept about UID, please let me know in the comment section.

Источник

Читайте также:  Как сделать панель задач прозрачной windows 10 без активации
Оцените статью