Linux user with uid 0

Все, что вам нужно знать о 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 был занят другим пользователем, уже находящимся в системе.

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

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

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

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

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

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

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

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

Источник

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.

Читайте также:  All in one emulator mac os

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:

Читайте также:  Как открыть панель управления графикой intel windows 10

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.

Источник

Linux Change or Rename User Name and UID

Linux Change or Rename User Command Syntax

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Linux terminal
Est. reading time 5 mintues

The syntax is as follows to rename by user name:
usermod -l login-name old-name

  • We use the usermod command in Linux to rename user account. The name of the user will be changed from the old-name to login_name. Nothing else is changed. In particular, the user’s home directory name should probably be changed to reflect the new login name.

The syntax is as follows to rename by a UID (user ID):
usermod -u UID username
Where,

  • The numerical value of the user’s ID (UID) . This value must be unique unless the -o option is used. The value must be non-negative. Values between 0 and 99 are typically reserved for system accounts. Any files which the user owns and which are located in the directory tree rooted at the user’s home directory will have the file user ID changed automatically. Files outside of the user’s home directory must be altered
    manually.

List all users in Linux system

Type the following cat command:
cat /etc/passwd
One can use the grep command to filter out only user names:
grep -w ‘^username’ /etc/passwd
grep -w ‘^jerry’ /etc/passwd
Another option is to use the cut command:
cut -d: -f1 /etc/passwd
Sample outputs:

How to Change or Rename Username and UID in Linux

Let us see how to rename user login. First, make sure user name is not logged into the server and any other process is not running under the same user name. I also recommend that you backup any data or server files before changing user names.

View current user and group membership for user named tom

First get user identity using the id command:
id tom
Next use the grep command to grab login info about user named tom from the /etc/passwd file
grep ‘^tom:’ /etc/passwd
See group info about user named tom using the groups command:
grep ‘tom’ /etc/group
groups tom
Find home directory permissions for user named tom, run the following ls command:
ls -ld /home/tom/
Finally, see all Linux process owned by user and group named tom using the ps command:
ps aux | grep tom
ps -u tom

Fig.01: Getting info about user named ‘tom’ on a Linux based system

Rename and change username from tom to jerry on Linux

Type the usermod command as follows:
# id tom
# usermod -l jerry tom
## Verify ###
# id tom
# id jerry
# ls -ld /home/tom

A note about running process

You may see an error as follows if tom is logged in and running jobs:

You need to kill all Linux process owned by user named tom and forcefully logged them out of the system:

Rename and change primary groupname from tom to jerry

Type the usermod command as follows:
# id tom
# groupmod -n jerry tom
## Verify it ###
# id tom
# ls -ld /home/tom
Sample outputs:

Fig.02: Sample session renaming user on a Linux based server

How to change user home directory from /home/tom/ to /home/jerry

The syntax is as follows:
# usermod -d /home/jerry -m jerry
# id jerry
# ls -ld /home/jerry
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

How to change user tom UID from 5001 to 10000

Type the usermod command as follows:
# id tom
# usermod -u 10000 tom
# id tom

Getting help about usermod command

You can pass the —help option to the usermod command. For instance, type the following command at the shell prompt in Linux:
usermod —help

Options Description
-c OR —comment COMMENT new value of the GECOS field
-d OR —home HOME_DIR new home directory for the user account
-e OR —expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE
-f OR —inactive INACTIVE set password inactive after expiration to INACTIVE
-g OR —gid GROUP force use GROUP as new primary group
-G OR —groups GROUPS new list of supplementary GROUPS
-a OR —append append the user to the supplemental GROUPS mentioned by the -G option without removing the user from other groups
-h OR —help display this help message and exit
-l OR —login NEW_LOGIN new value of the login name
-L OR —lock lock the user account
-m OR —move-home move contents of the home directory to the new location (use only with -d)
-o OR —non-unique allow using duplicate (non-unique) UID
-p OR —password PASSWORD use encrypted password for the new password
-R OR —root CHROOT_DIR directory to chroot into
-P OR —prefix PREFIX_DIR prefix directory where are located the /etc/* files
-s OR —shell SHELL new login shell for the user account
-u OR —uid UID new UID for the user account
-U OR —unlock unlock the user account
-v OR —add-subuids FIRST-LAST add range of subordinate uids
-V OR —del-subuids FIRST-LAST remove range of subordinate uids
-w OR —add-subgids FIRST-LAST add range of subordinate gids
-W OR —del-subgids FIRST-LAST remove range of subordinate gids
-Z OR —selinux-user SEUSER new SELinux user mapping for the user account

Conclusion

In this tutorial, you learned how to change or rename username and UID in Linux using the usermod command. Read man pages of usermod(8) and groupmod(8) commands for more information see this page.

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

Источник

Читайте также:  Udp открывает порт linux
Оцените статью