Linux change uid user

How to Change a USER and GROUP ID on Linux For All Owned Files

  1. Become superuser or get an equivalent role using sudo command/su command
  2. First, assign a new UID to user using the usermod command.
    Tutorial details
    Difficulty level Easy
    Root privileges Yes
    Requirements None
    Est. reading time 2m
  3. Second, assign a new GID to group using the groupmod command.
  4. Finally, use the chown and chgrp commands to change old UID and GID respectively. You can automate this with the help of find command.
  5. Verify that the group owner of the file has changed using the ls command

Change a USER and GROUP ID on Linux

It cannot be stressed enough how important it is to make a backup of your system before you do this. Make a backup. Let us say, our sample user name is foo

  1. Foo’s old UID: 1005
  2. Foo’s new UID: 2005
  3. Our sample group name: foo
  4. Foo’s old GID: 2000
  5. Foo’s new GID: 3000

Linux command to change UID and GID

To assign a new UID to user called foo, enter:
# usermod -u 2005 foo
To assign a new GID to group called foo, enter:
# groupmod -g 3000 foo
Verify that you changed UID and GID for given users with the help of ls command:
# ls -l
Please note that all files which are located in the user’s home directory will have the file UID changed automatically as soon as you type above two command. However, files outside user’s home directory need to be changed manually. To manually change files with old GID and UID respectively, enter:
# find / -group 2000 -exec chgrp -h foo <> \;
# find / -user 1005 -exec chown -h foo <> \;

The -exec command executes chgrp or chmod command on each file. The -h option passed to the chgrp/chmod command affect each symbolic link instead of any referenced file. Use the following command to verify the same:
# ls -l /home/foo/
# id -u foo
# id -g foo
# grep foo /etc/passwd
# grep foo /etc/group
# find / -user foo -ls
# find / -group sales -ls

  • 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

Conclusion

This page explained how to change group and user ownership of a file in Linux operating systems using the command-line utilities such as chgrp and others. See man page of chgrp for more info here.

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

Источник

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

Источник

Изменение UID&GID пользователя и его файлов


Встала тут передо мной задача изменить UID и GID пользователя и правильно изменить владельца всех файлов.
Дело в том, что я работаю за двумя компьютерами попеременно, и файлы mysql лежат у меня на флешке. Получилось так, что id пользователя mysql на обоих компах отличается и мускл не может получить доступ к своим файлам. Присваивать права 0666 скучно, и по этому поводу я решил научиться грамотно изменять uid пользователя 🙂

Казалось бы, всё просто, но есть два нюанса которые необходимо учесть:

  1. UID и GID не всегда одинаковы для пользователя и его группы
  2. Не все файлы принадлежат одновременно юзеру mysql и группе mysql: файлы для chown нужно искать отдельно

Статья написана для тех, кто ещё не делал ничего подобного а также кто хочет научиться продвинутому использованию команды find и узнать что такое xargs.

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

user =mysql new_uid = 600 old_uid =$ ( id -u $user )
group =mysql new_gid = 600 old_gid =$ ( id -g $user )
sudo usermod -u $new_uid $user
sudo groupmod -g $new_gid $group

Поиск осиротевших файлов

Если сейчас посмотреть на одну из папок с файлами mysql (например, ls -lah /var/lib/mysql ) то мы увидим, что файлы принадлежат подозрительному пользователю 112 и подозрительной группе 127. Такие файлы мы и будем искать с тем, чтобы удочерить их 🙂

Первое, что приходит в голову, это найти все файлы принадлежащие пользователю $old_uid или группе $old_group , и собрать все найденные файлы (при помощи xargs) в качества аргументов команде chown $user:$group . find выполняется от root чтобы гарантировать что он сможет забраться во все даже самые сурово защищённые папки и найдёт всё что от него требуется. xargs собирает строки из pipe и передаёт их команде, указанной в аргументе (chown). Замечу, что xargs может выполнить команду несколько раз во избежание слишком длинной строки аргументов.
Например, так:

sudo find / -user $old_uid -or -group $old_gid -print0 | xargs -0 sudo chown $user : $group

Сразу обращу внимание на флаги find -print0 и xargs -0 : это такая борьба с возможными пробелами в именах файлов. Такие файлы могут быть восприняты chown ‘ом как два разных. Первый флаг заставляет find выводить каждый найденный файл с нулём в конце (символ конца строки в Си), а второй флаг сообщает xargs что ему нужно отделять файлы друг от друга не по переводу строки, а по этому самому нулю, что гарантирует верную обработку даже самых хитрых имён файлов 🙂

Однако такой способ не принесёт желаемого результата: некоторые файлы, владельцем которых был ‘mysql:root’ станут принадлежать ‘mysql:mysql’. А мы ведь договорились сделать всё предельно правильно 🙂 Следовательно, поиск по user и по group надо вести отдельно.

Можно выполнить подряд две команды find:

sudo find / -user $old_uid -print0 | xargs -0 sudo chown $user
sudo find / -group $old_gid -print0 | xargs -0 sudo chown : $group

и это уже будет намного ближе к истине, но тогда find ‘у придётся дважды шуршать по всему жёсткому диску.

Есть способ заставить команду find выполнить для нас две операции параллельно, сократив количество чтений с диска ровно в два раза. Для этого используем группировку условий и команд find круглыми скобками (не забывая их экранировать: иначе за них возьмётся шелл) и пославив между ними оператор «запятая»: тогда обе скобки будут выполняться для каждого файла.
Мы составим два отдельных файла: в первом будет список файлов с -user=$old_uid , а во втором — с -group=$old_gid , и обрабатывать эти файлы мы будет раздельно. Условие поиска теперь разделено на две выполняющися для каждого файла скобки, и в случае выполниния условия команда -fprint0 записывает в соответствующий временный файл путь к найденному осиротевшему файлу.

chownlist =$ ( tempfile ) chgrplist =$ ( tempfile )
sudo find / \
\ ( -user $old_uid -fprint0 » $chownlist » \ ) , \ ( -group $old_gid -fprint0 » $chgrplist » \ )

После недолгого поиска все файлы будут найдены.

Последний момент поиска: на форумах очень часто задаётся вопрос как исключить папки из списка find так, чтобы он туда вообще не залезал. Это делается при помощи сочетания условия -path «folder» и команды -prune , которая запрещает find залезать в папки, попавшие в условие. Мы исключим из поиска папки ‘/proc’ и ‘/sys’.
Для этого в условия добавим ещё одну группировку скобками, отделив их от уже существующих скобок оператором -or . Этот оператор выполнит первое условие, а второе — только если не сработало первое. Так, find проверит не попалась ли ему исключённая из листинга директория (в которой он не будет искать), и если нет — будет составлять списки файлов.
Делается это так:

chownlist =$ ( tempfile ) chgrplist =$ ( tempfile )
sudo find / \
\ ( \ ( -path «/proc» -or -path «/sys» \ ) -prune \ ) -or \ # исключение папок
\ ( \ ( -user $old_uid -fprint0 » $chownlist » \ ) , \ ( -group $old_gid -fprint0 » $chgrplist » \ ) \ )

Также в исключения можно внести путь к диску с бекапом (он ведь у вас есть, верно? ;), подмонтированные сетевые шары и прочее.

Финиш

cat » $chownlist » | xargs -0 sudo chown $user
cat » $chgrplist » | xargs -0 sudo chown : $group
sudo rm » $chownlist » » $chgrplist » # Не забываем подчистить за собой

Проверка

sudo find / -nouser -or -nogroup -print

Если всё было сделано правильно (и в системе не водилось осиротевших файлов) — команда не должна ничего вывести.

Полный код скрипта

Надеюсь, статья окажется полезной. Рекомендую ближе ознакомиться с синтаксисом этой команды: она ведь намного мощнее чем вы думаете 🙂
Напоследок приведу полный код скрипта для смены UID&GID пользователя и его файлов:

#=== Настройки
user =mysql new_uid = 600 old_uid =$ ( id -u $user ) # имя, новый и старый UID
group =mysql new_gid = 600 old_gid =$ ( id -g $user ) # имя, новый и старый GID
#=== Смена UID & GID
sudo usermod -u $new_uid $user
sudo groupmod -g $new_gid $group
#=== Поиск файлов
chownlist =$ ( tempfile ) chgrplist =$ ( tempfile ) sudo find / \
\ ( \ ( -path «/proc» -or -path «/sys» \ ) -prune \ ) -or \
\ ( \ ( -user $old_uid -fprint0 » $chownlist » \ ) , \ ( -group $old_gid -fprint0 » $chgrplist » \ ) \ )
#=== chown и чистка
cat » $chownlist » | xargs -0 sudo chown $user
cat » $chgrplist » | xargs -0 sudo chown : $group
sudo rm » $chownlist » » $chgrplist «

Источник

Читайте также:  Windows 10 disable driver autoupdate
Оцените статью