Change users linux terminal

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

Иногда компьютерами под управлением операционных систем Linux пользуются несколько юзеров по очереди, например, дома. В таких случаях не всегда удобно иметь одну учетную запись на всех человек, поскольку каждый желает задать определенную конфигурацию ОС и получить хотя бы минимальную конфиденциальность. Именно поэтому разработчики добавляют возможность создавать неограниченное количество защищенных профилей, чтобы в любой момент переключиться к какому-либо из них. На нашем сайте уже имеется статья, в которой детально описано два способа создания юзеров, поэтому сегодня мы опустим этот процесс и сразу перейдем к теме способов переключения между профилями.

Меняем пользователя в Linux

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

Способ 1: Список профилей при входе в систему

По умолчанию абсолютно во всех существующих дистрибутивах Линукс функция автоматического входа отключена, поэтому при создании нового сеанса требуется выбрать пользователя для входа, а уже потом появится строка для ввода пароля. На этом этапе вы можете указать, к какой именно учетной записи хотите подключиться.

    Включите компьютер, чтобы создать новый сеанс. При отображении списка кликните левой кнопкой мыши по соответствующей строке с подходящим именем.

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

Здесь сначала указывается имя, поэтому вам необходимо точно знать его, а далее вводится пароль. Если вся информация указана правильно, создастся новая виртуальная консоль с графической оболочкой.

Как видите, этот метод максимально прост, что позволит даже самому начинающему юзеру выполнить его без каких-либо трудностей. Однако если вы уже создали сеанс и не желаете перезагружать ПК для смены профиля, обратите внимание на следующий способ.

Способ 2: Кнопка «Сменить пользователя» в окружении

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

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

В появившемся контекстном меню кликните по имени своего профиля и в списке выберите «Сменить пользователя».

Появится та же самая форма, что вы видели в инструкции к предыдущему методу. Здесь кликните ЛКМ по нужной учетной записи.

Введите пароль и нажмите на «Разблокировать».

Теперь вы можете с легкостью проверить, произошла ли смена пользователя. Это осуществляется через ту же кнопку на панели задач, о которой мы говорили в первом шаге или путем запуска «Терминала». Там вы увидите, от какого имени была открыта консоль.

Читайте также:  Долго могут устанавливаться обновления windows

Способ 3: Команда в «Терминале»

Отметим, что этот вариант подойдет только в том случае, если вы не хотите менять юзера для всей сессии, а желаете выполнить какие-либо команды от его имени через консоль, а потом снова вернуться к управлению через исходный профиль. В любом дистрибутиве существует единая команда, позволяющая осуществить задуманное.

    Откройте «Терминал» любым удобным способом, например, через главное меню.

Введите команду su — username , где username — точное имя необходимой учетной записи.

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

Теперь обратите внимание на зеленую надпись. Как видите, пользователь был успешно сменен.

При закрытии консоли появится всплывающее окно, что здесь запущен какой-то процесс. Этот процесс как раз и является сменой пользователя. Подтвердите закрытие, чтобы завершить консольную сессию учетной записи.

Как видите, для осуществления данного способа потребуется знать точное имя пользователя, а не только его пароль. Однако это единственный доступный вариант, позволяющий выполнять команды в пределах одной консоли от имени другого юзера.

Способ 4: Функция «Автоматический вход»

Иногда во время установки или уже после нее юзер создает учетную запись без пароля и активирует функцию «Автоматический вход». В такой ситуации авторизация происходит самостоятельно, поэтому у других юзеров нет возможности сменить профиль при включении компьютера. Исправить это положение или назначить другой профиль для автоматического входа помогут параметры, реализованные через графическую оболочку.

    Откройте меню приложений и перейдите в «Параметры».

Здесь вас интересует категория «Сведения о системе».

Разверните категорию «Пользователи» и кликните по кнопке «Разблокировать».

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

После этого переключитесь на необходимый профиль, активируйте или деактивируйте функцию «Автоматический вход» путем перемещения ползунка.

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

Помимо этой статьи, на сайте еще 12315 инструкций.
Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.

Отблагодарите автора, поделитесь статьей в социальных сетях.

Источник

How to Change Users in Linux Command Line

Linux systems have different types of users with different types or permissions as well.

Not all users can execute all commands and not all users are allowed to switch to other users neither. This all might sound confusing but, I will try to explain these so it can be easy to understand.

For the moment, here’s a quick summary of how to switch users in Linux command line.

To switch users, you need to know the password of that user. You can switch the users with this command:

To switch to root user in Ubuntu, you can use this command:

Various user types in Linux

If you list all users in Linux, you’ll see a lot of users that you didn’t know about. Who are these users? Where did they come from? I could write an entire article in regards of how users work in Linux, however, this is not the idea for this one.

Basically, there are 3 types of users in Linux:

1. System Users

These are the users that are automatically created in Linux systems to be able to run services or applications and are not intended to log in to the system (in fact you can’t log in as any of these users).

2. Regular Users

These are the (human) users who can log in to a system. Each of these users might have or not different permissions or levels in the system which is given by the groups they belong to.

3. Super Users

These are system administrators or users who can perform high-level tasks that can be considered critical or system dangerous.

Switch users in the command line

When using a Linux system you can log in with a user and then simply “switch” to another user through the same command line session. In order to do this, there is a command “su -“, which allows you to switch to become another user:

Читайте также:  Что такое простой том windows

In the above example, you need to know the password of janedoe in order to switch to that user. Which makes sense because if you are going to switch to a user, you need to know the password of that user else it will be a security risk.

Switch to root user

For security reasons, some systems have ‘root’ account blocked for direct login, either locally or remotely, so this means it will not accept someone who tries to log in using ‘root’ even with the correct password.

So, how do you perform actions as the ‘root’ user? That’s what the ‘sudo’ command allows you to.

The sudo command will basically execute anything you want in the system as if the ‘root’ was doing it. You don’t need to know the ‘root’ user’s password, in fact, probably nobody knows it or there is no password assigned to ‘root’. You only need to know your own user’s password and that user must be in the ‘sudoers’ group, which is basically the group of users which can use ‘sudo’ in the system.

Normally, it is a good practice to run the commands with sudo that needs to run with root permission like this:

But if you want to change to root user so that all the subsequent commands will be run as root, you can use:

You’ll use your own password here, not the root account’s password.

As a sudo user yourself, you can create sudo user by adding the user to sudo group.

Conclusion

Linux systems allow you to easily switch users or execute high-level commands with the usage of ‘su‘ and ‘sudo’ commands. And remember: with great sudo power comes great responsibility!

Источник

Linux Change or Rename User Name and UID

Linux Change or Rename User Command Syntax

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Linux terminal
Est. reading time 5 mintues

The syntax is as follows to rename by user name:
usermod -l login-name old-name

  • We use the usermod command in Linux to rename user account. The name of the user will be changed from the old-name to login_name. Nothing else is changed. In particular, the user’s home directory name should probably be changed to reflect the new login name.

The syntax is as follows to rename by a UID (user ID):
usermod -u UID username
Where,

  • The numerical value of the user’s ID (UID) . This value must be unique unless the -o option is used. The value must be non-negative. Values between 0 and 99 are typically reserved for system accounts. Any files which the user owns and which are located in the directory tree rooted at the user’s home directory will have the file user ID changed automatically. Files outside of the user’s home directory must be altered
    manually.

List all users in Linux system

Type the following cat command:
cat /etc/passwd
One can use the grep command to filter out only user names:
grep -w ‘^username’ /etc/passwd
grep -w ‘^jerry’ /etc/passwd
Another option is to use the cut command:
cut -d: -f1 /etc/passwd
Sample outputs:

How to Change or Rename Username and UID in Linux

Let us see how to rename user login. First, make sure user name is not logged into the server and any other process is not running under the same user name. I also recommend that you backup any data or server files before changing user names.

View current user and group membership for user named tom

First get user identity using the id command:
id tom
Next use the grep command to grab login info about user named tom from the /etc/passwd file
grep ‘^tom:’ /etc/passwd
See group info about user named tom using the groups command:
grep ‘tom’ /etc/group
groups tom
Find home directory permissions for user named tom, run the following ls command:
ls -ld /home/tom/
Finally, see all Linux process owned by user and group named tom using the ps command:
ps aux | grep tom
ps -u tom

Fig.01: Getting info about user named ‘tom’ on a Linux based system

Rename and change username from tom to jerry on Linux

Type the usermod command as follows:
# id tom
# usermod -l jerry tom
## Verify ###
# id tom
# id jerry
# ls -ld /home/tom

A note about running process

You may see an error as follows if tom is logged in and running jobs:

You need to kill all Linux process owned by user named tom and forcefully logged them out of the system:

Rename and change primary groupname from tom to jerry

Type the usermod command as follows:
# id tom
# groupmod -n jerry tom
## Verify it ###
# id tom
# ls -ld /home/tom
Sample outputs:

Fig.02: Sample session renaming user on a Linux based server

How to change user home directory from /home/tom/ to /home/jerry

The syntax is as follows:
# usermod -d /home/jerry -m jerry
# id jerry
# ls -ld /home/jerry
Sample outputs:

  • 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

How to change user tom UID from 5001 to 10000

Type the usermod command as follows:
# id tom
# usermod -u 10000 tom
# id tom

Getting help about usermod command

You can pass the —help option to the usermod command. For instance, type the following command at the shell prompt in Linux:
usermod —help

Options Description
-c OR —comment COMMENT new value of the GECOS field
-d OR —home HOME_DIR new home directory for the user account
-e OR —expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE
-f OR —inactive INACTIVE set password inactive after expiration to INACTIVE
-g OR —gid GROUP force use GROUP as new primary group
-G OR —groups GROUPS new list of supplementary GROUPS
-a OR —append append the user to the supplemental GROUPS mentioned by the -G option without removing the user from other groups
-h OR —help display this help message and exit
-l OR —login NEW_LOGIN new value of the login name
-L OR —lock lock the user account
-m OR —move-home move contents of the home directory to the new location (use only with -d)
-o OR —non-unique allow using duplicate (non-unique) UID
-p OR —password PASSWORD use encrypted password for the new password
-R OR —root CHROOT_DIR directory to chroot into
-P OR —prefix PREFIX_DIR prefix directory where are located the /etc/* files
-s OR —shell SHELL new login shell for the user account
-u OR —uid UID new UID for the user account
-U OR —unlock unlock the user account
-v OR —add-subuids FIRST-LAST add range of subordinate uids
-V OR —del-subuids FIRST-LAST remove range of subordinate uids
-w OR —add-subgids FIRST-LAST add range of subordinate gids
-W OR —del-subgids FIRST-LAST remove range of subordinate gids
-Z OR —selinux-user SEUSER new SELinux user mapping for the user account

Conclusion

In this tutorial, you learned how to change or rename username and UID in Linux using the usermod command. Read man pages of usermod(8) and groupmod(8) commands for more information see this page.

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

Источник

Читайте также:  Jungleflasher для windows 10
Оцените статью