Linux add user and password

Easily Create User With Password with one line command in Linux

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.

Add a user to Linux the usual way.

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

  • -c comment: Add a comment for user.
  • -e yyyy-mm-dd: Date for the account to be disabled
  • -f days: Set expiration date 0 to disable account with password expiration. -1 for not disable the account.
  • -M: Do not create the home directory
Читайте также:  User account in linux system

Load more options you can choose by typing the command.

Linux add user with password one line

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.

Источник

How to create a new user and set a password in a single command (Linux/CentOS/Docker/Container)

Creating a user with a password in one line

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.

Creating a user with a password with predefined values

  • Predefine usernames and passwords in variables.
  • Do a useradd with the pre-defined variables
[[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.

Verifying whether the user accounts have been created

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

Cleanup – How to delete test user accounts?

[[email protected] ~]# userdel -r testuser [[email protected] ~]# userdel -r newuser

Dockerfile – how to create a user with password on the fly?

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.

Читайте также:  Load file java linux

The latest

Источник

Создание пользователя в Linux. Команды adduser и useradd

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

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

Для создания пользователей из командной строки обычно используют утилиты adduser или useradd. Рассмотрим, использование данных утилит.

В чем отличия adduser и useradd?

useradd — это низкоуровневая утилита для создания пользователей в Linux.

adduser — представляет собой более простое решение для создания пользователей и по факту является надстройкой над useradd, groupadd и usermod.

Утилита adduser доступна не во всех дистрибутивах Linux. Реализация adduser также может отличаться. Если в дистрибутиве присутствует утилита adduser, то для создания пользователей рекомендуется использовать именно ее.

Команда adduser

Создание пользователя командой adduser

Рассмотрим, как создать обычного пользователя командой adduser

Чтобы создать нового пользователя, выполняем команду adduser и указываем имя пользователя (вместо pupkin укажите имя пользователя, которого вы создаете):

После запуска данной команды, вы должны ввести пароль для нового пользователя. Затем будет предложено ввести дополнительную информацию о пользователе: имя, номер комнаты (кабинета), телефоны и комментарий. Вводить эту информацию необязательно. Просто нажимайте Enter , чтобы пропустить ввод данных.

$ sudo adduser pupkin [sudo] пароль для pingvinus: Добавляется пользователь «pupkin» . Добавляется новая группа «pupkin» (1001) . Добавляется новый пользователь «pupkin» (1001) в группу «pupkin» . Создаётся домашний каталог «/home/pupkin» . Копирование файлов из «/etc/skel» . Новый пароль : Повторите ввод нового пароля : passwd: пароль успешно обновлён Изменение информации о пользователе pupkin Введите новое значение или нажмите ENTER для выбора значения по умолчанию Полное имя []: Vasiliy Pupkin Номер комнаты []: 123 Рабочий телефон []: Домашний телефон []: Другое []: Janitor Данная информация корректна? [Y/n] y

Команда adduser в Linux

В результате выполнения команды adduser будут выполнены следующие действия:

  • Создается новый пользователь с именем, которое вы указали при выполнении команды.
  • Создается группа с тем же именем.
  • Создается домашний каталог пользователя в директории /home/имяпользователя
  • В домашний каталог копируются файлы из директории /etc/skel

Команда useradd

Синтаксис команды useradd

Команда useradd принимает в качестве аргумента имя пользователя, а также различные опции.

Синтаксис команды следующий:

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

Чтобы просто создать пользователя используется команда useradd без каких-либо опций. Указывается только имя пользователя.

Данная команда создает нового пользователя с системными параметрами по умолчанию, которые прописаны в файле /etc/default/useradd

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

Создание нового пользователя с домашней директорией в /home

Создадим пользователя и его домашнюю директорию.

Домашняя директория создается по умолчанию в каталоге /home . Имя директории совпадает с именем пользователя.

Создание нового пользователя с произвольной домашней директорией

Чтобы создать пользователя с домашней директорией, расположенной в произвольном месте, используется опция -d , после которой указывается путь до директории. Директорию необходимо создать заранее.

Создаем домашнюю директорию для будущего пользователя:

Копируем файлы и директории, которые по умолчанию создаются в домашней директории пользователя в данной системе. Данные файлы находятся в директории /etc/skel

sudo cp -rT /etc/skel /users/pupkin

Создаем пользователя и указываем домашнюю директорию:

sudo useradd -d /users/pupkin pupkin

Меняем права доступа у домашней директории:

sudo chown -R pupkin:pupkin /users/pupkin

Задаем пароль для пользователя:

Можно просмотреть информацию о пользователе, которая сохранена в файле /etc/passwd

cat /etc/passwd | grep pupkin pupkin:x:1001:1001::/users/pupkin:/bin/sh

Команда useradd. Создание пользователя с произвольной домашней директорией

Создание нового пользователя с произвольными UID, GID

Каждый пользователь в Linux имеет свой числовой идентификатор — UID, а также идентификатор основной группы пользователя — GID.

При создании пользователя можно задать произвольные номера UID и/или GID. При указании номера группы, группа с этим номером должна быть создана заранее.

useradd -u 1234 -g 1222 pupkin

Создание пользователя с указанием оболочки (shell)

По умолчанию новые пользователи создаются с оболочкой /bin/sh Чтобы задать другую оболочку, используется опция -s /путь/до/оболочки

sudo useradd -m -s /bin/bash pupkin

Создать пользователя и добавить его в группы

Обычно пользователи в Linux принадлежат нескольким группам. Чтобы при создании нового пользователя задать группы, к которым он будет принадлежать, используется опция -G список,групп

sudo useradd -m -G adm,cdrom,wheel -s /bin/bash pupkin

Заключение

Мы рассмотрели примеры создания нового пользователя в Linux с использованием команд adduser и useradd . Команда adduser более простая и в большинстве случаев рекомендуется использовать именно ее.

Источник

Оцените статью
Adblock
detector