Идентификатор пользователя в линукс

Everything Important You Need to Know About UID in Linux

This Linux Basics guide teaches you everything important associated with 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.

root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/usr/sbin/nologin man:x:6:12:man:/var/cache/man:/usr/sbin/nologin lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail:x:8:8:mail:/var/mail:/usr/sbin/nologin news:x:9:9:news:/var/spool/news:/usr/sbin/nologin johndoe:x:1000:1000:John Doe. /home/helder:/bin/bash davmail:x:127:65534::/var/lib/davmail:/usr/sbin/nologin statd:x:128:65534::/var/lib/nfs:/usr/sbin/nologin

The third field here represents the user ID or UID.

Uid Gid Etc Passwd File 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.

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:

id uid=1000(abhishek) gid=1000(abhishek) groups=1000(abhishek),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),116(lpadmin),126(sambashare),127(kvm)

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

id standard uid=1001(standard) gid=1001(standard) groups=1001(standard)

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.

find / -user old_uid_of_user_2 -exec chown -h 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:

ls -l $(which sleep) -rwxr-xr-x 1 root root 39048 Mar 6 2020 /usr/bin/sleep

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

ls -lhn $(which sleep) -rwxr-xr-x 1 0 0 39K Mar 6 2020 /usr/bin/sleep

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.

strace ls -lhn $(which sleep) 2>&1 | grep passwd 

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

strace ls -lh $(which sleep) 2>&1 | grep passwd openat(AT_FDCWD, "/etc/passwd", O_RDONLY|O_CLOEXEC) = 6

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:

kill 3708 bash: kill: (3708) - Operation not permitted

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.
Читайте также:  Android app for linux

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.

Источник

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

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

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

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

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

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

id id [UserNameHere] id [параметры] id [параметры] [имя_пользователя]

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

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

uid=1000(vasia) gid=1000(vasia) группы=1000(vasia),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),130(sambashare),132(libvirtd),134(lxd)

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

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

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

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

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

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

uid=0(root) gid=0(root) группы=0(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 следующим образом:

id -ng id -nu id -nG id -nG vasia
vasia adm cdrom sudo dip plugdev lpadmin sambashare libvirtd lxd

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

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

id -r -g id -r -u ### [NOTE]########################### ### -r and -G only works on Linux ### ##################################### id -r -G id -r -u vasia

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

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

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

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

  • Методы монтирования дисков в Linux
  • Введение в диспетчер логических томов (LVM)
  • Локальное туннелирование с помощью SSH: несколько примеров
  • Альтернативы SSH, которые в некоторых случаях лучше оригинала
  • Полный набор лучших и современных консольных программ для Linux
  • Установка ZoneMinder на Ubuntu 22.04 (Linux Mint 21) и nginx
  • Устанавливаем GIMP в Ubuntu 22.04 (Linux Mint 21)
  • Устанавливаем qBittorrent в Linux Ubuntu/Mint
  • Исправляем ошибку — network unreachable resolving ‘./NS/IN’: 2001:503:c27::2:30#53
  • Установка remmina из ppa в Ubuntu 22.04 или Mint 21
  • Исправляем: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg)
  • Что такое зомби-процесс в Linux?
  • Хитрости командной строки Bash, которые помогут вам работать быстрее
  • Команда ls в Linux — подробно и с примерами
  • Команда mkdir в Linux — подробно и с примерами
  • Список непечатаемых символов Linux, MacOS или Windows
  • Команда chmod в Linux — подробно и с примерами
  • Команда cat и примеры её использования в Linux
  • Как установить приложение Yarock Music Player
  • Запуск нескольких команд Linux одной составной командой
  • Файловый менеджер nnn
  • Версия системы и версия ядра Ubuntu/Mint
  • Запуск команд на удаленном сервере через SSH
  • Цветовые схемы и внешний вид MC (midnight commander)
  • Переключение кодировок в MC
  • Шпаргалка по горячим клавишам для файловых панелей MC (midnight commander)
  • Ошибка NO_PUBKEY. Как найти GPG-ключ и добавить его в базу apt системы Ubuntu
  • Установка драйвера wifi Asus wl-167g v3 (rtl8192) для Ubuntu 16.04 и 18.04
  • Как настроить wifi из командной строки в Ubuntu
  • Изменение имени сетевого интерфейса в Ununtu/Mint
  • nmon — удобный инструмент для мониторинга Linux систем
  • Ошибка: 502 bad gateway — connect() to unix:/run/php/php-fpm.sock failed (11: Resource temporarily unavailable)
  • Команда history или работа с историей введенных команд
  • Шпаргалка по архиватору 7z (7-Zip) в Linux Ubuntu/Mint
  • Преобразование видео от 1080p до 720p с наименьшими потерями с использованием ffmpeg
  • Как посмотреть все доступные шрифты в терминале (CLI)?
  • Команда id — найти UID пользователя или GID
  • Лучшие рекомендации по повышению безопасности для серверов OpenSSH
  • Разрешения файлов директории .SSH
  • Настройка Nginx FastCGI Cache для сокращения времени отклика сервера WordPress
  • Как получить реальный IP-адрес пользователя в nginx за обратным прокси-сервером nginx
  • Чем отличается прямой прокси от обратного прокси
  • Руководство по iptables (Iptables Tutorial 1.1.19)
  • Настройка автозапуска скриптов в Linux Ubuntu/Mint
  • Устанавливаем оболочку bash про умолчанию
  • SOCS5 прокси сервер DANTE — установка и настройка
  • Сервис online настройки параметров сервера nginx
  • nmblookup — аналог команды Windows nbtstat для Linux.
  • Inxi — программа вывода информации о системе и железе в Linux
  • dnstop — мониторинг и анализатор DNS-трафика

Источник

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