Root User in Ubuntu- Important Things You Should Know

-u user
  • username: Tom
  • group: gTom
  • C program file: my_pro.c

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.

Use visudo only to edit /etc/sudoers as root. From visudo add:

ec  ALL=(ALL)   NOPASSWD: ALL

This works both on Linux and Mac.

ec ALL=NOPASSWD:ALL

Next time I am here, decipher the syntax and understand what all ALLs mean.

You shouldn’t need to use root to get rid of a segmentation fault. If root is the only thing that fixes a segfault, then the program has a bug. Programs should not fail like that just because they don’t have root.

sudo runs a command as the root (the default), without needing the root password:

sudo service some-service stop
sudo -u some-user some-command

Extensive information about how sudo is configured to run:

# as root
sudo -V

Use visudo only to edit /etc/sudoers as root. From visudo add:

webr    rangiroa= NOPASSWD: /home/webr/*/bin/apachectl

to give permission to run «/home/webr/httpd/bin/apachectl» on rangiroa, as root, without asking for webr’s password either — which is good for automated scripts.

It is important to define all environment variables required during server’s operation, as they are NOT inherited from root’s.

Example: JAVA_HOME, etc.

    ...

    start() {
        sudo -H -u wiki /bin/bash --login -c "/home/wiki/tomcat/bin/startup.sh 2>&1 >> /home/wiki/tomcat/logs/catalina.out"

    ...

    stop() {
        sudo -H -u wiki /bin/bash --login -c "/home/wiki/tomcat/bin/shutdown.sh 2>&1 >> /home/wiki/tomcat/logs/catalina.out"

    ...

The sudo and su commands are among the most widespread and effective in Linux. By deterring unpredictable things in your network, you can deter performance and safety issues in your network.

The two methods of gaining root privileges are sudo and su command. As a result, each functions distinctly and uses a distinct default configuration counting on the Linux distribution.

This permits us to exchange accounts without having to log out of the existing session. The difference between sudo and su  commands is that sudo command enables limited credentials and su command enables limitless credentials.

Table Of Contents

While logged in as the root account of a CLI installation, almost every application gives me this error:

Don't run this as root!

I want to bypass this error and run the application while logged into root. How do I do this?

asked Jul 11, 2016 at 9:44

Dev's user avatar

2 gold badges10 silver badges30 bronze badges

sudo adduser youruser sudo
sudo usermod -a -G sudo youruser

answered Jul 11, 2016 at 9:54

bobbybackblech's user avatar

Fortunately this question has an answer that works. Using the root account is insecure and I understand that. The accepted answer there is going to help me a lot. Thank you for your suggestions, criticism, and help, bobbyblackblech, Pilot6, Serg, and Parto.

Community's user avatar

answered Jul 11, 2016 at 10:13

Dev's user avatar

2 gold badges10 silver badges30 bronze badges

sudo <command>
sudo gedit

answered Jul 11, 2016 at 10:53

Juanjo Salvador's user avatar

xhost +
sudo foo
...
sudo bar

For foo and bar being X applications.

But I agree with everybody: don’t do that!

answered Jul 13, 2016 at 4:40

Michael Hooreman's user avatar

i made an script for my developers inside /root/prepare_server.sh

#!/bin/bash

FILES="/var/www/html/crm/cicrm/cache/
/var/www/html/crm/cicrm/data/
/var/www/html/crm/cicrm/logs/
/var/www/html/crmtest/cicrm/cache/
/var/www/html/crmtest/cicrm/data/
/var/www/html/crmtest/cicrm/logs/"

for f in $FILES
do
echo "processing $f" 1>&2
if [[ ! -e $f ]]; then
    mkdir $dir
elif [[ ! -d $f ]]; then
    echo "$f already exists but is not a directory" 1>&2
fi
done

chown -R manager:phpdev /var/www/html/crm/
chown -R manager:phpdev /var/www/html/crmtest/
chown -R manager:phpdev /var/redmine/crmGit/
chown -R manager:phpdev /var/redmine/owncloudGit/
chmod -R 770 /var/redmine/crmGit/
chmod -R 770 /var/redmine/owncloudGit/
chmod -R 770 /var/www/html/crm/
chmod -R 777 /var/www/html/crm/cicrm/cache/
chmod -R 777 /var/www/html/crm/cicrm/data/
chmod -R 777 /var/www/html/crm/cicrm/logs/
chmod -R 770 /var/www/html/crmtest/
chmod -R 777 /var/www/html/crmtest/cicrm/cache/
chmod -R 777 /var/www/html/crmtest/cicrm/data/
chmod -R 777 /var/www/html/crmtest/cicrm/logs/

and the whole dirs is only owned by me :
manager:phpdev

usually when my developers update all files with git, the permission is changing to developer:developer,

asked Jul 17, 2013 at 1:58

kreamik's user avatar

2 gold badges11 silver badges24 bronze badges

Use sudo, you can write rules in /etc/sudoers file,for example something like:

# format: user host = (run as) NOPASSWD: path
developer ALL=(root) NOPASSWD: /root/prepare_server.sh

Or you can use SUID to run that script as root:

chown root /root/prepare_server.sh
chmod u+s /root/prepare_server.sh

answered Jul 17, 2013 at 2:31

Jiaming Lu's user avatar

Jiaming Lu

5 silver badges20 bronze badges

Then, grant your developer permission to run that specific script.

answered Jul 17, 2013 at 2:12

Jeffrey Hantin's user avatar

Jeffrey Hantin

7 gold badges75 silver badges92 bronze badges

Set up your sudoers file to your liking. You can set it up so they can only run certain commands and they can do it without the password.

answered Jul 17, 2013 at 2:13

Iron Savior's user avatar

Iron Savior

3 gold badges25 silver badges30 bronze badges

I have a shell script that executes a series of terminal commands. What I would like to do is have these commands run through a root shell as they need root privileges.

Manually I would type :

sudo bash

into the terminal and a root shell would appear and I can execute all my commands.

When I try to automate this process in my script, the root shell appears but none of my commands execute, once I close the root shell with exit the commands then execute.

How can I fix this problem?

asked Dec 23, 2015 at 9:15

SyntaxErr0r's user avatar

sudo can run any command as root, not just a bash.
actually, it’s suggested use is to run the commands you need rather than open a generic shell with root access.

 $ cat myscript
 # cmd1 doesn't require supercow powers
 cmd1
 # but cmd2 and cmd3 do
 sudo cmd2
 sudo cmd3
 # cmd4 doesn't require supercow either
 cmd4
 $ ./myscript
 $

the nice part is, that sudo will cache the authorization for you: so if you have just entered the password correctly for cmd2, it won’t ask you again for cmd3.

 $ cat myscript
 cmd1
 cmd2
 cmd3
 cmd4
 $ sudo ./myscript
 $

answered Dec 23, 2015 at 9:34

umläute's user avatar

8 gold badges65 silver badges121 bronze badges

sudo -s <<EOF
#all root commands
#here
EOF

Using sudo in every command:

sudo cmd1
sudo cmd2
...

Compared to the heredoc method it has one disadvantage: If any command takes much time that the sudo session expires then the next sudo will ask for password again.

sudo /path/to/myscript
#all commands inside myscript gets sudo privilege

answered Dec 23, 2015 at 13:08

Jahid's user avatar

9 gold badges90 silver badges108 bronze badges

When I try to automate this process in my script, the root shell
appears but none of my commands execute, once I close the root shell
with exit the commands then execute.

This is because doing sudo bash spawns a sub-shell which even though has the root privileges will be useless because the commands that you wish to execute are in the parent shell. So once you exit this root shell your successive commands run in the normal shell with normal privileges.

Дополнительно:  Root access как получить

You could do it this way :

#!/bin/bash
function do_on_demand()
{
#The commands that you wish to execute as root goes here.
}
export -f do_on_demand
su root -c "do_on_demand"

Save as say supercow, do chmod u+x supercow and run it.

Doing this you could run a set of commands as root just by entering the
root password once.

This may give you the root subshell as you wish :

su - -c "bash -c 'command1;command2'"

But a problem with this one is that the parent environment can’t be used here, so be vigilant to give the full path to your scripts inside the bash commands.

answered Dec 23, 2015 at 9:29

sjsam's user avatar

5 gold badges54 silver badges101 bronze badges

In my scripts, I just type sudo before any command that needs higher privilege. You can do sudo su as the first command in your script. When you run the script, it will ask for your password, and then complete as necessary.

answered Dec 23, 2015 at 9:57

user3606374's user avatar

Either you run commands with root privilege like this:

sudo any_command
sudo su

What is root user? Why is it locked in Ubuntu?

Root User Ubuntu

You don’t need to have root privilege for your daily tasks like moving file in your home directory, downloading files from internet, creating documents etc.

Take this analogy for understanding it better. If you have to cut a fruit, you use a kitchen knife. If you have to cut down a tree, you have to use a saw. Now, you may use the saw to cut fruits but that’s not wise, is it?

Does this mean that you cannot be root in Ubuntu or use the system with root privileges? No, you can still have root access with the help of ‘sudo’ (explained in the next section).

How to run commands as root user in Ubuntu?

apt update
Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)

So, how do you run commands as root? The simple answer is to add sudo before the commands that require to be run as root.

sudo apt update
[email protected]:~$ sudo apt update
[sudo] password for abhishek: 

If you are absolutely new to Linux, you might be surprised that when you start typing your password in the terminal, nothing happens on the screen. This is perfectly normal because as the default security feature, nothing is displayed on the screen. Not even the asterisks (*). You type your password and press enter.

Bottom line:
To run commands as root in Ubuntu, add sudo before the command.
When asked for password, enter your account’s password.
When you type the password on the screen, nothing is visible. Just keep on typing the password and press enter.

How to become root user in Ubuntu?

The sudo command allows you to simulate a root login shell with this command:

sudo -i
[email protected]:~$ sudo -i
[sudo] password for abhishek: 
[email protected]:~# whoami
root
[email protected]:~# 

You’ll notice that when you switch to root, the shell command prompt changes from $ (dollar key sign) to # (pound key sign). This makes me crack a (lame) joke that pound is stronger than dollar.

sudo su

If you try to use the su command without sudo, you’ll encounter ‘su authentication failure’ error.

exit

How to enable root user in Ubuntu?

sudo passwd root

Again, this is not recommended and I won’t encourage you to do that on your desktop. If you forgot it, you won’t be able to change the root password in Ubuntu again.

sudo passwd -dl root

I hope you have a slightly better understanding of the root concept now. If you still have some confusion and questions about it, please let me know in the comments. I’ll try to answer your questions and might update the article as well.

Linux run command or script as root (sudo) on startup / boot

This article explains how to run a command or script at startup / boot as root on Linux, in two ways: using systemd or a cron job.

To use systemd to run a command or script as root when your computer boots, create a file (as root) called (replace with whatever you want to call it) in .

We can use Nano command line text editor to open / create this file:

sudo nano /etc/systemd/system/mycommand.service
[Unit][Service][Install]
WantedBy=multi-user.target

Here, change the value to describe what this does, and the value to the command or path of the script you want to run as root on startup. Don’t add at the beginning of the command or script, because it runs as root anyway.

Now save the file and exit Nano. In case you’re not familiar with Nano text editor, you can save the file by pressing Ctrl + o, then . Exit by pressing Ctrl + x.

sudo systemctl enable mycommand.service

Remember to replace with the actual filename you’ve used for this systemd service file. There’s no need to run the systemd service right now, since this is about running it on boot.

Дополнительно:  Как убрать ошибку в профиле Яндекс браузера

If you use this to run a script, make sure to make the script executable (chmod +x /path/to/script) or else it won’t run.

You might also like: How To Launch Startup Applications With A Delay

How to use a cron job to run a command or script as root on startup / boot

sudo crontab -e
@reboot /path/to/command/or/script

Now save the crontab and exit. If you’ve used Nano command line editor to edit it (should be default in most cases), you can save the file by pressing Ctrl + o, then . Exit Nano by pressing Ctrl + x. Don’t add before command or script, because it runs as root anyway, since it’s added to the root crontab.

In case you want to use a particular editor to edit the root crontab, run it like this: sudo EDITOR=editor crontab -e, e.g. for Vim: sudo EDITOR=vim crontab -e, or for Nano: sudo EDITOR=nano crontab -e.

A few notes about this:

  • If you use this to run a script, make sure to make the script executable (chmod +x /path/to/script) or else it won’t run
  • Use the full path to the command or script, or else it may fail to run (this depends on the Linux distribution you’re using, e.g. you don’t need to use the full path on Ubuntu 20.04 for example)
  • If the script ran by cron also includes commands without the full path, you can avoid having to rewrite the script by adding this at the top of the crontab file:
  • If you need to delay the start of the command / script, you can make use of the command, e.g.: to run the command or script 60 seconds after the system boots

You might also like: How To Run A Command After The Previous One Has Finished On Linux

Which to choose between systemd or a cron job to run a command or script as root on startup / boot, if you have a choice? When in doubt, pick systemd (if it’s available on your system) because it should be more reliable and easier to use.

Also, on Fedora, cron is not installed by default (install it using sudo dnf install cronie). On Manjaro, cron is installed by default, but not enabled by default (enable it using sudo systemctl enable --now cronie).

You might like: How To Find All Files Containing Specific Text On Linux From The Command Line

The «su» command

su command ensures you have the root password when running a command as root. The output of all commands accomplished with su command is not logged.

How does a su command works in Linux?

Listing the Commands Allowed to run as Sudo

sudo -ll [-U <user>]

What You Really Want

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.

If sudo is run over ssh

ssh -t someuser@1.2.3.4 sudo /bin/bash -c "..."

The essential part is «-t».

More details http://unix.stackexchange.com/questions/122616/why-do-i-need-a-tty-to-run-sudo-if-i-can-sudo-without-a-password

If sudo is NOT run over ssh (as part of a systemd script)

sudo behaves that way because the /etc/sudoers file has

Defaults requiretty

which makes sudo require a TTY. If the configuration is removed, the sudo stops complaining.

Major difference between the «su» and «su -«

Here is a list of the main differences between the su and su - commands in Linux:

1. «su» command

  • Switches to the specified user’s account and it will inherit the original user’s environment variables to target user.
  • The current working directory, environment variables, and shell remain unchanged.
  • Example: su root

2. «su -» command

  • Switches to the specified user’s account, but does not inherit the original user’s environment variables instead it resets all environment variables and creates them again.
  • The current working directory is changed to the target user’s home directory.
  • Example: su - root

Here is an example to demonstrate the difference between su and su -:

su ubuntu
Root User in Ubuntu- Important Things You Should Know

We will now create an environment variable in the terminal by using the export command.

export ATATUS_NAME=atatus
Root User in Ubuntu- Important Things You Should Know

Use the env command to determine whether the environment variable has been set:

env 
Root User in Ubuntu- Important Things You Should Know
echo $ATATUS_NAME
Root User in Ubuntu- Important Things You Should Know
su johndoe
Root User in Ubuntu- Important Things You Should Know
Root User in Ubuntu- Important Things You Should Know
su - ubuntu
Root User in Ubuntu- Important Things You Should Know

Multiple commands with sudo over ssh

ssh -t someuser@1.2.3.4 sudo -n /bin/bash -c "id -un; hostname"

This will print «root» and the remote host name.

For a complex example that works, see https://github.com/NovaOrdis/em/blob/master/src/main/bash/bin/commands/update

The «sudo» command

Employing sudo  command in linux offers you the capability to run commands as root. It may not be essential to utilize the root password relying on the setup. A log is held for every command managed with su command.

How does a sudo command works in Linux?

Installation

If sudo command isn’t already installed in your Linux distribution, let’s learn how to install it.

In the case of the apt package manager, you would type:

$ apt install sudo

Alternatively, if using Yum:

$ yum install sudo

A default installation of the sudo package is available in most Linux distributions. Simply type sudo and then hit enter to run the sudo command in linux.

$ sudo
sudo command in Linux
sudo command in Linux

If sudo is installed, you’ll see details about how the sudo package is being used. In the absence of that, a message will appear stating «command not found».

In your C code

...
int main() {
    ...
    system("/usr/bin/mysudo yum install xxxxx");
    ...
}

#gcc && ls -l
#-rwxr--r--  1 Tom gTom 1895797 Jul 23 13:55 my_pro

Infrastructure Monitoring with Atatus

Track the availability of the servers, hosts, virtual machines and containers with the help of Atatus Infrastructure Monitoring. It allows you to monitor, quickly pinpoint and fix the issues of your entire infrastructure.

In order to ensure that your infrastructure is running smoothly and efficiently, it is important to monitor it regularly. By doing so, you can identify and resolve issues before they cause downtime or impact your business.

Infrastructure Monitoring
Infrastructure Monitoring 

It is possible to determine the host, container, or other backend component that failed or experienced latency during an incident by using an infrastructure monitoring tool. In the event of an outage, engineers can identify which hosts or containers caused the problem. As a result, support tickets can be resolved more quickly and problems can be addressed more efficiently.

Дополнительно:  Синий экран смерти (BSoD) - боремся с ошибками •

Impel your application swifter and bug-free, try the 14-days free trial of Atatus!

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

(sudo -i gnome-terminal is also okay.)

Getting rid of the controlling non-root terminal:

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 &

But this will only work if sudo doesn’t have to prompt for a password. If it does, you won’t see the password prompt.

One way to work around this is to use:

sudo -v
sudo -H gnome-terminal

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:

  1. Run sudo -H gnome-terminal from the original non-root graphical terminal.
  2. Enter your password as prompted by sudo. The graphical terminal will start.
  3. 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.
  4. 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
ek@Ilex:~$ sudo -H gnome-terminal
[sudo] password for ek: 
^Z
[1]+  Stopped                 sudo -H gnome-terminal
ek@Ilex:~$

With gksu/gksudo

Since you have the gksu Install 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:

Run a command textbox in Unity

And like this in MATE (GNOME Flashback/Fallback, Xfce, LXDE are similar):

Run Command dialog box in MATE

«su» commands in Linux

su [OPTIONS] [USER [ARGUMENT...]]

The standard function of su command , if summoned without any options, is to drive an interactive shell as root:

$ su
su command in Linux
su command in Linux
$ whoami
su whoami command in Linux
su whoami command in Linux

It is most common to use - ( -l  , --login) when invoking su command . When you execute this command, the shell switches from its original directory to a login shell that simulates an actual login:

su -

With the -s, --shell option, you can run a different shell instead of the one defined in the passwd file. For instance, to run zsh as root, type:

su -s /usr/bin/zsh
su -p

There is no effect on -p when using the - option.

su -c ps
su ubuntu

A comparison of su and sudo

Some key differences between su vs sudo include:

  • su  command  in linux allows a user to switch to another user account and gain all of its privileges, while sudo command  in linux allows a user to execute a specific command with the privileges of another user.
  • su command  in linux prompts the user for the password of the target user account, while sudo command  in linux prompts the user for their own password.
  • su root command gives the user full access to the privileges of the target user account, while sudo root command only grants temporary privileges for a specific command.

«sudo» commands in Linux

The Basics

apt-get update

Here’s how to run the exact command with sudo:

sudo apt-get update

Execute the command as another user

$ whoami
whoami command in Linux
whoami command in Linux
sudo -u [different_username] whoami
Different Username Command in Linux
Different Username Command in Linux

Change to the root user

sudo bash

You should change the command line to:

root@hostname:/home/[username]
sudo bash command in Linux
sudo bash command in Linux

Accomplish previous commands with sudo

sudo !!
sudo !! command in Linux
sudo !! command in Linux

You can also use this with older commands. The historical number should be defined as shown below:

sudo !6

In this example, the sudo command is utilised to recount the 6th entry in history.

Using one line to run multiple commands

By including a semicolon, you can string together numerous commands:

sudo ls; whoami; hostname
sudo numerous command in Linux
sudo numerous command in Linux

Adding a text string to a current file

echo "string-of-text" | sudo tee -a [path_to_file]
Adding text using echo command in Linux
Adding text using echo command in Linux

Compile my_sudo. c to get a my_sudo executable file

   sudo chown root:gTom my_sudo   // user root && gTom group
   sudo chmod 4550 my_sudo        // use SUID to get root privilege

   #you will see my_sudo like this(ls -l)
   #-r-sr-x--- 1 root my_sudo 9028 Jul 19 10:09 my_sudo*

   #assume we put my_sudo to /usr/sbin/my_sudo

Execute. /my_pro

You can execute the yum install without sudo.

How to become «root»?

[sudo] password for bytecommander:

Let me give you an example on how/when to use sudo:

  • apt-get is the command-line tool to run software updates and install new packages. This affects the whole system and therefore requires root permissions. Therefore, whenever we need to invoke apt-get, we have to do this with sudo:

    sudo apt-get install vlc
    

How to proceed with graphical applications instead of terminal commands?

gksudo nautilus

Contents

Write a C code tool

...
int main(int args, char *argv[]) {
    if (args < 2) 
        printf("Usage: my_sudo [cmd] [arg1 arg2 ...]");

    // cmd here is the shell cmd that you want execute in "my_pro"
    // you can check the shell cmd privilege here
    // example:  if (argv[1] != "yum") return; we just allow yum execute here

    char cmd[MAX_CMD];
    int i;
    for ( i = 2; i < args; i ++) {
    // concatenate the cmd, example: "yum install xxxxx"
        strcat(cmd, " ");
        strcat(cmd, argv[i]);
    }

    system(cmd);
} 

Add /etc/sudoers. d File

For this to work, /etc/sudoers must contain:

#includedir /etc/sudoers.d
testuser ALL=(ALL) NOPASSWD: ALL

Final Shot

In Linux, you will usually find a wide variety of options for every task you need to accomplish. The two commands su and sudo in linux each have their strengths, and when used appropriately, they can be secure.

The command sudo and the command su are both methods of gaining root privileges. Each Linux distribution employs a distinct configuration by default, and each function in a distinct way.

When you forget to switch out, you can reach treacherous circumstances. When you use sudo root command, you can enter a password each time you run a command.


Оцените статью
Master Hi-technology
Добавить комментарий