- Удалить пользователя из группы Linux
- Удаление пользователя из группы Linux
- Выводы
- How to Add or Remove Linux User From Group
- Check a User Group in Linux
- Add a User to a Group in Linux
- Remove a User from a Group in Linux
- How do I remove a user from a group?
- 12 Answers 12
- How to Remove a User from a Group Linux
- What are groups in Linux?
- How to remove a user from a group in Linux using gpasswd:
- How to remove a user from a group in Debian or Ubuntu with deluser:
- Removing a user from a group in Linux by editing the /etc/group file:
- Conclusion:
- About the author
- David Adams
Удалить пользователя из группы Linux
Группы пользователей в Linux используются для тонкой настройки доступа к файлам операционной системы. И поскольку в Linux все объекты ОС являются файлами, то с помощью групп можно настроить или ограничить доступ к любой возможности системы.
В одной из предыдущих статей мы говорили о том, как посмотреть список групп Linux, в которых состоит пользователь. В этой же заметке разберём, как удалить юзера из группы Linux, чтобы он больше не мог иметь доступа к файлам, которые находятся в этой группе.
Удаление пользователя из группы Linux
Очень много слов вступления, а дела не более чем на одну команду. Мы будем использовать gpasswd. Она имеет такой синтаксис:
gpasswd -d пользователь группа
Опция -d сообщает, что нужно выполнить удаление, далее мы указываем пользователя, с которым будем работать и в конце группу, из которой его надо удалить. Теперь откройте терминал с помощью сочетания клавиш Ctrl+Alt+T и наберите следующую команду, чтобы удалить пользователя testuser из группы wheel:
sudo gpasswd -d testuser wheel
С помощью команды usermod вы можете удалить текущего пользователя из всех дополнительных групп:
sudo usermod -G «» имя_пользователя
Только будьте осторожны с этой командой, применяя её к текущему пользователю, иначе вы удалите себя из группы sudo и больше не сможете выполнять административные действия. В Ubuntu, где нет прямого доступа к пользователю root это может создать серьёзные проблемы для новичков, смотрите статью сброс пароля в Ubuntu.
В некоторых дистрибутивах можно использовать ещё и команду deluser. Точно также указываем сначала имя пользователя, а затем группу, из которой собираемся его удалить:
sudo deluser testuser adm
Если вы случайно удалили пользователя из группы, в которой он должен быть, можно всё вернуть обратно. Смотрите статью «как добавить пользователя в группу Linux».
Выводы
В этой небольшой статье мы рассмотрели, как удалить пользователя из группы Linux. Как видите, это совсем не сложно, только надо соблюдать осторожность, чтобы не удалить ничего лишнего и не создать себе проблем. Если у вас остались вопросы, спрашивайте в комментариях! Почитать более подробно о группах можно в статье «группы пользователей Linux».
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
How to Add or Remove Linux User From Group
Linux is by default a multi-user system (meaning many users can connect to it simultaneously and work), thus Linux user management is one of the fundamental tasks of a system administrator, which includes everything from creating, updating, and deleting user accounts or user groups on a Linux system.
In this short quick article, you will learn how to add or remove a user from a group in a Linux system.
Check a User Group in Linux
To find out what group a user is in, just run the following groups command and provide the username (tecmint in this example) as an argument.
# groups tecmint tecmint : tecmint wheel
To find out the group of root user in Linux, just run the groups command without any argument.
# group root
Add a User to a Group in Linux
Before trying to add a user to a group, ensure that the user exists on the system. To add a user to a certain group, use the usermod command with the -a flag which tells the usermod to add a user to the supplementary group(s), and the -G option specifies the actual groups in the following format.
In this example, tecmint is the username and postgres is the group name:
# usermod -aG postgres tecmint # groups tecmint
Remove a User from a Group in Linux
To remove a user from a group, use the gpasswd command with the -d option as follows.
# gpasswd -d tecmint postgres # groups tecmint
Additionally, on Ubuntu and its derivatives, you can remove a user from a specific group using the deluser command as follows (where tecmint is the username and postgres is the group name).
$ sudo deluser tecmint postgres
For more information, see the man pages for each of the different commands we have used in this article.
$ man groups $ man usermod $ man gpasswd $ man deluser
You will also find the following user management guides very useful:
How do I remove a user from a group?
Which command should I use to remove a user from a group in Debian? When adding a user to a group, it can be done with:
However, I could not find a similar command (accepting a group and user as arguments) for removing the user from the group. The closest I could get is:
usermod -G all,existing,groups,except,for,group user
Is there a command like usermod OPTION group user with OPTION an option to make usermod (or a similar program) remove the user from group?
For Fedora users who end up here, man usermod reveals in -G option comments that a listing all current groups wish to be retained IS the way to delete a group. No -R option with Fedora; you must use Lekensteyn’s approach he is trying to avoid.
12 Answers 12
# gpasswd --delete user group
The new group config will be assigned at the next login. If the user is logged in, the effects of the command aren’t seen immediately.
Perfect thanks! gpasswd -a user group for adding the user to the group seems also nicer, especially if a typo has made and the -a option gets dropped.
Doesn’t work for me. I get two messages: a) Removing user from group. b) gpasswd: user is not a member of group. Afterwards running «members group» shows no change.
@geoidesic I got these errors on Centos 7. I found you got this, if you were trying to remove the user from their default group. Try switching the default group with usermod -g user user then try to remove them.
On Debian, the adduser package contains a deluser program which removes a user from a group if you pass both as arguments:
If your distribution doesn’t have adduser , you can edit /etc/group and /etc/gshadow manually.
@JonathanLeaders Every user needs to be in at least one group. Use usermod or vipw to change the user’s primary group. This question was about supplementary groups.
removes all secondary/supplementary groups from username, leaving them as a member of only their primary group. this worked in Solaris 5.9
And this seems to be the best way to force the secondary groups to any list of groups, excluding all unlisted groups.
This is the “old school” approach.
Most *nix systems maintain group information into a plain text file /etc/group , where
- each line contains the fields
- group_name
- password
- GID, and
- user_list
delimited by the : character.
Now suppose you want to remove a user named thisuser from a group named thatgroup . Start by backing up /etc/group , then use the editor of your preference with su privileges to edit the file /etc/group and remove the thisuser reference from the thatgroup line entry, e.g.,
original line is something like this:
thatgroup:x:1274:someuser,thisuser,anotheruser
after editing should be left like this:
thatgroup:x:1274:someuser,anotheruser
As with all the other answers, this will not affect the user’s current session(s), if any (i.e., if the user is currently logged in). The change will take effect the next time the user logs in.
How to Remove a User from a Group Linux
This tutorial explains how to remove a user from a group in Linux. After reading this, you’ll know how to delete users from groups easily using both gpasswd and deluser commands.
What are groups in Linux?
In Linux, users are associated with groups defining their permissions and accesses. To understand what groups are in Linux, it is important to note that there are 3 ways to grant or restrict permissions and accesses: individually, collectively, and “by elimination”.
When a user is granted permissions individually, these permissions are associated with the user ID. To grant permissions collectively, the system administrator creates a group with certain rights, and the member users of that group acquire the group permissions. Removing a user from a group will remove all permission the user inherited from that group.
As said previously, permissions can be granted or restricted to specific users individually and collectively through groups. But the system also needs a policy for all others who are not associated users or groups. Thus when granting or removing permissions in Linux, we must specify 3 categories:
- User: Individual permissions.
- Group: Collective permissions.
- Others (also known as “World” ): Permission for undefined requesters.
In Linux, every user is associated with a group generated in the user’s account creation process.
You can check the groups a user belongs to by executing the groups command followed by the username, as shown in the screenshot below.
As you can see, the linuxhint user is a member of multiple groups, which will be explained later.
How to remove a user from a group in Linux using gpasswd:
To remove the user from one of those groups, you can invoke the gpasswd command with the –delete flag followed by the user to be removed and the group.
In the example below, the linuxhint user is removed from the group floppy.
As you can see, linuxhint isn’t part of the floppy group anymore.
How to remove a user from a group in Debian or Ubuntu with deluser:
On Debian-based Linux distributions, you can remove a user from a group using the deluser command followed by the user to be removed and the group. In the example below, the linuxhint user is removed from the group floppy.
Removing a user from a group in Linux by editing the /etc/group file:
Another way to remove a user from a group in Linux is to edit the /etc/group file. Open the /etc/group configuration file using a text editor, as shown in the example below (nano).
Find the group floppy; you can use the key combination CTRL+W to search “floppy” or the group you want a user to be removed from.
You’ll see the users belonging to the group, in my case, the linuxhint user. To remove the user from the group, remove the user from the group line.
In my case, I change the line of the floppy group from this:
Press CTRL+X to save changes and exit.
You can use the gpasswd to add users to groups too. Just replace the –delete flag with the –add a flag, as shown in the example below, in which the linuxhint user is added to the floppy group.
As you can see, the user linuxhint as added to group floppy.
You can also add users to groups using the usermod command with the -aG argument followed by the group and the user to be removed, as shown in the example below. The linuxhint user is removed from the floppy group.
Both ways explained above to add users to groups are correct.
Conclusion:
Learning how to manage a group is a basic requirement to deal with permissions. Groups is a Unix feature later adopted even by competitors like Microsoft Windows.
Users need to know how to restrict users’ access to certain groups, especially in operating systems in which initial users are granted privileges by default.
The gpasswd and /etc/group methods are convenient to keep in mind for being universal, while deluser remains a good option for users limited to Debian-based Linux distributions.
If you found this tutorial interesting, you may be interested in reading Setuid, setgid, and sticky bit explained.I hope this tutorial explaining how to remove a user from a group in Linux was useful. Keep following Linux Hint for more Linux tips and tutorials.
About the author
David Adams
David Adams is a System Admin and writer that is focused on open source technologies, security software, and computer systems.