sudo Command in Linux: sudo -i, sudo -s examples and more

This tutorial will guide you through the basics of the sudo command, which enables a permitted user to execute a command as the superuser or another user, as specified by the security policy in the sudoers file. We’ll explore not only the installation and basic usage of sudo but also dive into interactive shell options like sudo -i and sudo -s, configuring detailed permissions through the sudoers file, ensuring both flexibility and security in administrative operations. You’ll learn how to define access for individual users and groups, customize command execution environments, and implement security practices that restrict or log usage. By understanding these configurations, you’ll be able to effectively manage privileges on your system, safeguarding it against unauthorized changes while facilitating necessary administrative tasks.

In this tutorial you will learn:

  • How to check if sudo is installed on your system
  • How to use sudo -i for interactive root login shells
  • How to use sudo -s and sudo -u for different shell options
  • How to execute commands using sudo
  • How to grant and configure sudo permissions for individual users and groups
  • How to define command-specific sudo permissions for enhanced security
  • How to manage sudo session timeouts and default editor settings
  • How to set up passwordless sudo for seamless automation tasks
  • How to securely log sudo commands and require a terminal for execution
Sudo Command Usage - Installation Configuration and Shell Options
Sudo Command Usage – Installation Configuration and Shell Options
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distribution (Ubuntu, Debian, Fedora, etc.)
Software Sudo package installed
Other Access to terminal and user account with sudo privileges
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user
TL;DR
Use sudo -i to start an interactive root shell with root’s environment, or sudo -s to start a shell while keeping your current environment. For single commands, use sudo command or sudo -u username command to run as a different user.

Quick Sudo Command Reference
Command Purpose
sudo -i Start interactive root login shell
sudo -s Start shell preserving environment
sudo -u user command Run command as specific user
sudo command Execute single command as root

Getting Started with Sudo

Using the sudo command allows a permitted user to execute a command as the superuser or another user, enhancing security by limiting root access. To begin using sudo effectively, you first need to ensure it’s properly installed and configured on your Linux system. Follow these steps to verify installation and understand the sudo configuration.

  1. Check if sudo is installed:Before using sudo, you must confirm that it is installed on your system. You can do this by checking for the presence of the sudo executable in the system path. Open your terminal and type the following commands:
    $ which sudo

    This command will display the path to the sudo executable if it exists, indicating that sudo is installed. For example, it might return /usr/bin/sudo if sudo is installed in the usual location.

    $ sudo -V

    This command will output the version of the sudo command, helping you ensure that it is up to date. This information can be useful for troubleshooting and verifying that your system meets specific security standards.

    If sudo is not installed, you’ll need to install it. You can install sudo using the package management system specific to your Linux distribution. Here are commands for popular distributions.
    For Debian-based systems like Ubuntu:

    # apt-get install sudo

    For Red Hat-based systems like Fedora:

    # yum install sudo
  2. Locate the sudoers file:The sudoers file controls who can run what commands on which machines and as which users. It’s crucial to know where this file is located and to ensure it has the correct permissions set to maintain system security. By default, the sudoers file is located at /etc/sudoers. You can verify its location and permissions with the following command:
    $ ls -l /etc/sudoers

    This command lists the sudoers file along with its permissions. Typically, the permissions should be set so that only root has read and write access (e.g., -r--r-----), ensuring that no unauthorized changes can be made.

    It’s important not to edit the sudoers file directly with a regular text editor. Instead, use the visudo command, which locks the sudoers file against multiple simultaneous edits and performs syntax checking to prevent configuration errors from blocking sudo operations:

    # visudo

    Visudo opens the sudoers file in a safe editor and checks for syntax errors before saving any changes, which helps prevent any misconfiguration that could potentially lock out administrative access.

Once you have confirmed the installation and located the sudoers file, you are ready to configure sudo according to your needs and begin using it to manage administrative tasks securely.

Understanding Sudo -i and Shell Options

Sudo provides several options for starting interactive shells with elevated privileges. Understanding the differences between sudo -i, sudo -s, and related commands is essential for effective system administration. These options differ in how they handle environment variables, shell initialization, and working directories.

  1. Using sudo -i for interactive root login shell: The sudo -i option starts an interactive login shell as the root user, simulating a full root login. This is the most common way to get a root shell environment.
    $ sudo -i

    This command starts a login shell for root, reading root’s .profile, .bash_profile, and other initialization files. The working directory changes to root’s home directory (typically /root), and all environment variables are set as if root had logged in directly. This is equivalent to running sudo su - and provides a complete root environment.

  2. Using sudo -s to preserve your environment: The sudo -s option starts a shell as root but preserves your current user’s environment variables and working directory.
    $ sudo -s

    This command runs the shell specified in your SHELL environment variable with root privileges, but keeps your current directory and most environment settings. This is useful when you need root access but want to maintain your current working context. The shell doesn’t read root’s login files, making it faster to start than sudo -i.

  3. Running commands as a specific user with sudo -u: The sudo -u option allows you to execute commands as any user on the system, not just root.
    $ sudo -u postgres psql

    This example runs the psql command as the postgres user. This is particularly useful for managing services that run under specific user accounts or when you need to perform actions with another user’s permissions. If you don’t specify the -u option, sudo defaults to running commands as root.

  4. Starting an interactive shell as another user: You can combine sudo -i with the -u option to start a login shell as any user.
    $ sudo -i -u postgres

    This command starts an interactive login shell as the postgres user, reading that user’s initialization files and changing to their home directory. This is useful for troubleshooting user-specific issues or managing applications that require a specific user context.

  5. Understanding the difference between sudo su and sudo -i: While both commands give you a root shell, there are subtle differences in how they work.
    $ sudo su -

    This command uses sudo to run the su command, which then switches to root. The hyphen after su makes it a login shell. While functionally similar to sudo -i, using sudo -i is more direct and efficient because it doesn’t involve starting an additional su process. Therefore, sudo -i is the recommended approach for starting an interactive root shell on modern systems.

Configuring Sudo Permissions

Understanding how to configure sudo permissions is crucial for system security and efficient management. The sudoers file controls these permissions, allowing specified users to execute commands with the privileges of other users, typically the superuser. Below are 10 common examples of sudo configurations that cater to various needs in a Linux environment.

  1. Grant sudo access to a single user: To allow a user to execute all commands under sudo, you can grant them full sudo privileges. This is commonly used for administrators.
    john ALL=(ALL) ALL

    This line allows the user ‘john’ on any host to execute any command as any user.

  2. Grant sudo access without a password: Sometimes, for automation tasks, you might want to allow a user to execute commands without a password prompt.
    john ALL=(ALL) NOPASSWD: ALL

    This configuration allows ‘john’ to execute any command on any host as any user without being prompted for a password.

  3. Restrict sudo access to specific commands: Limiting sudo access to specific commands enhances security by minimizing potential damage if a user account is compromised.
    lisa ALL=(ALL) /usr/bin/apt-get, /usr/bin/systemctl

    This allows ‘lisa’ to only run the apt-get and systemctl commands as root on any machine.

  4. Grant sudo access for a specific directory: Granting permission to run commands within a specific directory can be useful for script management or maintenance tasks.
    tom ALL=(ALL) NOPASSWD: /usr/local/scripts/*

    This line allows ‘tom’ to execute any command located within the ‘/usr/local/scripts’ directory without a password using the nopasswd directive.

  5. Configure sudo timeout: By default, sudo sessions last for a certain time. You can extend this duration as per your needs.
    Defaults:jane timestamp_timeout=30

    This sets the sudo timeout to 30 minutes for the user ‘jane’, meaning once authenticated, ‘jane’ won’t need to re-enter her password for sudo commands within this period.

  6. Allow sudo access for a group: If multiple users require the same sudo privileges, configuring a group is more efficient than configuring each user individually.
    %admins ALL=(ALL) ALL

    This grants all members of the ‘admins’ group full sudo access on any machine.

  7. Disallow sudo access for specific commands: To enhance security, you might want to explicitly forbid using certain commands through sudo.
    john ALL=(ALL) ALL, !/usr/bin/vim

    This configuration allows ‘john’ to use all commands except for ‘/usr/bin/vim’.

  8. Set a default editor for visudo: You can specify a default editor to use when editing the sudoers file with visudo to ensure consistency and ease of use.
    Defaults editor=/usr/bin/nano

    This sets nano as the default editor for visudo.

  9. Log all sudo commands: For security and auditing purposes, you may want to log all sudo commands executed on the system.
    Defaults log_output

    This directive configures sudo to log the output of all commands run under sudo to the syslog.

  10. Require a tty for sudo: Requiring a tty for sudo commands can help prevent automated scripts from running potentially harmful commands.
    Defaults requiretty

    This setting forces users to be logged into a real or pseudo-terminal to use sudo.

Each of these configurations can be added to your sudoers file using the visudo command. Always use visudo to edit the sudoers file to avoid syntax errors and potential security issues.

Conclusion

This guide covered the essential aspects of using sudo on Linux systems, from basic installation and verification to advanced shell options and sudoers configuration. We explored how sudo -i provides a complete root login environment, while sudo -s offers a more lightweight shell option that preserves your current context. You also learned how to execute commands as different users with sudo -u and configure granular permissions through the sudoers file. For comprehensive information about all available sudo options and advanced configurations, consult the official documentation by running:

man sudo
man sudoers

You can also visit the official sudo documentation for the latest information and best practices.

Frequently Asked Questions

  1. What is the difference between sudo -i and sudo -s?The main difference lies in environment handling. The sudo -i command starts a login shell as root, loading root’s environment variables and changing to root’s home directory. In contrast, sudo -s starts a shell as root but preserves your current environment and working directory. Use sudo -i when you need a complete root environment, and sudo -s when you want to maintain your current context while having root privileges.
  2. How do I exit a sudo -i shell session?To exit a shell started with sudo -i, simply type:
    # exit

    Alternatively, you can press Ctrl+D. This returns you to your normal user shell. Always remember to exit root shells when you’re done with administrative tasks to minimize security risks.

  3. Can I use sudo -u to run commands as any user?Yes, the sudo -u username command syntax allows you to execute commands as any user on the system, not just root. However, your sudo privileges must be configured to allow this in the sudoers file. By default, sudo runs commands as root, but with proper configuration, you can run commands as service accounts like postgres, www-data, or any other system user.
  4. Why should I use sudo -i instead of sudo su?While both commands achieve similar results, sudo -i is more efficient and direct. The command sudo su - actually starts two processes: sudo first elevates privileges, then runs su to switch users. Using sudo -i accomplishes the same goal with a single process, making it the recommended modern approach. Moreover, sudo -i is consistent with sudo’s design philosophy and provides better integration with sudo’s logging and security features.
  5. How can I check which sudo privileges my user account has?To view your current sudo privileges, run:
    $ sudo -l

    This command lists all the commands you’re allowed to run with sudo, including any restrictions or special configurations applied to your account. If you’re prompted for a password, enter your user password (not root’s password). The output shows which commands you can execute and under what conditions.



Comments and Discussions
Linux Forum