Виртуальная консоль Linux организована на основе текстовых возможностей графического контроллера, в том числе работы через фреймбуфер.
В процессе работы Linux активно несколько виртуальных консолей. Каждая виртуальная консоль доступна по нажатию Alt и функциональной клавиши с номером этой консоли. Так, в ALT Linux после загрузки системы функции системной консоли берёт на себя 12-я виртуальная консоль (Alt-F12). Если запущена графическая подсистема X11, она занимает седьмую консоль, а для переключения в текстовый режим описанные клавиши нужно нажимать вместе с Ctrl: Ctrl-Alt-F1, Ctrl-Alt-F2 и т. д.
В современных ОС графическая подсистема переехала по умолчанию с седьмой (F7) на первую консоль (F1), поэтому для перехода в текстовую консоль, надо нажать одну из комбинаций Ctrl-Alt-F2 . Ctrl-Alt-F6, а для возврата в графику Ctrl-Alt-F1.
Если вы переключитесь в виртуальную консоль, то увидите приглашение на вход вида:
Lada login:
где Lada — имя вашего компьютера.
Как Получит Права Супер Пользователя root | linux ubuntu обзор для начинающих
Вводите имя root и пароль root:
Lada login: root Password:
при вводе пароля ничего не высвечивается — это сделано специально, для безопасности.
Далее, например, вызываем mc (файловый менеджер с текстовым интерфейсом) и работаем в нём, если нет предпочтений вроде zsh.
В Википедии есть обзорная статья по теме «Midnight_Commander».
Для возвращения в графику выходим из mc, заканчиваем сеанс в виртуальном терминале (чтобы зря не висел) командой exit [1] и переходим в графику сочетанием клавиш Alt+F1 (в некоторых раскладках консоли Ctrl+Alt+F1).
Управление доступом к командам перехода в режим суперпользователя
В дистрибутивах ALT для управления доступом к важным службам используется подсистема control. Для получения текущего состояния войдите через login в root и дайте команду control без параметров, например:
# control | grep su su wheelonly (public wheel wheelonly restricted) sudo wheelonly (public wheelonly restricted) sudoers relaxed (strict relaxed)
Для того чтобы посмотреть что значит та или иная политика, дайте команду control имя_службы help , например
# control su help public: Any user can execute /bin/su wheel: Any user can execute /bin/su, but only «wheel» group members can switch to superuser wheelonly: Only «wheel» group members can execute /bin/su restricted: Only root can execute /bin/su
Для задания новой политики можно задать control имя_службы новая_политика , например:
control sudo restricted
что запретит использовать команду sudo всем, кроме root (а самому root уже в настройках sudo по умолчанию запрещено её использовать).
Примечание: Как видно из приведённых выше команд, команды su и sudo по умолчанию позволено использовать только пользователям, входящим в группу wheel.
Краткое сравнение команд su и sudo
1. Режим работы по умолчанию:
Далее все команды до команды exit выполняются в режиме суперпользователя.
sudo команда
Выполняется только одна конкретная команда.
Как зайти под root в Kali Linux 2020.1?
2. Запрашиваемый пароль по умолчанию:
su — — запрашивает пароль root;
sudo — запрашивает пароль пользователя для первой команды, для следующих в течение определённого времени вообще не запрашивает пароль.
3. Каждая команда самостоятельна и настраивается отдельно.
По умолчанию в большинстве дистрибутивов ALT sudo запрещено
Вход через su —
- получение прав через su —
Источник: www.altlinux.org
How to run Terminal as root?
When we want to run a programs as root we use sudo , gksu , gksudo and etc. Now my question is how do we can run a Terminal as the root user in Terminal? I tried with using gksudo terminal and gksu terminal but nothing happens. and by running sudo terminal I get error sudo: terminal: command not found .
116k 54 54 gold badges 315 315 silver badges 489 489 bronze badges
asked Aug 23, 2014 at 19:44
35k 41 41 gold badges 129 129 silver badges 192 192 bronze badges
It is gnome-terminal . So try sudo gnome-terminal .
Aug 23, 2014 at 19:58
Is there really any advantage to running the terminal program itself as root? why not just start an interactive root shell inside the terminal with sudo -i ?
Aug 23, 2014 at 20:05
Aug 23, 2014 at 20:26
yes, you are correct.
Aug 23, 2014 at 20:36
7 Answers 7
The default terminal emulator on Ubuntu is the GNOME Terminal. It’s located at /usr/bin/gnome-terminal and can be run with the gnome-terminal command.
What You Really Want
What you probably want is a shell running as root, as though it were produced from a root login (for example, with all the environment variables set for root rather than for your user).
Assuming that’s what you want, as steeldriver has suggested, just run:
sudo -i
You’ll have a root shell in which commands you enter will be run as root (without having to precede them with sudo ).
But if you really want to run the graphical terminal emulator application as root, read on. I present two ways: with gksu / gksdo , and with the sudo command.
With gksu / gksudo
Since you have the gksu package installed, you can run gnome-terminal as root with either of:
gksu gnome-terminal
gksudo gnome-terminal
(Since gksu is set to sudo-mode in Ubuntu by default, these should be equivalent.)
Running gnome-terminal as root without a controlling non-root terminal:
Virtually every desktop environment provides a facility to run a command without having to open a terminal (which would then, if closed, usually cause the command to be terminated).
This is usually achieved with Alt + F2 . A textbox labeled Run command (or similar) will appear and you can enter your command.
For example, it looks like this in Unity:
And like this in MATE (GNOME Flashback/Fallback, Xfce, LXDE are similar):
Note that this works with gksu and gksudo because they use a graphical authentication dialog. If you were to press Alt + F2 and run sudo . , you would then be unable to interact with the password prompt.
With sudo
If you don’t have the gksu package and you won’t want to install it, you can use:
sudo -H gnome-terminal
The -H flag is important because it sets the HOME environment variable to /root instead of your own user’s home directory. You should not use sudo gnome-terminal as it can break the gnome-terminal configuration belonging to the non-root user. For more information about this, see:
- RootSudo on the Ubuntu help wiki
- Why should users never use normal sudo to start graphical applications?
( sudo -i gnome-terminal is also okay.)
Getting rid of the controlling non-root terminal:
If you (1) open a graphical terminal, (2) run something like sudo -H gnome-terminal in it, to create a new graphical root terminal, and (3) quit the original non-root graphical terminal . then the root graphical terminal quits as well.
This is because the root graphical terminal is sent SIGHUP when the terminal that owns it is exited.
To prevent this, you might think you could instead launch the graphical root terminal with:
sudo -H gnome-terminal update[s] the user’s cached credentials, authenticating the user if necessary.»
Note that this will still not work if run directly from your desktop environment’s Alt + F2 «run command» box, because you still need a terminal to enter your password for sudo -v .
Or you can do it in what might be called the traditional way, by suspending the job after it starts:
- Run sudo -H gnome-terminal from the original non-root graphical terminal.
- Enter your password as prompted by sudo . The graphical terminal will start.
- Still in the non-root terminal, press Ctrl + Z to suspend the root terminal. While the root terminal is suspended, you can’t use it; its interface will not respond to your actions.
- Quit the controlling non-root terminal with exit . The graphical root terminal job will be both unsuspended and disowned by the non-root terminal, automatically.
sudo -H gnome-terminal ^Z exit
But suppose you wanted to keep using the original, non-root terminal too. Then you could run bg N , where N is the graphical root terminal’s job number, to resume the job in the background. You can run jobs to find N but you probably won’t have to—that number was shown as [N] when you pressed Ctrl + Z . For example:
answered Aug 23, 2014 at 20:22
Eliah Kagan Eliah Kagan
116k 54 54 gold badges 315 315 silver badges 489 489 bronze badges
Aug 23, 2014 at 20:41
gksudo gnome-terminal (assuming gksu is installed)
opens a terminal as root:
No need to explain that you can use this to open any terminal as root like this; like Vala ( gksudo vala-terminal ), Xterm ( gksudo xterm ), Termit ( gksudo termit ), UXTerm ( gksudo uxterm ), Konsole ( gksudo konsole ) and so on.
answered Aug 23, 2014 at 19:56
Jacob Vlijm Jacob Vlijm
82.2k 11 11 gold badges 194 194 silver badges 299 299 bronze badges
Aug 23, 2014 at 20:21
As previously stated, you ask how to run Terminal as root, but more likely you actually want to run the graphical Terminal application as your normal user, and start a root shell inside it where you are logged on as root. In this way the graphical terminal application is not granted root privileges. The previous answers don’t seem to give clear command lines to use so here’s what I use.
With xterm
xterm -bg black -fg red -e sudo -i
The ‘-e sudo -i’ tells xterm to switch to root in the session, and the colours are just to make it very obvious that it’s a root shell.
With Gnome Terminal
gnome-terminal — sudo -i
Personally, I bind Gnome keybindings to launch terminals easily
Go to Keyboard settings, add a custom shortcut with Shortcut Super+X and command ‘xterm -bg black -fg white -sb -sl 5000’, and root xterm with Shortcut Super+Z and command ‘xterm -bg black -fg red -sb -sl 5000 -e sudo -i’.
In the past I have tended to prefer xterm over Gnome Terminal because the font is small and simple, but I’m coming round to Terminal now I run high DPI big screens. Colour coding your terminals is a very good idea once you start to run different profiles with dangerous consequences to avoid accidents (e.g. local root, remote client’s machine, remote client root).
answered May 17, 2019 at 2:33
146 2 2 bronze badges
Yes this is exactly what I want to do: «run the graphical Terminal application as your normal user, and start a root shell inside it » I want to run one application as if it was preceded with sudo. I’m starting about 10 programs each in their own terminal, and each requires sudo. I’m using commands like this in the main script: gnome-terminal —title=»airmon» — bash -c ‘sudo airodump-ng wlan0mon —gpsd -C 1 -w $NOW-wlan0_airmon.pcap; $SHELL’ This works, but I have to type my password into all 10 terminals before they start.
Mar 19 at 20:55
If I precede the launch script with sudo sudo ./tenterms.sh , it fails with # Failed to parse arguments: Cannot open display: . I don’t understand your syntax of gnome-terminal — sudo -i with the current gnome-terminal «— » terminates options and starts the command.
Mar 19 at 20:57
Mar 21 at 9:06
That question sounds so simple that there must be a simple solution, right?
Of course you can use gksudo or similar tools but there may be environments where you don’t want to depend on GTK. It’s confusing but a terminal is not a shell !
The terminal is that thing what shows you stuff, where the shell is the thing that has those fancy features like environment variables, conditionals and all that scripting stuff. That’s why x-terminal-emulator -e . just expects a program to run. No scripts possible here, it just starts a new process. When a terminal starts it just knows that there’s some kind of screen showing you stuff and the input of your keyboard which pours directly in there. A shell delivers all the logic of a script language like eg. sh, bash, ash, zsh, .
The other important distinction is who is running the terminal and what shell is running inside it. You may run a terminal in the context of an ordinary user which runs a root shell inside of it but this has some disadvantages eg. when you start a new tab a new shell is spawned but it falls back to the privileges of an ordinary user. Your command of a ‘New shell please’ goes to the terminal and not the shell!
A disappointment when you realize that you have to enter all those sudo stuff once again for every tab you open. Now, is there a way to open a terminal and not a shell as root without using packages like gksudo? Expecting a debian context:
bash -c «xhost +si:localuser:root; ssh-askpass | sudo -S -Hb /usr/bin/xfce4-terminal —default-working-directory=/root»
Although it looks simple a lot stuff is happening here:
- allow root to access the X desktop of the current user.
- since sudo requires a tty, we avoid that by running ssh-askpass which runs in the context of the current user and asks for your pass.
- sudo now reads that pass from the stdin (-S), it set’s the home folder (-H) and spawns a new process detaching from our context (-b).
- and finally sets the terminal process’ default home folder to root to avoid landing in the home of the current user.
et voilà! You have a terminal running as root spawned in the context of the current user. Now when you spawn a new tab it’s happening inside the root terminal instead of the user who spawned it.
Attention! There’s is a reason why this stuff is so complicated. Keep in mind in whatever X|VNC|RDP session you are running it. It just keeps a terminal open. That’s the downside! If someone is able to capture your session (however likely it may be), root access is for free!
Your decision.
Источник: askubuntu.com
Создание ярлыков на рабочем столе для запуска программ с правами root в Ubuntu 11.10
Программы, такие как Nautilus или gedit, позволяют вам просматривать или просматривать все файлы в вашей системе, но они позволяют только изменять или создавать новые файлы в вашем домашнем каталоге (например, / home / lori) и его подпапках.
Ранее мы показали вам, как получить доступ к расширенному файловому менеджеру, если вы используете Linux Mint 12 . Если вы используете Ubuntu 11.10, легко настроить ярлык, который позволит вам открыть любую программу от имени пользователя root или другого пользователя.
Чтобы создать ярлык в Ubuntu 11.10, вы должны установить несколько пакетов. См. Нашу статью о создании ярлыков в Ubuntu 11.04 и 11.10 для получения инструкций.
ПРИМЕЧАНИЕ. Когда мы говорим вам вводить или вводить текст в поле редактирования или в командной строке, а текст окружен кавычками, НЕ вводите кавычки, если не указано иное.
После того, как вы установили необходимые пакеты, нажмите Ctrl + Alt + T, чтобы открыть окно терминала. Введите в командной строке следующую команду и нажмите Enter.
gnome-desktop-item-edit -create-new ~ / Desktop
ПРИМЕЧАНИЕ. Вы также можете нажать Alt + F2 и ввести команду в появившемся окне редактирования.
Откроется диалоговое окно «Создать панель запуска». Введите имя, например «Открыть как», в поле «Имя». Введите следующий текст в поле редактирования команды:
Вы можете ввести описание для ярлыка в поле редактирования комментария, но это не обязательно. Нажмите OK, чтобы создать ярлык.
Вы вернетесь к приглашению в окне терминала. Чтобы закрыть окно, введите «exit» в командной строке и нажмите Enter.
Новый ярлык «Открыть как» отображается на рабочем столе. Дважды щелкните по нему, чтобы вызвать его.
Откроется диалоговое окно «Выполнить программу». Если вы хотите запустить Nautilus от имени пользователя root, введите «nautilus» в поле «Редактировать», убедитесь, что root выбран в раскрывающемся списке «Как пользователь», и нажмите кнопку «ОК».
Введите пароль в появившемся диалоговом окне и нажмите «ОК».
Появляется следующая ошибка, поскольку Nautilus использует каталог в каталоге .config в домашнем каталоге текущего пользователя, который в данном случае является root. Поэтому нам нужно создать каталог «nautilus» в каталоге /root/.config. Для этого мы должны открыть окно терминала с правами root. Мы можем использовать наш новый ярлык, чтобы сделать это.
Когда появится диалоговое окно «Выполнить программу», введите «gnome-терминал» в поле «Редактировать» и нажмите «ОК».
Откроется окно терминала со знаком фунта (#) в качестве приглашения. Это означает, что вы теперь root. Введите в командной строке следующую команду и нажмите Enter, чтобы перейти в каталог «.config» в каталоге «root».
В каталоге .config нам нужно создать каталог «nautilus». Для этого введите в командной строке следующую команду и нажмите Enter.
Если вы введете «ls» в командной строке и нажмете Enter, вы увидите новый каталог nautilus. Чтобы закрыть окно терминала, введите «exit» в командной строке и нажмите Enter.
Теперь, когда вы вызываете ярлык Open As и вводите «nautilus», Nautilus открывается с правами root.
Вы можете добавить ярлык в панель запуска Unity, перетаскивая его на панель запуска.
Значок добавлен в нижней части лаунчера.
ВАЖНОЕ ПРИМЕЧАНИЕ: Будьте очень осторожны при изменении или удалении файлов за пределами вашего домашнего каталога. Если вы переименуете или удалите важный файл, вы можете испортить вашу систему и сделать ее непригодной для использования.
Вы также можете запустить Firefox от имени пользователя root, введя «firefox» в диалоговом окне «Запуск программы». Если вы хотите открыть домашнюю папку как root, введите «nautilus / home» в диалоговом окне «Запуск программы». Чтобы открыть командную консоль, введите «gnome-терминал» в диалоговом окне «Запуск программы».
Таким способом вы можете запускать большинство программ с правами root, если вы знаете команду для запуска программы. См. Нашу статью о поиске файлов и папок в Linux с помощью командной строки для получения информации о командах which и whereis, которые могут помочь вам найти исполняемые файлы.
Источник: gadgetshelp.com