- How To Allow Normal User Run Commands As Root In Linux with sudo Command?
- Sudo Command
- Sudoers
- Add User To Wheel Group To Enable Admin Access
- Add User Specifically In The Sudoers File
- Sudo Usage Log
- How To Allow Normal User Run Commands As Root In Linux with sudo Command? Infografic
- Как зайти под root в Ubuntu
- Как зайти под root в Ubuntu
- Linux Run Command As Another User
- 1. Using Linux runuser command as another user
- The runuser command options
- 2. Run a Linux command with substitute user and group ID using ‘su command’
- How Can I Log In As root User?
- su command
- su command syntax
- Remote root login over the ssh session
- su command and log files
- Say hello to sudo command
- Sample sudo command session
- Sudo and log file
How To Allow Normal User Run Commands As Root In Linux with sudo Command?
We have an application that needs higher privileges than normal user. This application may be run with root user. But we need to run this application with normal user with root privileges.
Sudo Command
sudo command is used to elevate user privileges to higher. Generally used to run commands as root user. Commands issued with sudo are logged into /var/log/auth.log
In this example we will print the /etc/shadow file which is only printed with the root user. In order to get root privileges we will use sudo .
Sudo Command
Sudoers
Sudoers is sudo configuration file where sudo enabled users are list. Beyond listing users also their permissions are set in this file. Sudoers file can be access from /etc/sudoers . Example sudoers file can be found below
Add User To Wheel Group To Enable Admin Access
There are different ways to get root privileges. Most used way is to add user to the wheel group. Whell is a special group where users in this group have root privileges.
Now user test2 can run higher privilege commands like below
Add User Specifically In The Sudoers File
We can add user test2 to the sudoers file like adding following line.
- We will add our user with echo to the /etc/sudoers file
- test2 is the username
- ALL=(ALL) ALL line will add all privileges to the test2 user.
Sudo Usage Log
sudo command usage is important because it will give root access to the normal users. The actions of the users should be saved in to a log file. sudo command log files are stored in the /var/log/auth.log .
How To Allow Normal User Run Commands As Root In Linux with sudo Command? Infografic
Источник
Как зайти под root в Ubuntu
Политика дистрибутива Ubuntu нацелена на то, что все действия, требующих административных привилегий надо выполнять с помощью команды sudo. Использовать root пользователя как основного для новичков опасно, поскольку они ещё плохо ориентируются в системе и могут забыть, что они вошли как root и удалить что-то важное.
А поскольку восстановить файлы, удалённые с помощью команды rm почти нельзя, то лучше новичков туда не пускать. Но иногда возникает необходимость войти под пользователем root. В этой небольшой статье мы рассмотрим как это сделать.
Как зайти под root в Ubuntu
По причинам, описанным выше для пользователя root пароль в Ubuntu не задан по умолчанию, поэтому вы не можете просто так войти от его имени с помощью в виртуальных консолях доступных по Ctrl+Alt+FN или с помощью утилиты su. Поскольку пароля нет, ввести его верно вы не сможете.
Но это всё очень просто обходится. Для того чтобы войти под пользователем root в терминале достаточно дописать sudo перед командой su:
Также можно использовать опцию -i команды sudo чтобы открыть консоль от имени суперпользователя:
Однако, если вы хотите авторизоваться от имени этого пользователя в виртуальной консоли или по SSH, то вам надо сначала задать для него пароль. Для этого выполните:
sudo passwd root
Затем введите два раза пароль. После этого пользователь root становится почти полноценным пользователем системы. Вы не сможете только войти под ним в графический интерфейс потому что на это действует ограничение самой оболочки Gnome, это очень плохая практика — запускать целую оболочку от имени root.
Но если вам всё же очень хочется, надо немного настроить правила PAM для GDM. Для этого откройте файл /etc/pam.d/gdm-password и закомментируйте там строчку:
sudo vi /etc/pam.d/gdm-password
# auth required pam_succeed_if.so user != root quiet_success
После этого вы сможете авторизоваться от имени root в менеджере входа. Просто кликните по пункту Нет в списке, а затем введите логин root:
Перед вами откроется оболочка, запущенная от имени суперпользователя:
Это очень небезопасно, потому что любая программа может делать с вашим компьютером всё, что захочет и никто её не остановит. Фактически, первые версии Windows тоже работали в таком режиме и поэтому они были очень уязвимы к вирусам.
Источник
Linux Run Command As Another User
Dear nixCraft,
I just want to know how to run Linux commands as another user or as the root user?
–Sincerely,
Confused About Linux commands.
Dear Confused,
You can use the following commands to run as another user or as root user on Linux.
1. Using Linux runuser command as another user
Only session PAM hooks are run, and there is no password prompt. If run as a non-root user without privilege to set user ID, the command will fail as the binary is not setuid. As runuser doesn’t run auth and account PAM hooks, it runs with lower overhead than su.
For example, as a root user you may want to check shell resource limits for oracle user, enter:
# runuser -l oracle -c ‘ulimit -SHa’
Check nginx or lighttpd web server limitations:
# runuser -l nginx -c ‘ulimit -SHa’
# runuser -l lighttpd -c ‘ulimit -SHa’
Sometime, a root user can not browse NFS mounted share due to permission (security) issue:
# ls -l /nfs/wwwroot/cyberciti.biz/http
OR
# cd /nfs/wwwroot/cyberciti.biz/http
Sample outputs:
However, apache user is allowed to browse or access nfs based system mouted at /nfs/wwwroot/cyberciti.biz/http/:
# runuser -l apache -c ‘ls -l /nfs/wwwroot/cyberciti.biz/http/’
# runuser -l apache -c ‘cd /nfs/wwwroot/cyberciti.biz/http/; vi index.php’
No password is required to use runuser command and it must be run by root user only. Sometimes sudo or su will give following error:
To get around this try the following syntax:
# runuser -u www-data — command
## Run commands as www-data user ##
# runuser -u www-data — composer update —no-dev
# runuser -u www-data — php7 /app/maintenance/update.php
The runuser command options
- -l user_login_name : Make the shell a login shell, uses runuser-l PAM file instead of default one.
- -g group : Specify the primary group.
- -G group : Specify a supplemental group.
- -c COMMAND : Pass a single COMMAND to the shell with -c.
- —session-command=COMMAND : Pass a single COMMAND to the shell with -c and do not create a new session.
- -m : Do not reset environment variables.
- -u username : Run command as given username to get around ‘su -‘ or ‘sudo’ limit.
2. Run a Linux command with substitute user and group ID using ‘su command’
The su command allows you to become a super user or substitute user, spoof user, set user or switch user. It allows a Linux user to change the current user account associated with the running console or shell provided that you know the target user’s password. The syntax is as follows:
Источник
How Can I Log In As root User?
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | su/sudo |
Est. reading time | Less than a minute |
It is not good a practice for anyone to use root as their normal user account, because of security risks. Therefore, you use a normal user account instead. You need to use the su or sudo command to switch to root user account.
su command
The su command is use to change user ID or become super-user during a login session i.e. it allows you to become a super user or substitute user, spoof user, set user or switch user.
Note: su only works if you know the target or root user’s password.
su command syntax
If invoked without a user-name, su defaults to becoming the super user. The user will be prompted for a password, if appropriate.
To log in as root user type the following command (you need to supply root user account password when prompted):
$ su —
Sample outputs:
Once logged in, your prompt should change from $ to #. To log in as another user say nixcraft, type the following command (you need to supply nixcraft user account password when prompted):
$ su — nixcraft
Sample outputs:
Remote root login over the ssh session
You can use the ssh client as follows:
$ ssh root@server.ip-address-here
$ ssh root@server1.cyberciti.biz
$ ssh root@1.2.3.4
However, remote root login over ssh session is disabled in most cases for security reasons. First, login as a normal user and then switch to root account using the su command:
su command and log files
The su command logs its usage in a system log file. This is useful to find out su login information. If you are RHEL / CentOS / Fedora Linux user type the following as root to see the contents of /var/log/secure:
# tail -f /var/log/secure
Debian / Ubuntu Linux user try:
# tail -f /var/log/auth.log
Sample outputs:
Say hello to sudo command
The sudo is a program for Linux / Apple OS X / *BSD / Unix-like computer operating systems that allows users to run programs with the security privileges of another user, normally the superuser (root). By default, sudo will prompt for a user password but it may be configured to require the root password or no password at all. Apple Mac OS X and Ubuntu Linux and many other oses uses sudo command for many administrative tasks.
- 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 ➔
sudo executes a command as another user but follows a set of rules about which users can execute which commands as which other users. This is configured in a filed named /etc/sudoers. Unlike su, sudo authenticates users against their own password rather than that of the target user. See how to configure and use sudo tool under Linux operating system.
For example, to login as root under Linux or Unix like operating system, type:
$ sudo -s
Sample sudo command session
Fig.01: Switching to root account using sudo command
Sudo and log file
The sudo log can be viewed by issuing the following command as root user:
See also
- Linux Run Command As Another User – Explains how to run run Linux commands as another user or run commands as root user using runuser, su, and sudo utilities.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
I have installed ubuntu and always log in as user. I have read the HOW TOO’s but I am confused by the comment ‘Make sure you use the root password.’ How can you use a root password when you haven’t got one (I think) because the only password I use is the password I gave when I installed Ubuntu (dapper Drake). Is this a root password also if you say it’s root as time of login. If you have to have a seperate login root password – How do you get it? Thanks john6.
By default, the root account password is locked in Ubuntu. This means that you cannot login as root directly or use the su command to become the root user. However, since the root account physically exists it is still possible to run programs with root-level privileges.
Hmmm, lets see Can not log in as : \ SU Thought Ubuntu is open source The only why you can adjust the Kernel is as root. what they hiddin willis.
opp’s should have read more of the reply’s. but as a openBSD user never really had this issue.
Thank you very much for this help!
To all the latin people…..here is the answer in spanish:
Escriban “su -” para cambiar al root. Les pedira la clave del root.
Escriban “su – gon” para cambiar al usuario llamado gon. Les pedira la clave.
John.
You can change your root password by typing in console” sudo passwd root ” By doing this i had to enter my user password then set a new root password and repeat it.
Baller. That was perfect. Thank you.
thnx. by default there is no password for root, hve to get by typing ”sudo passwd root”.
Thanks for this article and to AIS/fahim for the additional information about how to change the root password! Just what I was looking for.
AIS, thanks a lot
The question is still unanswered.
To login as root is very convenience and very important for some applications. Without it, you may not be able to run those programs at all. Su is good but with great limitation.
So if anyone who know the answer, please help. We do not need advise about workaround.
After 5 minutes of browsing on the Internet, I found it is very easy to make the changes so you can login as root from GUI. This is for Fedora 11:
First, (dangerous?) you must su and login as root then cd to /etc/pam.d
There are two files: gdm and gdm-password. Use your editor and
Comment this statement for both files:
# auth required pam_succeed_if.so user != root quiet
Save and logout. Try login as root. You should be.
After login as root and play around, I found the above changes were not enough. Thanks to my-guides.net, I found the last piece that fixed the problem.
You need to edit another file: /etc/PolicyKit/PolicyKit.conf
and add
between .
That will do the job.
The missing statement between is
Thanks a tonnnnn Gregory. Somehow I could never find the answer for this , instead of getting ridiculed for wanting this. 🙂
Thanks for command “sudo passwd root” !!
you didn’t answer the question!
you condescendingly gave some “best practices” advice, and then proceeded to explain out how to do something else.
I have to agree that the entire tenor of this conversation is offensive. Crossing the street is dangerous, also, but I do it anyway. My mother taught me the risks when I was quite small, as well as how to do it safely. If you really want to keep UBUNTU safe from learning problems, I suggest that you lock down the entire system and send us all to a Windows app.
Instead, please stop insulting all of us who are adults and capable of taking our own risks. I need to open the folder /etc/openvpn using my GUI and add a file to the folder. Stop patronizing me and tell me how to do this please.
I agree whole-heartedly. Uber-geek Linux users can be extremely condescending. I’ve had them to tell me to RTFM. Which one? The “right” one”? The “other” one. The one that applies to my distro? Oh wait, that distro has tons of bugs, but the upcoming distro gives you a workaround. RTFM!
How bout this? FTFM ! FIX it. Fix all the crappy and conflicting documentation. Yeah, this thing is “free”. But when all the wasted time getting things to work is considered, it’s more expensive than products from The Dark Empire. Bottom line is, if you’re going to do something, whether it’s for free or not, do it right and make it work like you say it does. Or don’t do it at all.
You people have a lot of nerve criticizing Windows when you worship a product that is a stone’s throw away from hieroglyphics and documented in glyphs.
Cheers, ubers …
I agree wholeheartedly. I need Linux for a project, but it, and all other Linux distros I’ve used, seems to be dwelling in the past, and the developers delight in their backward approach and to delight in making things difficult. Personally, I think it’s almost up to the Windows 98 point, but not quite there yet….
Источник