Меню Рубрики

Linux change group 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 Easy (rss)
    Root privileges Yes
    Requirements None
    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


Let us see some examples and commands to change a user and group ID in Linux:

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

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.

Источник

How can I change a user’s default group in Linux?

Being new to Linux administration, I’m a little confused about the following commands:

I’ve just finished reading the user administration book in the Linux/Unix Administrator’s handbook, but some things are still a little hazy.

Basically useradd seems straight forward enough:

I can add «David Hilbert» with username hilbert , setting his default directory, shell, and groups. And I think that -g is his primary/default group and -G are his other groups.

So these are my next questions:

  1. Would this command still work if the groups faculty and famous did not exist? Would it just create them?
  2. If not, what command do I use to create new groups?
  3. If I remove the user hilbert and there are no other users in those groups, will they still exist? Should I remove them?
  4. After I run the useradd command above, how do I remove David from the famous group, and reassign his primary group to hilbert which does not yet exist?

Источник

Группы пользователей в Linux: создаем группы, добавляем и удаляем из них пользователей

Перевод статьи «Linux User Groups Explained: How to add a new group, a new group member, and change groups».

Linux позволяет многочисленным пользователям работать в системе одновременно. Установка прав доступа защищает пользователей друг от друга. Для объединения пользователей с одинаковыми правами доступа создаются группы. Члены этих групп могут, например, иметь доступ к каким-то файлам или устройствам, в то время как для остальных пользователей доступ будет закрыт.

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

Группы бывают двух основных видов: первичные и вторичные. Первичная группа это основная группа пользователя, установленная для него по умолчанию, с ней связан его аккаунт. Директории и файлы, создаваемые пользователем, имеют Group ID именно этой, первичной группы. Любая другая группа (а их может быть много), в которую входит пользователь, является вторичной.

Создание групп

Давайте создадим две группы: «writers» («писатели») и «editors» («редакторы»). Для этого используется команда groupadd. (Возможно, потребуется также поставить sudo в начале команды, чтобы получить право создавать группы).

Создание пользователей

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

Ниже представлена команда для создания пользователя по имени «quincy». Флаг -m нужен для создания домашней директории пользователя (для ее названия используется имя пользователя). Флаг -p позволяет задать пароль для пользователя, в данном случае — «p4ssw0rd».

Позже пользователь сможет изменить свой пароль при помощи команды passwd. Для этого ему понадобится ввести текущий пароль и новый.

Добавление пользователя в группу

Для добавления пользователя в группу используется команда usermod. Давайте добавим пользователя «quincy» в группу «writers». Опция -a означает «append» («добавить», «прикрепить»), а опция -G служит для указания названия вторичной группы.

Когда вы создаете пользователя при помощи команды adduser, для него автоматически создается первичная группа, носящая его имя. Поэтому в настоящее время пользователь «quincy» состоит в первичной группе «quincy» и вторичной «writers».

Также можно добавить пользователя сразу в несколько групп, перечислив их через запятую без пробелов (-G group1,group2,group3).

А эта команда изменит первичную группу пользователя quincy на группу «editors»:

Удаление пользователя из вторичной группы

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

При помощи команды id смотрим, в каких группах состоит пользователь (опция -n нужна для вывода названий групп, а не их ID).

Предположим, мы увидели, что пользователь quincy состоит в группах «editors» и «writers». Если мы хотим удалить его из группы «writers», мы можем воспользоваться следующей командой:

Эта команда очень похожа на ту, которой мы установили для пользователя quincy вторичную группу «editors». Но поскольку мы сейчас не использовали флаг -a, предыдущий список групп просто перезаписался, и теперь в нем нет группы «writers».

Заключение

Теперь вы можете начать управлять группами и пользователями. Следующий шаг — определить, какие привилегии должны быть у каждой группы.

Источник

Safely change primary group of a user in Linux

When it comes to user permission even a system administrator sometimes gets confused. No matter what linux training or administration training courses one has had one mistake and sever management can become a hell. Same holds true even for a Linux user at home. One has to be extremely careful while changing the primary group of any existing user. If you do some research, you will find that several people accidentally locked themselves out of being able to sudo. In order to avoid these unnecessary headaches it is essential that you change primary group of a user in linux, correctly.

Record the Current State

Before you change primary group of a Linux user, make a note of the user’s current status. Let us consider a user by the username «mackey». You can find this users current group memberships like this:

The user mackey’s primary group is «mackey». This is user is also associated with a bunch of other groups: adm,cdrom,sudo,dip,plugdev,sambashare,lpadmin.

Note that adm, cdrom, sudo, dip, plugdev, sambashare, and lpadmin are all default secondary groups assigned to a user in Ubuntu 12.04 Precise Pangolin.

Change Primary Group of User

The command to use is «usermod». Below is the syntax of the command:

If you search the internet you may find that you can change the primary group using the following command:

As expected the above command would change mackey’s primary group from «mackey» to «NewPrimaryGroup». However, all of this user’s secondary group memberships will be gone, including «admin». This means that the user will henceforth be not able to use the «sudo» command to gain root access. This user will not be able to do any changes to the system (eg. install/remove softwares).

This, however, does not happen in all distributions. For example, in Ubuntu 12.04 Precise Pangolin «sudo usermod -g NewPrimaryGroup user» command assigns the new primary group to the user keeping all existing secondary groups. Yet, I like to change primary group the safe way, which puts control in my hand.

The safe way to change primary group of a Linux user is using this following command:

This command will first change the user mackey’s primary group from «mackey» to «NewPrimaryGroup». Then it will assign the user «mackey» to the following secondary groups «mackey,adm,cdrom,sudo,dip,plugdev,sambashare,lpadmin». This way mackey’s primary group will be changed without affecting his other group memberships or losing his membership to his previous primary group «mackey».

Want to further understand users, groups, and system administration? Check these learning resources:

How to Fix In Case of a Screw Up

If you change a user’s primary group with just the «-g» option and all of his/her secondary group memberships are gone, then you can fix this by couple of different ways.

Method 1: If you had setup a «root» password previously (not normal in Ubuntu) you can login as «root» and then run the following command:

After running the above command, logout and login as the user (mackey in this case).

Method 2: If you did not setup a password for the user «root» then you cannot login as a root user. In this case, from grub menu boot into recovery and enter command line with root previleges. Then run the same command listed above:

Reboot and the user «mackey» should now have all the secondary groups restored. The primary group will be «NewPrimaryGroup».

If you simply want to add an existing user to a secondary group, retaining all his/her primary and secondary group memberships, then use the following command:

The «-a» option means append to existing memberships.

There you go, now you can change primary group of users safely. Hope this helps.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

  • Mac os как отключить spotlight
  • Mac os как освободить оперативную память
  • Mac os как объединить разделы жесткого диска
  • Mac os как объединить pdf файлы в один
  • Mac os как найти установленную программу