With the su command, any user who knows the root password can “get root” and do anything the root user can do. An account using “su – root” essentially is the server administrator. This is often much more power than should be delegated to users. A better practice is to delegate specific functions to users rather than granting system-wide root privileges.
The sudo command enables the server administrator to delegate specific commands to specific users without granting them full privileges on the server. Delegation is done in the /etc/sudoers file by using the visudo editor. Users and groups may be given specific commands to run in order to fulfill their responsibilities without having full administrator privileges.
Syntax
The syntax of the sudo command is:
$ sudo [options] {command}
If you encounter the below error while running the sudo command:
sudo: command not found
you may try installing the sudo package as shown below as per your choice of distribution.
Distribution | Command |
---|---|
Debian | apt-get install sudo |
Ubuntu | apt-get install sudo |
Alpine | apk add sudo |
Arch Linux | pacman -S sudo |
Kali Linux | apt-get install sudo |
CentOS | yum install sudo |
Fedora | dnf install sudo |
Raspbian | apt-get install sudo |
sudo Command Examples
1. Run a command as the superuser:
$ sudo less /var/log/syslog
2. Edit a file as the superuser with your default editor:
$ sudo --edit /etc/fstab
3. Run a command as another user and/or group:
$ sudo --user=user --group=group id -a
4. Repeat the last command prefixed with `sudo` (only in `bash`, `zsh`, etc.):
$ sudo !!
5. Launch the default shell with superuser privileges and run login-specific files (`.profile`, `.bash_profile`, etc.):
$ sudo --login
6. Launch the default shell with superuser privileges without changing the environment:
$ sudo --shell
7. Launch the default shell as the specified user, loading the user’s environment and reading login-specific files (`.profile`, `.bash_profile`, etc.):
$ sudo --login --user=user
8. List the allowed (and forbidden) commands for the invoking user:
$ sudo --list
Conclusion
how exactly does the can-do-anything sudo program work? It’s simpler than you think! Refer to the following code:
$ which sudo /usr/bin/sudo $ ls -l $(which sudo) -rwsr-xr-x 1 root root 145040 Jun 13 2022 /usr/bin/sudo
We note that the binary executable sudo is really a setuid-root program! So think about it: whenever you run a program with sudo, the sudo process runs with a root privilege straight away—no password, no fuss. But, of course, for security, the user must enter the password; once they enter it correctly, sudo continues execution and executes the command you want it to—as root. If the user fails to enter the password correctly (within three attempts typically), sudo aborts execution.