Linux terminal сменить пользователя

How to switch between users on one terminal?

I’d like to log in as a different user without logging out of the current one (on the same terminal). How do I do that?

I asked a similar question, because I ran into issues with XDG environment variables ( $XDG_RUNTIME_DIR in particular) that were driving me nuts. -> unix.stackexchange.com/questions/354826/…

10 Answers 10

How about using the su command?

$ whoami user1 $ su - user2 Password: $ whoami user2 $ exit logout 

If you want to log in as root, there’s no need to specify username:

$ whoami user1 $ su - Password: $ whoami root $ exit logout 

Generally, you can use sudo to launch a new shell as the user you want; the -u flag lets you specify the username you want:

$ whoami user1 $ sudo -u user2 zsh $ whoami user2 

There are more circuitous ways if you don’t have sudo access, like ssh username@localhost, but sudo is probably simplest, provided that it’s installed and you have permission to use it.

I am getting this error «-su: /dev/stderr: Permission denied» after executing this command echo >>/dev/stderr on a login with su —login . , any tip? I found this btw unix.stackexchange.com/questions/38538/…

Does this allow each new user to have different, overriding values for environment variables? e.g. git config for work, open source, etc.

One finding, when I listed the env it saw that everything was in order as well as a visual inspection can go; And one thing was incorrect: XAUTHORITY=/home/user1/.Xauthority’. Not sure _why_? So X-window doesn’t work by default because the protection on ~/.Xauthority` file is: -rw——- . I made a copy and that let me run gedit as an experiment.

Generally you use sudo to launch a new shell as the user you want; the -u flag lets you specify the username you want:

[mrozekma@etudes-1 ~] % whoami mrozekma [mrozekma@etudes-1 ~] % sudo -u nobody zsh [nobody@etudes-1 ~] % whoami nobody 

There are more circuitous ways if you don’t have sudo access, like ssh username@localhost , but I think sudo is probably simplest if it’s installed and you have permission to use it

sudo -s gives you a shell like su , sudo -i simulates login like su — . Can be combined with -u $user , of course.

much more efficient. being able to «login» as a user who can’t normally login is a great asset. totally allowed me to run a database instance without messing with permissions or selinux

This command prints the current user. To change users, we will have to use this command (followed by the user’s password):

After entering the correct password, you will be logged in as the specified user (which you can check by rerunning whoami .

If you’re running Ubuntu, and if the user you want to login as doesn’t have a password set:

Enter your own password and you should be set. Of course, this requires that your user has rights to gain root privileges with sudo .

Читайте также:  Arch linux grub customizer

To switch the terminal session to a different user, where that user can’t exit back into the original user, use exec:

This will technically login the new user in a new term process, and close out the current one. That way when the user attempts exit or Ctrl-D, the terminal will close as though that user was the one who instantiated it, i.e., the user can’t exit back into the original user’s term. Kind of pointless, considering they can still just start a new terminal session and automatically be in the original user term login, but there it is.

EDIT: For what it’s worth, you can use linux vlock command in your ~/.bashrc to lock terminal sessions by default, requiring the password of the term session user to unlock. This would somewhat prevent the aforementioned term restart under the original user context, given the term isn’t instantiated using the non-default ~/.bashrc of the user, as configured.

Источник

How to Change Users in Linux Command Line

Linux systems have different users and different types of users. Learn how to switch the users in Linux command line or how to change to the root user in Linux.

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:

[email protected]:~$ su - janedoe Password: [email protected]:~$ 

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.

Change to root user in Linux

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

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!

Источник

Как переключать пользователей в Ubuntu и других дистрибутивах Linux [Быстрый совет для новичков]

Переключить пользователей в Ubuntu или любой другой дистрибутив Linux, использующий терминал.

Все, что вам нужно сделать, это знать имя пользователя и пароль учетной записи, и вы можете переключать пользователей с помощью команды su:

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

Как вы можете видеть на скриншоте выше, я перешел на пользователя Пракаш от пользователя Абхишек в терминале.

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

Переход на пользователя root

Если вы хотите переключиться на пользователь root в Ubuntu, вы можете использовать следующую команду:
Sudo су
Здесь вам нужно будет ввести свой собственный пароль пользователя.

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

Давайте разберемся немного подробнее. Чтобы переключить пользователей, вам нужно сначала узнать точное имя пользователя, потому что конкуренция за вкладки здесь не работает. Ты можешь перечислить всех пользователей в командной строке Linux просмотрев содержимое файла / etc / passwd.

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

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

Вы заметите, что некоторые люди используют — между su и именем пользователя. На то есть конкретная причина.

При использовании параметра -, -l или –login оболочка запускается как оболочка входа. Это означает, что он инициализирует переменные среды, такие как PATH, и изменяет домашний каталог измененного пользователя. Будет так, как если бы вы вошли в терминал как второй пользователь.

Читайте также:  Файлы блочных устройств linux

Примечание: хотя — является более популярным, рекомендуется использовать параметр –login.

Графическое изменение пользователей в Linux (для настольных компьютеров Linux)

Если вы используете настольную ОС Linux, описанного выше метода может быть недостаточно. Зачем? Потому что вы переключаете пользователя только в терминале. Он ограничен терминалом. За пределами терминала ничего не меняется.

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

Теперь скриншоты могут выглядеть иначе, но шаги остаются прежними. Вот как переключать пользователей в Ubuntu Linux.

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

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

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

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

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

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

Похожие посты:

Источник

Как сменить пользователя Ubuntu

Операционная система Ubuntu рассчитана на то, чтобы её использовали от имени одного определенного пользователя. Менять пользователя в процессе работы приходится не так уж часто. Обычно вы вводите логин и пароль при входе в систему, а затем пользуетесь ею пока не придёт пора выключать компьютер.

Если надо выполнить какие-либо действия с административными привилегиями, то для этого есть sudo. Однако иногда надо сменить пользователя Ubuntu. В этой статье мы поговорим о том как сделать это в графическом интерфейсе и в терминале.

Как сменить пользователя в Ubuntu

Сначала кликните по значку выключения в правом верхнем углу экрана и выберите там пункт Завершить сеанс или Сменить пользователя:

Затем подтвердите завершение сеанса или смену:

Далее перед вами откроется обычное окно входа, где вы сможете выбрать пользователя из списка или ввести его логин в поле ввода. Затем вы снова окажетесь на рабочем столе Ubuntu.

Теперь давайте поговорим как выполняется смена пользователя в терминале. Для этого надо использовать команду su. Например, чтобы сменить пользователя на losst достаточно выполнить:

Утилита запросит пароль пользователя losst после чего откроет командную строку от его имени:

Если вы хотите, чтобы путь к домашней папке и все другие переменные окружения для пользователя обновились используйте опцию -l или —login. Вместо неё также можно просто добавить чёрточку «-«. Например:

Если выполнить утилиту без параметров, то вы войдете от имени пользователя root. Но поскольку пароль root не задан по умолчанию, то следует добавить перед ней sudo:

В таком случае иногда целесообразнее использовать опцию -i команды sudo:

В этой статье мы рассмотрели как поменять пользователя в Ubuntu, как видите, здесь всё очень просто. Если остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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