The sudo (Superuser Do) command allows authorized users to execute commands with root privileges or another userโs permissions, as defined in the /etc/sudoers file.
sudo ls /root๐น Runs ls /root with root privileges.
๐น You will be prompted for your password.
sudo -u nikhil whoaminikhil
๐น Runs whoami as user nikhil.
sudo bash -c "whoami && id"root
uid=0(root) gid=0(root) groups=0(root)
๐น Runs multiple commands as root.
sudo -s
whoamiroot
๐น Opens a root shell.
sudo -i๐น Logs in as root, loading root's environment.
sudo visudo๐น Runs visudo without saving it in shell history.
To configure who can use sudo and for which commands, edit the /etc/sudoers file using visudo:
sudo visudo๐น visudo prevents syntax errors that could lock you out.
nikhil ALL=(ALL:ALL) ALL๐น nikhil can run any command as any user or group.
jaydeep ALL=(ALL) /usr/sbin/apt update, /usr/bin/systemctl restart apache2๐น jaydeep can only run package updates and restart Apache.
jaydeep ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart apache2๐น jaydeep can restart Apache without a password.
nikhil ALL=(ALL) /usr/bin/ls, /usr/bin/cat๐น nikhil can only run ls and cat with sudo.
%developers ALL=(ALL) NOPASSWD: /usr/bin/mkdir, PASSWD: /usr/bin/rm๐น The developers group can create directories without a password but must enter a password to delete files.
%www-data ALL=(ALL:ALL) NOPASSWD: /usr/bin/systemctl restart apache2๐น Web server processes can restart Apache without a password.
Cmnd_Alias WEB_CMDS = /usr/bin/systemctl restart apache2, /usr/bin/systemctl reload nginxjaydeep ALL=(ALL) NOPASSWD: WEB_CMDS๐น Defines a command alias (WEB_CMDS) and assigns it to jaydeep.
| Rule | Description |
|---|---|
nikhil ALL=(ALL:ALL) ALL |
nikhil can run all commands as any user |
jaydeep ALL=(ALL) /usr/bin/systemctl restart apache2 |
jaydeep can only restart Apache |
jaydeep ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart apache2 |
jaydeep can restart Apache without a password |
%developers ALL=(ALL) NOPASSWD: /usr/bin/mkdir, PASSWD: /usr/bin/rm |
Developers can create directories without a password but must enter a password to delete files |
%www-data ALL=(ALL:ALL) NOPASSWD: /usr/bin/systemctl restart apache2 |
www-data can restart Apache without a password |
Cmnd_Alias WEB_CMDS = /usr/bin/systemctl restart apache2, /usr/bin/systemctl reload nginx |
Defines a command alias (WEB_CMDS) for web services |