SH - Sudo (Switch User and do)

> Procedural Languages > Bash Shell and (Unix|Linux) Utilities (XCU)

1 - About

execute a command as another user

sudo determines who is an authorized user by consulting the file /etc/sudoers.

See also:

Advertising

3 - Example

sudo -H -u UserOtherThanRoot

where:

  • - H: sets the HOME environment variable to the homedir of the target user
  • - u: run the specified command as a user other than root

4 - Configuration File

4.1 - /etc/sudoers

The default security policy is sudoers, which is configured via the file /etc/sudoers, or via LDAP.

Open the sudoers file

sudo visudo

4.2 - /etc/sudoers.d/

The last line of the /etc/sudoers files include others configuration that can be added in the directory /etc/sudoers.d/

The last line is not a comment. A comment in the sudoers file as a space after the hash tag

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d

Example in Azure they will add the file waagent

/etc/sudoers.d/waagent
sshuser ALL=(ALL) NOPASSWD: ALL
Advertising

4.3 - /etc/sudo.conf

The sudo configuration is in the file /etc/sudo.conf

5 - Management

Language of the configuration file

5.1 - wheel / sudo admin group

If the wheel line is uncommented, you got an admin group.

## Allows people in group wheel to run all commands
%wheel	ALL=(ALL)	ALL

Example:

cat /etc/group | grep wheel
wheel:x:27:testuser,sshuser

5.2 - Allow a user to run a command

In the /etc/sudoers file add the following rules:

userName ALL=(ALL) NOPASSWD: /full/path/to/command
# or
userName ALL=(ALL) NOPASSWD: /full/path/to/command ARG1 ARG2

Example allow the powercenter user to start and stop its services

powercenter  ALL=(ALL) NOPASSWD: /sbin/service infa start
powercenter  ALL=(ALL) NOPASSWD: /sbin/service infa stop
Advertising

5.3 - Disable password prompt

Disable password prompt for all command.

  • Open the sudoers file.
sudo visudo
  • Append the following line at the bottom of the sudoers file:
<username> ALL=NOPASSWD: ALL
  • Save the file and exit the editor.
  • Log out and log in to apply the changes.

5.4 - Test if allowed

run sudo with the -l or -v flags

Example with the su command

$ sudo -l su
[sudo] password for gerard:
/bin/su

If a user who is not listed in the sudoers file tries to run a command via sudo without the -l or -v flags, mail is sent to the proper authorities, as defined at configure time or the sudoers file (defaults to root).

6 - Documentation / Reference

lang/bash/sudo.txt · Last modified: 2019/10/06 14:44 by gerardnico