Когда я создаю двух пользователей с одинаковыми идентификаторами UID и GUID, но с разными домашними каталогами, мой 17.10 Ubuntu не загружается, почему?

Я хочу иметь возможность входить в систему с разными настройками, но все равно быть тем же «пользователем». Итак, я добавил второго пользователя с тем же идентификатором UID / GUID, но с другим домашним каталогом, а теперь при загрузке Ubuntu система просто зависает. Если я удалю второго пользователя из файлов passwd и shadow, система загрузится просто отлично.

3
задан 2 December 2017 в 09:55

2 ответа

Как правило, плохая идея вручную отредактировать файл /etc/passwd и /etc/shadow. Я рекомендую использовать для этого эти инструменты. Кроме того, хотя пользователь может использовать один и тот же идентификатор GUID с другим пользователем, UID должен быть уникальным для каждого пользователя. Таким образом, загрузка, скорее всего, не удастся либо в Linux, чтобы предотвратить запуск необходимых приложений и / или сбой приложений, ожидающих уникальности идентификаторов UID.

Лучший подход двух пользователей, разделяющих каталог, - это управление группами для этого. См. Документацию об управлении пользователями или просмотр Ask Ubuntu для возможных руководств:

https://help.ubuntu.com/stable/ubuntu-help/user-accounts.html Как управлять пользователями и группами?

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

sudo useradd -U -m -G <additional groups here> <user-name>

Это добавит пользователя в вашу систему, которая будет работать. Объяснение приведенной выше строки из Задайте Ubuntu (крайне укорочен только для самых обычных опций, для полного просмотра обзорной страницы):

ОПЦИИ The options which apply to the useradd command are: -c, --comment COMMENT Any text string. It is generally a short description of the login, and is currently used as the field for the user's full name. -g, --gid GROUP The group name or number of the user's initial login group. The group name must exist. A group number must refer to an already existing group. If not specified, the behavior of useradd will depend on the USERGROUPS_ENAB variable in /etc/login.defs. If this variable is set to yes (or -U/--user-group is specified on the command line), a group will be created for the user, with the same name as her loginname. If the variable is set to no (or -N/--no-user-group is specified on the command line), useradd will set the primary group of the new user to the value specified by the GROUP variable in /etc/default/useradd, or 100 by default. -G, --groups GROUP1[,GROUP2,...[,GROUPN]]] A list of supplementary groups which the user is also a member of. Each group is separated from the next by a comma, with no intervening whitespace. The groups are subject to the same restrictions as the group given with the -g option. The default is for the user to belong only to the initial group. -k, --skel SKEL_DIR The skeleton directory, which contains files and directories to be copied in the user's home directory, when the home directory is created by useradd. This option is only valid if the -m (or --create-home) option is specified. If this option is not set, the skeleton directory is defined by the SKEL variable in /etc/default/useradd or, by default, /etc/skel. If possible, the ACLs and extended attributes are copied. -m, --create-home Create the user's home directory if it does not exist. The files and directories contained in the skeleton directory (which can be defined with the -k option) will be copied to the home directory. By default, if this option is not specified and CREATE_HOME is not enabled, no home directories are created. -M Do no create the user's home directory, even if the system wide setting from /etc/login.defs (CREATE_HOME) is set to yes. -s, --shell SHELL The name of the user's login shell. The default is to leave this field blank, which causes the system to select the default login shell specified by the SHELL variable in /etc/default/useradd, or an empty string by default. -U, --user-group Create a group with the same name as the user, and add the user to this group. The default behavior (if the -g, -N, and -U options are not specified) is defined by the USERGROUPS_ENAB variable in /etc/login.defs.

Таким образом, -U создаст группу пользователей, похожую на имя пользователя, имеющую идентификатор GUID, соответствующий UID пользователей. -m создаст домашний каталог пользователей в /home/<user-name> и -G, чтобы дать дополнительные группы, к которым должен принадлежать этот пользователь. Вы можете добавлять группы позже. Группы Ubuntu добавляются к основному пользователю: adm, cdrom, sudo, dip, plugdev, lpadmin и sambashare. Чтобы добавить группы позже, вы можете использовать следующую команду:

sudo usermod -aG <group-or groups> <user-name>

Наконец, ваш пользователь должен иметь пароль, который вы можете установить с помощью:

sudo passwd <username>

Это завершает создание пользователя

Существует также комбинированная команда, также называемая adduser, которая автоматизирует некоторые из процессов, о которых вы видели выше, поскольку их использование имеет вид man 8 adduser.

2
ответ дан 18 July 2018 в 02:03

Как правило, плохая идея вручную отредактировать файл /etc/passwd и /etc/shadow. Я рекомендую использовать для этого эти инструменты. Кроме того, хотя пользователь может использовать один и тот же идентификатор GUID с другим пользователем, UID должен быть уникальным для каждого пользователя. Таким образом, загрузка, скорее всего, не удастся либо в Linux, чтобы предотвратить запуск необходимых приложений и / или сбой приложений, ожидающих уникальности идентификаторов UID.

Лучший подход двух пользователей, разделяющих каталог, - это управление группами для этого. См. Документацию об управлении пользователями или просмотр Ask Ubuntu для возможных руководств:

https://help.ubuntu.com/stable/ubuntu-help/user-accounts.html Как управлять пользователями и группами?

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

sudo useradd -U -m -G <additional groups here> <user-name>

Это добавит пользователя в вашу систему, которая будет работать. Объяснение приведенной выше строки из Задайте Ubuntu (крайне укорочен только для самых обычных опций, для полного просмотра обзорной страницы):

ОПЦИИ The options which apply to the useradd command are: -c, --comment COMMENT Any text string. It is generally a short description of the login, and is currently used as the field for the user's full name. -g, --gid GROUP The group name or number of the user's initial login group. The group name must exist. A group number must refer to an already existing group. If not specified, the behavior of useradd will depend on the USERGROUPS_ENAB variable in /etc/login.defs. If this variable is set to yes (or -U/--user-group is specified on the command line), a group will be created for the user, with the same name as her loginname. If the variable is set to no (or -N/--no-user-group is specified on the command line), useradd will set the primary group of the new user to the value specified by the GROUP variable in /etc/default/useradd, or 100 by default. -G, --groups GROUP1[,GROUP2,...[,GROUPN]]] A list of supplementary groups which the user is also a member of. Each group is separated from the next by a comma, with no intervening whitespace. The groups are subject to the same restrictions as the group given with the -g option. The default is for the user to belong only to the initial group. -k, --skel SKEL_DIR The skeleton directory, which contains files and directories to be copied in the user's home directory, when the home directory is created by useradd. This option is only valid if the -m (or --create-home) option is specified. If this option is not set, the skeleton directory is defined by the SKEL variable in /etc/default/useradd or, by default, /etc/skel. If possible, the ACLs and extended attributes are copied. -m, --create-home Create the user's home directory if it does not exist. The files and directories contained in the skeleton directory (which can be defined with the -k option) will be copied to the home directory. By default, if this option is not specified and CREATE_HOME is not enabled, no home directories are created. -M Do no create the user's home directory, even if the system wide setting from /etc/login.defs (CREATE_HOME) is set to yes. -s, --shell SHELL The name of the user's login shell. The default is to leave this field blank, which causes the system to select the default login shell specified by the SHELL variable in /etc/default/useradd, or an empty string by default. -U, --user-group Create a group with the same name as the user, and add the user to this group. The default behavior (if the -g, -N, and -U options are not specified) is defined by the USERGROUPS_ENAB variable in /etc/login.defs.

Таким образом, -U создаст группу пользователей, похожую на имя пользователя, имеющую идентификатор GUID, соответствующий UID пользователей. -m создаст домашний каталог пользователей в /home/<user-name> и -G, чтобы дать дополнительные группы, к которым должен принадлежать этот пользователь. Вы можете добавлять группы позже. Группы Ubuntu добавляются к основному пользователю: adm, cdrom, sudo, dip, plugdev, lpadmin и sambashare. Чтобы добавить группы позже, вы можете использовать следующую команду:

sudo usermod -aG <group-or groups> <user-name>

Наконец, ваш пользователь должен иметь пароль, который вы можете установить с помощью:

sudo passwd <username>

Это завершает создание пользователя

Существует также комбинированная команда, также называемая adduser, которая автоматизирует некоторые из процессов, о которых вы видели выше, поскольку их использование имеет вид man 8 adduser.

2
ответ дан 24 July 2018 в 17:30
  • 1
    Я использовал команду adduser для добавления второго пользователя, просто указав опцию -uid 1000 для повторного использования одного и того же uid. Да, я удалил, отредактировав файлы вручную, но это потому, что мне пришлось использовать другую копию ubuntu в системе для редактирования файлов, так как измененная копия не загрузилась. – intel_chris 2 December 2017 в 11:53
  • 2
    Ну, по крайней мере теперь вы знаете, почему. Вы можете прочитать, как работает chroot, это могло бы привести вас к нормальной работе с пользователями :) – Videonauth 2 December 2017 в 11:55
  • 3
    Нет, я не знаю , почему . Я все еще просто знаю, что что-то висит. Я не знаю, что терпит неудачу. Кроме того, я не вижу, как chroot решит мою проблему. У меня все еще не было двух сред, в которых есть все файлы. Насколько я помню chroot, помогает создать ограниченную среду, которая видит только подмножество системы, например, если вы хотите ограничить анонимный ftp. – intel_chris 2 December 2017 в 14:09
  • 4
    Вы могли бы использовать chroot для монтирования в вашу сломанную систему с USB-накопителя и делать свои исправления таким образом с помощью обычных инструментов командной строки. И вы должны окончательно прочитать управление пользователями. Наличие двух имен разных пользователей, имеющих один и тот же UID, всегда является вызовом для проблем, и его следует избегать. – Videonauth 2 December 2017 в 14:16
  • 5
    хорошо, я понимаю, что вы предлагаете с chroot. Я могу сделать это из моего другого убунту. (У меня нет ручки USB). – intel_chris 2 December 2017 в 14:24

Другие вопросы по тегам:

Похожие вопросы: