- How to Switch Users in Linux
- Command Syntax for su
- su Command Options
- Examples of su Commands
- Changing to an Another User
- As a Different User, Execute a Specific Command
- Switching to a Different Shell Environment
- In the Same Environment, Use a Different User
- su vs. sudo Command Comparison
- su Command
- Sudo Command
- Conclusion
- How to Switch Users in Ubuntu and Other Linux Distributions [Quick Beginner Tip]
- Change user in Linux command line
- Change users in Linux graphically (for desktop Linux)
- How to Change Users in Linux Command Line
- Various user types in Linux
- 1. System Users
- 2. Regular Users
- 3. Super Users
- Switch users in the command line
- Switch to root user
- Смена пользователя в Linux
- Меняем пользователя в Linux
- Способ 1: Список профилей при входе в систему
- Способ 2: Кнопка «Сменить пользователя» в окружении
- Способ 3: Команда в «Терминале»
- Способ 4: Функция «Автоматический вход»
How to Switch Users in Linux
How do I switch a user in Linux? What is the su command? How does it differ from sudo? If you ever had these questions then you are in the right place.
List of content you will read in this article:
Su (switch user) is a Linux command that lets you run a command as a separate user. In the latest logged-in session, this is the simplest way to migrate to the administrative account. Any Linux distributions, such as Ubuntu, disable the root user account by default, rendering the code safer. However, the user would be unable to execute complex instructions as a result of this restriction. You can get around this limitation by briefly acting as a root user with su. If you want to learn more about the su and sudo command, then read this article completely. In this article, we will consider everything about the sudo command and ways to use it in Linux.
Command Syntax for su
To use the su command, type the following into the command prompt:
su [options] [username [arguments]]
su defaults to the superuser if no username is specified (root). Locate the required user and include it in the su command syntax.
su Command Options
Use -h to see a list of commands options in su:
You can use the su command with the following options:
- Username – Change your username with the username you’d like to use to log in. Any consumer, not just root, can do this.
- –command or –c [cmd] – Executes a command as the user-defined.
- –login or –l [username] – Changes the username by running a login script. For that person, you are required to enter a password.
- –s or –shell [shell] – Allows you to execute the command in a separate shell context.
- –h or –help – Displays the su command’s help file.
- –p or ––preserve-environment – Protect the shell environment (HOME, SHELL, USER, LOGNAME).
Examples of su Commands
Changing to an Another User
Enter the following to change the logged-in user in this terminal window:
su –l [other_user_name]
A password would be needed. When you type it in, the username will be changed to that account.
As a Different User, Execute a Specific Command
Using the –c alternative to execute a particular command as a separate user:
su –c [command] [other_user_name]
The system would then prompt you for your user name. When you execute this command, the system will run the ls (list the directory contents) command for the defined account.
Switching to a Different Shell Environment
Enter the following to use a new shell or operating environment:
In Z shell, this command creates a root user account.
In the Same Environment, Use a Different User
With the –p alternative, you can hold the current user account’s environment:
su –p [other_user_name]
[another user] can be replaced with the real username you choose to use. The user account will change, but your home directory will remain the same. If you need to execute a command as a new user but need access to the current user’s files, this is helpful.
Use the echo $HOME command to show the directory you’re operating in to ensure you’re still in the same home environment.
su vs. sudo Command Comparison
su Command
Su allows you to change the existing user to some other user. Use the –l [username] method to define a user account if you need to execute a command as someone other than root. Switching between shell interpreters on one go is also possible using the su command. Su is a more powerful but older command. It can mimic sudo’s features by passing a single command to the shell with the –c option.
Sudo Command
The sudo command provides temporary or one-time privilege access to the root. The sudo command is typically used to easily run an administrative command before returning to the user account’s normal permissions. The consumer must be connected to the sudo community to gain sudo access.
Conclusion
You now know how to use the su command in Linux to shift users and run commands briefly. Also, su and sudo have their differences. Follow the guide and start using su command as per your requirement. We hope that the above information will help you use the su commands while using the Linux terminal in your system.
Источник
How to Switch Users in Ubuntu and Other Linux Distributions [Quick Beginner Tip]
Last updated October 29, 2020 By Abhishek Prakash 12 Comments
It is really simple to switch users in Ubuntu or any other Linux distribution using the terminal.
All you need to do is to know the unsername and its account password and you can switch users with su command:
You’ll be asked to enter the password of the user you want to switch to.
As you can see in the screenshot above, I changed to user prakash from user abhishek in the terminal.
There are some minor details with this method that I’ll share with you in a moment. I’ll also share the graphical way of switching users in Linux if you are using desktop Linux.
Switching to root user
If you want to switch to the root user in Ubuntu, you can use the following command:
sudo su
You’ll have to enter your own user password here.
Change user in Linux command line
Let’s see things a bit in detail. To switch users, you need to first know the exact username because tab competition doesn’t work here. You can list all the users in Linux command line by viewing the content of the /etc/passwd file.
You’ll also need to know the password of the user account you want to switch to. This is for security reason, of course.
If you are the admin user or have sudo access, you can change account password with passwd command.
You’ll notice that some people use a — between su and the username. There is a specific reason for that.
When you use -, -l or –login option, you start the shell as a login shell. This means that it will initialize the environment variables like PATH and changes to the home directory of the changed user. It will be as if you logged into the terminal as the second user.
Note: though — is more popular, it is advised to use –login option.
Change users in Linux graphically (for desktop Linux)
If you are using desktop Linux, the above method may not be sufficient for you. Why? Because you switch the user in the terminal only. It is confined to the terminal. Nothing is changed outside the terminal.
If you want to switch users so that you can log in as another user and use all the system (browser, applications etc) graphically, you’ll have to log out and then log back in.
Now the screenshots may look different but the steps remain the same. Here’s how to switch users in Ubuntu Linux.
Go to the top right corner and click the Power Off/Log out option to open the dropdown and you can choose either of Switch User or Log Out.
- Switch User: You get to keep your session active (applications keep on running) for current user. Good for temporarily switching users as you won’t lose your work.
- Log out: Current session ends (all applications are closed). Good when you want to switch to the other user for a long time.
You can choose whichever option is more suited for your need.
Now, you’ll be at the login screen with all the available users for your system. Choose the user account of your choice.
Clearly, you need to know the password of the user account you want to use.
That’s it. I hope you find this quick beginner tip helpful in changing users in Ubuntu and other Linux distributions. Questions and suggestions are always welcome.
Like what you read? Please share it with others.
Источник
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:
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
Иногда компьютерами под управлением операционных систем Linux пользуются несколько юзеров по очереди, например, дома. В таких случаях не всегда удобно иметь одну учетную запись на всех человек, поскольку каждый желает задать определенную конфигурацию ОС и получить хотя бы минимальную конфиденциальность. Именно поэтому разработчики добавляют возможность создавать неограниченное количество защищенных профилей, чтобы в любой момент переключиться к какому-либо из них. На нашем сайте уже имеется статья, в которой детально описано два способа создания юзеров, поэтому сегодня мы опустим этот процесс и сразу перейдем к теме способов переключения между профилями.
Меняем пользователя в Linux
Далее вы узнаете о четырех доступных вариантах смены учетной записи в Linux на примере дистрибутива Ubuntu. Проще всего это сделать через графическую оболочку или сразу же при начале нового сеанса. Однако существуют и другие условия, о которых мы тоже поговорим в рамках данного материала. Дополнительно вам может понадобиться просмотреть список всех профилей, чтобы знать, какие у них установлены пароли и имена. Для этого мы предлагаем ознакомиться со следующей статьей по ссылке ниже, а мы переходим к первому варианту.
Способ 1: Список профилей при входе в систему
По умолчанию абсолютно во всех существующих дистрибутивах Линукс функция автоматического входа отключена, поэтому при создании нового сеанса требуется выбрать пользователя для входа, а уже потом появится строка для ввода пароля. На этом этапе вы можете указать, к какой именно учетной записи хотите подключиться.
- Включите компьютер, чтобы создать новый сеанс. При отображении списка кликните левой кнопкой мыши по соответствующей строке с подходящим именем.
Если вы обнаружили, что профиль отсутствует в списке, потребуется перейти к отдельному меню.
Здесь сначала указывается имя, поэтому вам необходимо точно знать его, а далее вводится пароль. Если вся информация указана правильно, создастся новая виртуальная консоль с графической оболочкой.
Как видите, этот метод максимально прост, что позволит даже самому начинающему юзеру выполнить его без каких-либо трудностей. Однако если вы уже создали сеанс и не желаете перезагружать ПК для смены профиля, обратите внимание на следующий способ.
Способ 2: Кнопка «Сменить пользователя» в окружении
Еще раз уточним, что мы рассматриваем выполняемую процедуру на примере Ubuntu и установленной по умолчанию в ней графической оболочке. Если же вы обнаружили какие-либо различия, изучая скриншоты, вам предстоит самостоятельно отыскать необходимую кнопку. Это не составит труда, если вы хотя бы немного ориентируетесь в графическом интерфейсе. В противном случае можно обратиться к официальной документации дистрибутива и его оболочки. Смена учетной записи через окружение рабочего стола происходит так:
- Нажмите на кнопку выключения, которая находится на панели задач. Она может быть расположена вверху или снизу, что зависит от общих настроек.
В появившемся контекстном меню кликните по имени своего профиля и в списке выберите «Сменить пользователя».
Появится та же самая форма, что вы видели в инструкции к предыдущему методу. Здесь кликните ЛКМ по нужной учетной записи.
Введите пароль и нажмите на «Разблокировать».
Теперь вы можете с легкостью проверить, произошла ли смена пользователя. Это осуществляется через ту же кнопку на панели задач, о которой мы говорили в первом шаге или путем запуска «Терминала». Там вы увидите, от какого имени была открыта консоль.
Способ 3: Команда в «Терминале»
Отметим, что этот вариант подойдет только в том случае, если вы не хотите менять юзера для всей сессии, а желаете выполнить какие-либо команды от его имени через консоль, а потом снова вернуться к управлению через исходный профиль. В любом дистрибутиве существует единая команда, позволяющая осуществить задуманное.
- Откройте «Терминал» любым удобным способом, например, через главное меню.
Введите команду su — username , где username — точное имя необходимой учетной записи.
Для разблокирования управления введите пароль. Учтите, что отображаться в консоли он не будет, но символы при этом корректно вводятся.
Теперь обратите внимание на зеленую надпись. Как видите, пользователь был успешно сменен.
При закрытии консоли появится всплывающее окно, что здесь запущен какой-то процесс. Этот процесс как раз и является сменой пользователя. Подтвердите закрытие, чтобы завершить консольную сессию учетной записи.
Как видите, для осуществления данного способа потребуется знать точное имя пользователя, а не только его пароль. Однако это единственный доступный вариант, позволяющий выполнять команды в пределах одной консоли от имени другого юзера.
Способ 4: Функция «Автоматический вход»
Иногда во время установки или уже после нее юзер создает учетную запись без пароля и активирует функцию «Автоматический вход». В такой ситуации авторизация происходит самостоятельно, поэтому у других юзеров нет возможности сменить профиль при включении компьютера. Исправить это положение или назначить другой профиль для автоматического входа помогут параметры, реализованные через графическую оболочку.
- Откройте меню приложений и перейдите в «Параметры».
Здесь вас интересует категория «Сведения о системе».
Разверните категорию «Пользователи» и кликните по кнопке «Разблокировать».
Потребуется ввести пароль суперпользователя, чтобы получить возможность управлять другими учетными записями.
После этого переключитесь на необходимый профиль, активируйте или деактивируйте функцию «Автоматический вход» путем перемещения ползунка.
Выше вы узнали о четырех доступных вариантах смены пользователя, последний из которых предполагает включение опции автоматического входа, что позволит упростить процедуру переключения в тех ситуациях, когда она производится довольно редко. Вам осталось только выбрать подходящий способ и следовать инструкциям, чтобы без проблем справиться с поставленной задачей.
Помимо этой статьи, на сайте еще 12315 инструкций.
Добавьте сайт Lumpics.ru в закладки (CTRL+D) и мы точно еще пригодимся вам.
Отблагодарите автора, поделитесь статьей в социальных сетях.
Источник