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 .
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.
Linux login command
On Unix-like operating systems, the login command begins a new login session on the system.
This page covers the Linux version of login.
Description
The login program is used to establish a new session with the system. It is normally invoked automatically by responding to the «login:» prompt on the user’s terminal. login may be special to the shell and may not be invoked as a sub-process. When called from a shell, login should be executed as exec login which causes the user to exit from the current shell (and thus prevents the new logged in user to return to the session of the caller). Attempting to execute login from any shell but the login shell produces an error message.
The user is then prompted for a password, where appropriate. Echoing is disabled to prevent revealing the password. Only a small number of password failures are permitted before login exits and the communications link is severed.
If password aging is enabled for your account, you may be prompted for a new password before proceeding. You will be forced to provide your old password and the new password before continuing; refer to our passwd for more information.
Your user and group ID will be set according to their values in the /etc/passwd file. The value for $HOME, $SHELL, $PATH, $LOGNAME, and $MAIL are set according to the appropriate fields in the password entry. ulimit, umask and nice values may also be set according to entries in the GECOS field.
On some installations, the environment variable $TERM will be initialized to the terminal type on your tty line, as specified in /etc/ttytype.
An initialization script may also be executed; check the documentation of your command interpreter for information on init scripts.
A subsystem login is indicated by the presence of a «*» as the first character of the login shell. The given home directory will be used as the root of a new file system which the user is actually logged into.
Syntax
login [-p] [-h host] [username] [ENV=VAR. ]
login [-p] [-h host] -f username
Options
-f | Do not perform authentication; user is pre-authenticated. In that case, username is mandatory. |
-h | Name of the remote host for this login. |
-p | Preserve environment. |
-r | Perform autologin protocol for rlogin. |
Configuration
The following configuration variables in /etc/login.defs change the behavior of this tool:
By default, the ownership of the terminal is set to the user’s primary group and the permissions are set to 0600.
TTYGROUP can be either the name of a group or a numeric group identifier.
Files
/var/run/utmp | List of current login sessions. |
/var/log/wtmp | List of previous login sessions. |
/etc/passwd | User account information. |
/etc/shadow | Secure user account information. |
/etc/motd | System message of the day file. |
/etc/nologin | Prevent non-root users from logging in. |
/etc/ttytype | List of terminal types. |
$HOME/.hushlogin | Suppress printing of system messages. |
/etc/login.defs | Shadow password suite configuration. |
The -r, -h and -f options are only used when login is invoked by root.
Examples
Attempts to log in to the host computerhope.com.
Related commands
csh — The C shell command interpreter.
exit — Exit the command shell.
init — The parent of all processes on the system.
ksh — The Korn shell command interpreter.
mail — Read, compose, and manage mail.
mailx — Process mail messages.
newgrp — Log into a new group.
passwd — Change a user’s password.
rlogin — Begin a session on a remote system.
rsh — Execute a command on a remote shell.
sh — The Bourne shell command interpreter.
telnet — Connect to a remote system using the telnet protocol.
umask — Get or set the file mode creation mask.
Как сделать автоматический логин в консоль Linux?
Требуется чтобы при загрузке машины линукс (Ubuntu 10) автоматически логинился как рут в консоли. Графической оболочки нет никакой. Расскажите как это делается? В интернете информации минимум и вся устаревшая.
Это нужно сделать для «удобства» ? (Тогда это сильно компромитирует систему) или Это нужно для выполнения определеных задачь? ( Тогда логинится в консоль не обязательно).
@Yaroslav Да, это надо для выполнения конкретных задач. Это плата, на которой при включении автоматически должен выполняться скрипт/подниматься иксы/запускаться ПО. На данный момент это все происходит по логину и прописано в ./bashrc . Осталось залогинится 🙂 Насчет секьюрности можно не переживать сети на ней нету, клавы тоже.
Возможно Вам , нужно корректно настроить систему автоматического запуска ? а не автоматически вводить логин/пароль
@alexanderbarakin, если дистр с системд, то рцлокал не пашет. Надо или его разрешить или сервис писать.
@donRumata, ну, с вашей-то версией убунты всё понятно, а вот в чём именно заключается проблема у автора — неясно.
1 ответ 1
предуведомление:
это ответ непосредственно на вопрос, а автору вопроса, судя по содержанию комментариев, требуется совсем-совсем другое — выяснить, по какой причине у него не выполняется скрипт /etc/rc.local . но это абсолютно другой вопрос.
В интернете информации минимум и вся устаревшая.
это не совсем верно. много лет в популярных дистрибутивах на нескольких первых (как правило — с первого по шестой) виртуальных терминалах обычно запускаются одни и те же программы agetty или mingetty.
и обе они имеют опцию —autologin имя-пользователя (некоторые реализации — -a имя-пользователя ), которая делает именно то, что следует из её названия.
другое дело, что не всегда просто определить, где именно находится файл, в котором описан запуск *getty . чтобы добавить опцию к вызову нужного экземпляра *getty .
- в «старой доброй» sysv-инициализации это, естественно, файл /etc/inittab :
$ grep -v '^#' /etc/inittab | grep getty 1:2345:respawn:/sbin/getty 38400 tty1 2:23:respawn:/sbin/getty 38400 tty2 3:23:respawn:/sbin/getty 38400 tty3 4:23:respawn:/sbin/getty 38400 tty4 5:23:respawn:/sbin/getty 38400 tty5 6:23:respawn:/sbin/getty 38400 tty6
$ grep -v '^#' /etc/init/tty?.conf | grep getty /etc/init/tty1.conf:exec /sbin/getty -8 38400 tty1 /etc/init/tty2.conf:exec /sbin/getty -8 38400 tty2 /etc/init/tty3.conf:exec /sbin/getty -8 38400 tty3 /etc/init/tty4.conf:exec /sbin/getty -8 38400 tty4 /etc/init/tty5.conf:exec /sbin/getty -8 38400 tty5 /etc/init/tty6.conf:exec /sbin/getty -8 38400 tty6