Linux creating user with password

Содержание
  1. Easily Create User With Password with one line command in Linux
  2. Add a user to Linux the usual way.
  3. Linux add user with password one line
  4. How to create a user account on Ubuntu Linux
  5. Steps to create a user account on Ubuntu Linux
  6. Ubuntu create user account commands
  7. Verification
  8. How do I log in using ssh?
  9. Creating a user account using useradd command on Ubuntu
  10. How to delete a user account
  11. How to change Linux user password
  12. Conclusion
  13. Создание пользователя в Linux. Команды adduser и useradd
  14. В чем отличия adduser и useradd?
  15. Команда adduser
  16. Создание пользователя командой adduser
  17. Команда useradd
  18. Синтаксис команды useradd
  19. Создание нового пользователя
  20. Создание нового пользователя с домашней директорией в /home
  21. Создание нового пользователя с произвольной домашней директорией
  22. Создание нового пользователя с произвольными UID, GID
  23. Создание пользователя с указанием оболочки (shell)
  24. Создать пользователя и добавить его в группы
  25. Заключение
  26. How To Linux Set or Change User Password
  27. Linux Set User Password
  28. Linux change password for other user account
  29. Linux Change Group Password
  30. Changing user passwords on Linux
  31. Forcing Linux user to change password at their next login
  32. Locking and Unlocking user password of the named account
  33. A note about setting up a secure Linux password
  34. Conclusion

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

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.

-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.

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.

Читайте также:  Windows server boot disk
Devendra Meena

Just helping people like you by fixing tech issues, all feedbacks are welcome.

Источник

How to create a user account on Ubuntu Linux

Steps to create a user account on Ubuntu Linux

  1. Open the terminal application
  2. Log in to remote box by running the ssh user@your-ubuntu-box-ip
  3. To add a new user in Ubuntu run sudo adduser userNameHere
  4. Enter password and other needed info to create a user account on Ubuntu server
  5. New username would be added to /etc/passwd file, and encrypted password stored in the /etc/shadow file

Let us see all commands in details and

Ubuntu create user account commands

Let us say you need to add a new user in Ubuntu called vivek, type the following command in your shell:
$ sudo adduser vivek
Type your own password and other info:

Verification

Use the grep command or cat command as follows:
$ cat /etc/passwd
$ grep ‘^vivek’ /etc/passwd
Sample outputs:

How do I log in using ssh?

From your Windows (WSL) or macOS or Linux desktop, run:
$ ssh vivek@your-aws-ubuntu-server-ip
OR
$ ssh -i

/.ssh/aws.pub.key vivek@your-aws-ubuntu-server-ip
Enter the password when prompted.

Creating a user account using useradd command on Ubuntu

Alternatively, you can use the useradd command is a low level utility for adding users on Ubuntu. The syntax is:
$ sudo useradd -s /path/to/shell -d /home/ -m -G
$ sudo passwd
Let us create a new user named vivek using the useradd command on Ubuntu:
$ sudo useradd -s /bin/bash -d /home/vivek/ -m -G sudo vivek
$ sudo passwd vivek
Where,

  • -s /bin/bash – Set /bin/bash as login shell of the new account
  • -d /home/vivek/ – Set /home/vivek/ as home directory of the new Ubuntu account
  • -m – Create the user’s home directory
  • -G sudo – Make sure vivek user can sudo i.e. give admin access to the new account

I strongly recommend installing ssh keys while creating the new user account. You must have RSA/ed25519 key pair on your local desktop/laptop . Use the cat command to view your current RSA/ed25519 public key on the desktop:
$ cat

View public ssh key on your macos/unix/linux desktop

How to delete a user account

Use the userdel command as follows:
sudo userdel
sudo userdel vivek
To remove home directory and mail spool too, enter:
sudo userdel -r
sudo userdel -r jerry

How to change Linux user password

Run the following passwd command:
sudo passwd
sudo passwd tom
To change your own password, enter:
passwd
First, the user is prompted for their current password. If the current password is correctly typed, a new password is requested. The new password must be entered twice to avoid password mismatch errors.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Conclusion

In this quick tutorial, you learned how to add users in Ubuntu Linux using the CLI. The same commands works for any Debian/Ubuntu based distribution too. See useradd man page using the man command or read it online here:
man 8 useradd
man 8 passwd
man 8 adduser

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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

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

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

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

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

Читайте также:  Linux как записать загрузочный образ

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

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

Команда adduser

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

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

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

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

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

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

В данной директории хранятся файлы, которые копируются в домашний каталог всех новых пользователей.

Команда useradd

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

Источник

How To Linux Set or Change User Password

Linux Set User Password

Type following passwd command to change your own password:
$ passwd
Sample Outputs:

The user is first prompted for his/her old password if one is present. This password is then encrypted and compared against the stored password. The user has only one chance to enter the correct password. The super user is permitted to bypass this step so that forgotten passwords may be changed. A new password is tested for complexity. As a general guideline, passwords should consist of 10 to 20 characters including one or more from each of following sets:

  1. Lower case alphabetics
  2. Upper case alphabetics
  3. Digits 0 thru 9
  4. Punctuation marks/spacial characters

Linux change password for other user account

You need to login as the root user, type the following command to change password for user vivek:
# passwd vivek
OR
$ sudo passwd vivek
Sample putput:

  • vivek – is username or account name.

Passwords do not display to the screen when you enter them. For example:

Linux changing user password using passwd

Linux Change Group Password

When the -g option is used, the password for the named group is changed. In this example, change password for group sales:
# passwd -g sales
The current group password is not prompted for. The -r option is used with the -g option to remove the current password from the named group. This allows group access to all members. The -R option is used with the -g option to restrict the named group for all users.

Changing user passwords on Linux

As a Linux system administrator (sysadmin) you can change password for any users on your server. To change a password on behalf of a user:

  1. First sign on or “su” or “sudo” to the “root” account on Linux, run: sudo -i
  2. Then type, passwd tom to change a password for tom user
  3. The system will prompt you to enter a password twice

To change or set a new root (superuser) password type:
$ sudo passwd

Forcing Linux user to change password at their next login

By default, Linux passwords never expire for users. However, we can force users to change their password the next time they log in via GUI or CLI methods. The syntax is straightforward:
$ sudo passwd -e
$ sudo passwd —expire
Let us immediately expire an account’s password:
$ sudo passwd -e marlena
The system will confirm it:

When user try to login via ssh command, they will see the following on screen:

Locking and Unlocking user password of the named account

Note that the following local command does not disable the account. The user may still be able to login using another authentication token, such as an SSH key. To disable the account, administrators should use either usermod —expiredate 1 or sudo passwd —expire command. Also, users with a locked password are not allowed to change their password to get around the security policy set by sysadmin.

We can lock the password as follows:
$ sudo passwd -l
This option disables a password by changing it to a value which matches no possible encrypted value (it adds a ! at the beginning of the password in the /etc/shadow file. Want to unlock the password, try:
$ sudo passwd -u
The above command option re-enables a password by changing the password back to its previous value. In other words, to the value before using the -l option.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

A note about setting up a secure Linux password

Compromises in password security typically result from careless password selection. Avoid common password such as:

  1. Words which appears in a dictionary
  2. Your first and last name
  3. Pet names
  4. Kids or spouses names
  5. License number
  6. Date of birth (DoB)
  7. Home or office address

I strongly recommend that you generate a unique password for all user accounts using your chosen password manager.

Conclusion

The passwd command line utility is used to update or change user’s password. The encrypted password is stored in /etc/shadow file and account information is in /etc/passwd file. To see all user account try grep command or cat command as follows:
$ cat /etc/passwd
$ grep ‘^userNameHere’ /etc/passwd
$ grep ‘^tom’ /etc/passwd
The guidance given in this quick tutorial should work with any Linux distribution, including Alpine, Arch, Ubuntu, Debian, RHEL, Fedora, Oracle CentOS, SUSE/OpenSUSE and other popular Linux distros.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Читайте также:  Стандартный пароль root для linux
Оцените статью