- Setting up a new user
- Contents
- Overview
- Creating a new user
- Options
- adduser
- addgroup
- Legacy
- Common permission groups
- Old newbie notes
- User creation and defaults
- User management and system access
- Как создать пользователя Linux
- Создание пользователя в Linux
- Команда useradd
- Создание нового пользователя linux в GUI
- Выводы
- Add, Delete And Grant Sudo Privileges To Users In Alpine Linux
- Add, Delete And Grant Sudo Privileges To Users In Alpine Linux
- 1. Create a sudo user in Alpine Linux
- 1.1. Grant sudo privileges to users in Alpine Linux
- 1.2. Check if an user has sudo access in Alpine Linux
- 2. Delete sudo privileges from an user in Alpine Linux
Setting up a new user
The root account should be used only for local administrative purposes that require elevated access permissions.
This page shows how to create non-privileged user accounts. i.e. those used for daily work, including desktop use and remote logins.
Contents
Overview
Creating user accounts provides users with their own $HOME directory and allows you (the root user) to limit the access those user accounts have to the operating system configuration files.
Using them increases security, because they limit possible actions and thus possible damage (even from accidental errors).
Creating a new user
- Either the /home filesystem needs to be mounted from a writable partition, or
- the /home directories have to be added to the lbu backup, and a new local backup needs to be committed after creating the user:
# lbu include /home # lbu commit
(Not recommended, as reverting to an older .apkovl will also revert the files in /home).
Regular user accounts can be created with:
By default, adduser will:
- prompt you to set a password for the new user
- create a home directory in /home/
- set the shell to the one used by the root account (ash by default)
- assign user ID and group ID starting at 1000
- set the GECOS (full name) field to «Linux User. «
This can be very useful to specify. Setting this string — at least equal to the username — makes the user distinguishable, e.g. when they are listed at the login screen of a display manager.
Only if elogind is not being used and running, then X users would need to be added to the video and input groups to be able to work with a graphical display.
If a user really must be allowed to have access to the root account, the can be added to the wheel group, doas («do as») may be installed, and the group «wheel» can be allowed to become root:
- Many desktop environments and file browsers support using admin:/// in their address bars, to access files through a local gvfs-admin mount
- doasedit or sudoedit enables starting an editor with a temporary copy of a file, which overwrites the original file after the user modifies and saves it. For example, sudoedit /etc/apk/lbu.conf
The sudo package is an alternative to using the BSD-like doas , but is a much larger package. It may be used as follows: adding a custom user configuration file to avoid having to deal with manually changing configuration files later during package upgrades.
The new user gets listed in
Contents of /etc/passwd
Now you should be able to issue the command exit and login to the new account.
Options
adduser
Usage (from «man busybox»):
If —ingroup isn’t set, (default) the new user is assigned a new GID that matches the UID. If the GID corresponding to a provided UID already exists, adduser will fail.
This ensures new users default to having a «user’s private group» (UPG) as primary group. These allow the system to use a permission umask (002), which creates new files automatically as group-writable, but only by the user’s private group. In special set-group-id (collaboration) directories, new files can be automatically created writable by the directory’s group.
addgroup
Usage (from «man busybox»):
Legacy
Common permission groups
- disk:x:6:root,adm needed only for use vith virtual machines and access to other partitions.
- lp:x:7:lp needed for printing services and printers management.
- wheel:x:10:root Administrator group, members can use sudo to run commands as root if enabled in the sudo configuration.
- floppy:x:11:root Backward compatible group. Use only if access to special external devices is needed.
- audio:x:18: Needed for audio listening and management of sound volume as normal user.
- cdrom:x:19: For access to CD/DVD/BR writers and mounting DVD, BR or CD rom disk as normal user.
- dialout:x:20:root Needed for dialing private connections and use of modems as normal user.
- tape:x:26:root Needed if you’re planning to use special devices for backup. Rare. Ususally used only on servers.
- video:x:27:root For usage of cameras, more than one GPU special features, as normal user.
- netdev:x:28: For network connections management as normal user.
- kvm:x:34:kvm Only if a normal user will manage virtual machines via a GUI. Rare. Ususally used only on servers.
- games:x:35: Needed if you want to play games. Especially if sharing scores between users.
- cdrw:x:80: Needed to write RW-DVD, RW-BR or RW-CD disk on a disk writing device.
- apache:x:81: Needed if you do development as normal user and want to publish locally on web server.
- usb:x:85: Needed to access to special usb devices. Deprecated group.
- users:x:100:games Needed if you plan to use common files for all users. Mandatory for desktop usage.
Old newbie notes
User creation and defaults
The following commands will set up root environment login, then assign a new password:
By default, remote management cannot be done directly with the root account. Because of SSH security we need to set up a remote connection account that will be used to switch to the root user via the su command, once connected.
Here’s an example: create user named «remote» and a user named «general». We will set up a hardened, limited, user environment and create those two users:
Note that those users are created with minimal privilege settings.
User management and system access
By default, a newly created user will not have enough privileges for most desktop purposes.
To add newly created users to groups that may come in handy for desktop useage, you run this command as root:
Источник
Как создать пользователя Linux
Основу управления правами доступа в Linux и уровнем привилегий в Linux составляют именно пользователи. Изначально, еще при проектировании системы существовал пользователь root, которому позволено выполнять любые действия и другие пользователи, права которых настраиваются с помощью вступления их в группы Linux и установки прав на каталоги.
Многопользовательская архитектура, одна из первых особенностей Linux, которая существует еще с зарождения системы. В системе могут работать одновременно множество пользователей благодаря удаленному входу, а также пользователи используются для запуска определенных сервисов. В этой статье мы рассмотрим как создать пользователя linux, рассмотрим способ через терминал и в графическом интерфейсе.
Создание пользователя в Linux
Вся информация о пользователях находится в файле /etc/passwd. Мы могли бы создать пользователя linux просто добавив его туда, но так делать не следует, поскольку для этой задачи существуют специальные утилиты. Одна из таких утилит, это useradd. Рассмотрим ее подробнее.
Команда useradd
Это довольно простая команда, которая есть во всех дистрибутивах Linux. Она позволяет зарегистрировать нового пользователя или изменить информацию об уже имеющемся. Во время создания можно даже создать домашний каталог пользователя и скопировать в него системные файлы. Рассмотрим синтаксис команды:
$ useradd опции имя_пользователя
Все довольно просто, дальше нам нужно рассмотреть основные опции команды, с помощью которых вы будете настраивать нового пользователя:
- -b — базовый каталог для размещения домашнего каталога пользователя, по умолчанию /home;
- -c — комментарий к учетной записи;
- -d — домашний каталог, в котором будут размещаться файлы пользователя;
- -e — дата, когда учетная запись пользователя будет заблокирована, в формате ГГГГ-ММ-ДД;
- -f — заблокировать учетную запись сразу после создания;
- -g — основная группа пользователя;
- -G — список дополнительных групп;
- -k — каталог с шаблонами конфигурационных файлов;
- -l — не сохранять информацию о входах пользователя в lastlog и faillog;
- -m — создавать домашний каталог пользователя, если он не существует;
- -M — не создавать домашнюю папку;
- -N — не создавать группу с именем пользователя;
- -o — разрешить создание пользователя linux с неуникальным идентификатором UID;
- -p — задать пароль пользователя;
- -r — создать системного пользователя, не имеет оболочки входа, без домашней директории и с идентификатором до SYS_UID_MAX;
- -s — командная оболочка для пользователя;
- -u — идентификатор для пользователя;
- -D — отобразить параметры, которые используются по умолчанию для создания пользователя. Если вместе с этой опцией задать еще какой-либо параметр, то его значение по умолчанию будет переопределено.
Теперь, когда вы знаете основные необходимые нам параметры утилиты мы можем перейти к разбору того, как выполняется создание нового пользователя linux. Сначала давайте посмотрим какие параметры будут применены для пользователя по умолчанию:
Как видите, по умолчанию домашний каталог пользователя будет создан в /home и будет использоваться оболочка /bin/sh. Теперь создадим минимального пользователя с минимальными настройками:
sudo useradd test
Был создан самый простой пользователь, без оболочки и пароля, а также без групп. Теперь немного усложним задачу и создадим пользователя с паролем и оболочкой /bin/bash:
sudo useradd -p password -s /bin/bash test1
Для того чтобы получать доступ к системным ресурсам пользователю нужно быть участником групп, у которых есть доступ к этим ресурсам. Дополнительные группы пользователя задаются с помощью параметра -G. Например, разрешим пользователю читать логи, использовать cdrom и пользоваться sudo:
sudo useradd -G adm,cdrom,wheel -p password -s /bin/bash test2
Также, можно установить дату, когда аккаунт пользователя будет отключен автоматически, это может быть полезно для пользователей, которые будут работать временно:
sudo useradd -G adm,cdrom,wheel -p password -s /bin/bash -e 01:01:2018 test2
Некоторых пользователей интересует создание пользователя с правами root linux, это очень просто делается с помощью useradd, если комбинировать правильные опции. Нам всего лишь нужно разрешить создавать пользователя с неуникальным uid, установить идентификатор в 0 и идентификатор основной группы тоже в 0. Команда будет выглядеть вот так:
sudo useradd -o -u 0 -g 0 -s /bin/bash newroot
Пожалуй, это все основные примеры как добавить пользователя linux. Дальше нам осталось взглянуть только на работу в графическом интерфейсе.
Создание нового пользователя linux в GUI
В графическом интерфейсе системы создать нового пользователя linux еще проще. Рассмотрим окружение Gnome, хотя и в KDE тоже есть аналогичная функция. Войдите в главное меню и откройте параметры системы:
Затем откройте «Пользователи»:
Поскольку утилита запущена от имени обычного пользователя вы ничего не можете сделать. Поэтому нажмите кнопку «Разблокировать»:
Только после этого используйте кнопку со знаком плюс для создания нового пользователя Linux:
В открывшемся окне нужно заполнить все поля. Но тут намного больше ограничений, чем в методе через терминал. Вы не можете задать слишком простой пароль, а также нельзя настроить группы. Можно только указать будет ли пользователь включен в группу wheel с помощью выбора типа пользователя — администратор или обычный:
После этого создание пользователя linux завершено, новый пользователь появится в списке.
Выводы
В этой статье мы рассмотрели как создать пользователя linux с помощью терминала или в графическом интерфейсе системы. Оба способа имеют свои преимущества. Например, способ в терминале намного гибче, но в то же время графический способ дает больше контроля над процессом. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
Add, Delete And Grant Sudo Privileges To Users In Alpine Linux
We already have shown you how to create a sudo user, assign sudo permissions to existing users and remove sudo privileges from an user in Arch Linux, CentOS and Ubuntu. Today, we will see how to add, delete and grant sudo privileges to users in Alpine Linux.
For the purpose of this guide, I will be using a minimal Alpine Linux box.
Add, Delete And Grant Sudo Privileges To Users In Alpine Linux
Login as root user or any other existing sudo user. Since it is a fresh and minimal Alpine Linux box, there are no other sudo users in my system, so I logged in as root user.
First of all, make sure the sudo package is installed in your Alpine Linux system. By default, sudo is not installed.
To install sudo in Alpine Linux as root user, run:
Next, let us create a new user in Alpine Linux and grant sudo privileges to the newly created user.
1. Create a sudo user in Alpine Linux
To create a new user in Alpine Linux, we use adduser command as shown below:
Here, I am creating a new user named «ostechnix».
Enter the password twice for the new user and complete the user creation.
We have just created a new normal user. The user doesn’t have any administrative rights yet.
You can verify if an user has sudo privileges or not in Alpine Linux using command:
Replace «ostechnix» in the above example with you own username.
Sample output:
Let us add the new user to sudoers list, so he/she can perform administrative operations.
1.1. Grant sudo privileges to users in Alpine Linux
We can do this in two ways.
Method 1 :
To assign sudo permissions to an user in Alpine Linux, simply add him/her to wheel group. For those who don’t know yet, wheel is a special group in some Unix-like operating systems. All the members of wheel group can perform administrative tasks. Wheel group is similar to sudo group in Debian-based systems.
Run the following command to allow the members of wheel group to perform any command:
Next, add the user «ostechnix» to the wheel group:
Grant sudo privileges to users in Alpine Linux
We added the user ostechnix to sudoers list. Now skip to the «1.2. Check if an user has sudo access in Alpine Linux» section and check if the user has sudo permissions.
Method 2:
The another way to assign sudo permissions to an user is by directly adding him in the /etc/sudoers configuration file.
To give sudo permissions to the user «ostechnix», edit «/etc/sudoers» file:
Add the following line:
Add users in sudoers configuration file in Alpine Linux
Hit ESC key and type :wq to save the file and exit.
Done! The user has been added to the sudoers list. Let su go ahead and check if he is able to run administrative operations.
1.2. Check if an user has sudo access in Alpine Linux
To verify if an user has sudo rights in Alpine Linux, run this command:
Sample output:
Check if user has sudo permission in Alpine Linux
As you can see, the user «ostechnix» can run all commands in my Alpine Linux box.
Let us switch to the new sudo user and verify if he can able to run sudo tasks.
To switch to the new user i.e. ostechnix in our case, run:
Run any sudo operation to verify if the user really has sudo permissions.
Sample output:
Verify if an user has sudo privileges in Alpine Linux
Yes, the user has become part of the administrative users group.
2. Delete sudo privileges from an user in Alpine Linux
To revoke the sudo permissions from an user in Alpine Linux, just remove him/her from the wheel group using gpasswd command. The gpasswd command is not available in Alpine base image. You need to install shadow package in order to get gpasswd command.
To install shadow package in Alpine Linux, run the following command as root user:
Now you can remove the sudo privileges from an user, for example ostechnix, using command:
Sample output:
The user ostechnix has been removed from wheel group. You can verify it using command:
Delete sudo privileges from an user in Alpine Linux
The user ostechnix has now become a regular user. He can’t perform any sudo operations anymore.
If you don’t want that user anymore, remove him entirely from the system using this command:
Here, -r flag is used to delete the $HOME directory of the user.
That’s it. This tutorial taught you how to create a sudo user, and how to assign sudo privileges to existing users and finally how to delete the sudo privileges from an user in Alpine Linux. Hope it helps.
Источник