Как видите, по умолчанию домашний каталог пользователя будет создан в /home и будет использоваться оболочка /bin/sh. Теперь создадим минимального пользователя с минимальными настройками:
Был создан самый простой пользователь, без оболочки и пароля, а также без групп. Теперь немного усложним задачу и создадим пользователя с паролем и оболочкой /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 еще проще. Рассмотрим окружение Gnome, хотя и в KDE тоже есть аналогичная функция. Войдите в главное меню и откройте параметры системы:
Затем откройте «Пользователи»:
Поскольку утилита запущена от имени обычного пользователя вы ничего не можете сделать. Поэтому нажмите кнопку «Разблокировать»:
Только после этого используйте кнопку со знаком плюс для создания нового пользователя Linux:
В открывшемся окне нужно заполнить все поля. Но тут намного больше ограничений, чем в методе через терминал. Вы не можете задать слишком простой пароль, а также нельзя настроить группы. Можно только указать будет ли пользователь включен в группу wheel с помощью выбора типа пользователя — администратор или обычный:
После этого создание пользователя linux завершено, новый пользователь появится в списке.
В этой статье мы рассмотрели как создать пользователя linux с помощью терминала или в графическом интерфейсе системы. Оба способа имеют свои преимущества. Например, способ в терминале намного гибче, но в то же время графический способ дает больше контроля над процессом. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
You can use the below command line combination:
useradd USERNAME && echo PASSWORD | passwd USERNAME --stdin
Note the –stdin at the end, which will request passwd command to accept the password from standard input.
[[email protected] ~]# useradd testuser && echo testuser-password | passwd testuser --stdin Changing password for user testuser. passwd: all authentication tokens updated successfully.
[[email protected] ~]# user=newuser [[email protected] ~]# pass=newpassword [[email protected] ~]# useradd $user && echo $pass | passwd $user --stdin Changing password for user newuser. passwd: all authentication tokens updated successfully.
Let us look into the last two lines of /etc/passwd to verify it.
[[email protected] ~]# tail -2 /etc/passwd testuser:x:1003:1004::/home/testuser:/bin/bash newuser:x:1004:1005::/home/newuser:/bin/bash
[[email protected] ~]# userdel -r testuser [[email protected] ~]# userdel -r newuser
Another practical usage for this is creating a user with a pre-defined password in the docker file.
# # 2 ENV variables or variables used in this Dockerfile # $ - This is the username # $ - This is the password for $ # useradd $ && echo $ | passwd $ --stdin
This experiment explains the steps for quickly creating a Linux user with a password in one line. This works in standard Unix/Linux/Debian/Cloud/Docker image/container Linux environments.
Linux requires knowledge about terminal and commands and unlike Windows 10 you can do everything with a bunch of keystrokes. Adding users in Linux is rather simple but command based. In this article, we will see how to create user with password on Linux and one line commands to add a user with password’.
When we talk about Linux, the first thing to consider is Ubuntu, which is a fairly popular operating system. Apart from this, many operating systems are based on Ubuntu since there are segments of people who don’t like the way Ubuntu works and looks. Some operating systems are such that are made for very specific users such as Elementary OS.
Whatever new user account you create, a new folder creates under /Home/username.
For this, you will have to open the terminal. You can open the terminal by going to the Task Bar — you will find the terminal app in applications list. There are some shortcuts that you can use to open the terminal window.
When the terminal window opens, you have to type the comment given below following by a username.
useradd [username] replace username with something more human.
The new user account has to be secured, so it’ll be locked which require you to set a new password.
passwd [password] This command will set given password for the user you created.
Example, I would like to have a new user account with the name “Devendra” and “qf007” password.
# useradd Devendra
# passwd qf007
Load more options you can choose by typing the command.
Linux users are demanding, many would ask for one line command to add username with password and fortunately, there is a way to do this.
In Linux, useradd is used to configure everything including username and password. For security reasons, the password should in encrypted, and you can use openssl for making md5 passwords, this helps to specify the password if it’s in plain text.
useradd -u ABCDE -g users -d /home/username -s /bin/bash -p $(echo mypasswd | openssl passwd -1 -stdin) username
-u userid
-d groupname
-d user home directory
-s default shell
-p password
Openssl passwd will generate hash of mypasswd to be used as secure password.
To exclude this from history, unite a space before the command to prevent is from history. If you have to do the corresponding on lots of machines, generate the password once and type in the command.
useradd -u 12345 -g users -d /home/username -s /bin/bash -p '$1$NNfXfoym$Eos.OG6sFMGE8U6ImwBqT1' username
adduser --uid 3434 --password my_password my_login
Pretty much everything was given in this article to create a user with password in Linux, even with a single line code-that’s something. If you like Linux, hop on and subscribe to our channel. Do you have more Linux tips, why not comment down them, below.
Since you are here…
I’ve got a small favor to ask. This is an independent site, and producing content takes a lot of hard work and time. Although many people are reading Quickfever, many use adblocker.. And unlike many other sites, there is no paywall blocking. So you can see why your help is needed. If everyone who finds this website useful and helps to support it, the future would be much more secure. Thank you.
If you use adblocker, please disable it for this site.
$0 raised so far by 0 people.
Adblock