7 UNIX / Linux sudo Command Examples to Execute root Command

Using sudo, a regular user can execute root command, provided they are allowed to execute the command by a sysadmin.

Apart from executing the command as root, an user can also execute a command as any other user, if they have the permission to do it.

This article explains how to use the sudo command from end-user point of view.

1. Basic Usage

In the following example, sysadmin has allowed user john to restart apache server.

Now, john can restart the apache from his account itself by using “sudo” followed by the command to restart the apache as shown below. Before executing the apache restart command, sudo will prompt for john’s password and execute the root’s command as shown below.

Also, as root, you can find out all the commands allowed by various users using “-U” and “-l” option. The following command will display all the root commands that user ramesh can execute.

# sudo -U ramesh -l

Note: If john tries to do the same thing, he’ll get error message as shown below, as he cannot view other’s sudo commands.

$ sudo -U ramesh -l
Sorry, user john is not allowed to execute 'list' as ramesh on dev-db.

4. Don’t Prompt for Sudo Password

Use -n option as shown below, which will execute the command without prompting for password. This is very helpful when john wants to run some of the sudo commands as background jobs (or in a shell script), where he doesn’t want sudo to ask for password. -n option stands for non-interactive.

$ sudo -n /sbin/service httpd restart

5. Validate sudo Credential

John can update his sudo cached credential using -v option. -v stands for validate. This is helpful when the password is changed, or if we cant to extend the sudo timeout. The default timeout is 5 minutes.

$ sudo -v
[sudo] password for john:

6. Your Own Sudo Prompt

You can also display your own sudo prompt using -p and format optionas as shown below.

$ sudo -p [%p@%H:%U] /sbin/service httpd restart
[john@dev-db:root]

The following are allowed format options for -p:

%H Host name (if FQDN is set, it will use that)

%h Local host name without domain name

%p Username for which the current password is asked

%U The command will run as this user (mostly root)

%u Invoking user’s login name

%% escape the % and display it literally

7. Execute as Another User or Group

Apart from executing root’s command, john can execute command as a different user.