Linux Sudo Command Explained: Usage, Configuration & Troubleshooting

目次

1. Getting Started: What is sudo?

The Basic Meaning and Role of sudo

In Linux and Unix-like systems, “sudo” is a crucial command.
sudo” is short for “superuser do” and is a tool to temporarily borrow administrator privileges (root privileges) to execute commands. Typically, regular users do not have the authority to perform operations that affect the entire system (such as installing packages or changing system settings). However, by using the sudo command, these privileged operations can be executed on a limited basis.

For example, you can execute the apt command with root privileges by running the following command:

sudo apt update

Thus, sudo plays a role in balancing system security and convenience as a “mechanism to safely use administrator privileges.”

Differences from the su Command

There is a command su that has a similar purpose to sudo, but there are clear differences between the two.

  • su stands for “substitute user” and is a command to switch to another user (mainly root). When you use su, operations are performed in a way that completely “becomes” the specified user.
  • On the other hand, sudo executes commands with temporarily borrowed administrator privileges while remaining the current user.

In other words, su is a method of switching on a per-session basis, while sudo is a method of escalating privileges on a per-command basis. This difference is significant in terms of security; sudo makes it easier to manage operation history, and in recent distributions, sudo has become the standard method.

Typical Linux Distributions Where sudo is Used

sudo is used by default in many Linux distributions, and its use is particularly assumed in the following distributions:

  • Ubuntu-based (Ubuntu, Linux Mint, etc.)
    → Initially, you do not log in directly to the root account but manage it with sudo.
  • Debian-based
    → sudo may be enabled later, but it is often recommended as a security policy.
  • Fedora, CentOS, and Red Hat-based
    → While using the root account is possible, using sudo is also common.

Especially in Ubuntu, the root account is disabled by default, and all administrative operations are designed to be performed via sudo. Therefore, understanding sudo is essential for Ubuntu users.

Why is “sudo sudo” Searched For?

The search keyword “sudo sudo” may seem redundant at first glance, but there are actually cases where it is searched with the following intentions:

  • Beginners who want to know the meaning and usage of sudo enter it repeatedly for emphasis.
  • Users who have encountered problems using sudo (e.g., sudo: sudo: command not found) are searching for solutions.
  • Users who saw examples of double sudo usage in scripts or pipelines and wondered about it.

Understanding these search intentions, the following chapters will explain in detail the correct usage and configuration methods of sudo, as well as troubleshooting.

年収訴求

2. Basic Usage of the sudo Command

Basic Syntax of sudo

The basic format of sudo is very simple.

sudo [options] command

For example, to update the system’s package information, use the following:

sudo apt update

This command means “execute ‘apt update’ with root privileges.”

Password Authentication Mechanism and Cache

The first time you use sudo, or after a certain period of time has passed, the system will prompt you to enter your user password. This is a mechanism to enhance security and prevent accidental operations or unauthorized use by third parties.

After entering the password, it is cached for a certain period (5 minutes by default in Ubuntu), and you can omit password entry when using sudo again. This time can be changed in the sudoers file.

Frequently Used Options

sudo has many options to make operations more convenient and flexible. Below are some of the most commonly used ones.

-u (Execute as Another User)

By default, it uses root privileges, but by using the -u option, you can execute commands as any user.

sudo -u www-data whoami

The execution result will be www-data, confirming that “the command was executed as www-data, not as myself.”

-s (Start a Shell)

The following command allows you to temporarily open a shell with root privileges.

sudo -s

However, operations in the root state should be performed with caution.

-i (Log in as a Full Root User)

This option recreates a more complete root environment. Since environment variables are also switched to those of root, it becomes a root session in the same state as immediately after login.

sudo -i

-l (Check Executable Commands)

You can also check the commands that you can execute using sudo.

sudo -l

This is useful for checking security restrictions and testing privilege settings.

Points for Beginners to Note

  • You need to put a space after sudo. Example: sudoapt is incorrect.
  • If you want to execute multiple commands, you need to enclose the entire command in quotes (" or ') or separate them with semicolons.
  • Be careful when running GUI applications with sudo, as it may corrupt configuration files (e.g., sudo gedit).

3. The sudoers File and Access Control

What is the sudoers File?

The configuration file that controls the behavior of the sudo command is /etc/sudoers in the system. This file defines who can execute which commands with sudo.

For example, fine-grained access control is possible, such as allowing a certain user to execute only specific commands with sudo.
This flexibility makes it possible to realize the security principle of granting users only the minimum necessary privileges (principle of least privilege).

Safe Editing with the visudo Command

The /etc/sudoers file should not be edited directly with a text editor.

This is because a syntax error can make sudo unusable, making recovery difficult. Therefore, it is recommended to use the visudo command for editing.

sudo visudo

visudo performs syntax checking upon saving, allowing for safe editing.

Basic Syntax and Configuration Examples

The basic syntax of the sudoers file is as follows:

username hostname = (runas_user) command(s)

Example:

alice ALL=(ALL:ALL) ALL

This setting allows the user “alice” to execute all commands on all hosts as any user.

To add more restrictions:

bob ALL=(ALL) /usr/bin/systemctl restart nginx

This setting restricts the user “bob” to only being able to execute the “nginx restart command” with sudo.

Controlling by Group: The sudo Group

In many distributions such as Ubuntu, users belonging to the sudo group are granted the privilege to use sudo.

%sudo  ALL=(ALL:ALL) ALL

By writing %sudo in this way, management by group becomes possible.

To add a user to the sudo group, use the following command:

sudo usermod -aG sudo username

How to Use and Precautions for the NOPASSWD Option

If you find it troublesome to enter your password every time you execute sudo, you can use the NOPASSWD option to skip password entry.

alice ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx

With this setting, the user “alice” will be able to restart nginx without a password.

However, this increases security risks, so it is important to use it only for a limited number of commands.
In particular, combining it with ALL is not recommended.

4. Advanced Usage of sudo

Executing Commands as a Specific User

Normally, sudo executes commands with root privileges, but by using options, you can also execute commands as any user.

For example, if you want to execute a command as the “www-data” user used by the web server, use the following:

sudo -u www-data whoami

The execution result will be www-data, confirming that “the command was executed as www-data, not as myself.”

This usage is useful when you want to check different environments or privileges for each user.

Combination with Redirects and Pipes

A common point of confusion for beginners is the combination of sudo with redirects (>) and pipes (|).
For example, the following command may look correct at first glance, but it will not work as expected:sudo echo "test" > /etc/test.conf

In this case, echo itself is executed with sudo, but the redirect with > is executed with regular user privileges. Therefore, writing will fail.

The correct way is to use the tee command:

echo "test" | sudo tee /etc/test.conf

By doing this, the redirect part is also executed with sudo privileges, and you can avoid the error.

Utilizing sudo in Scripts

When including commands that require administrator privileges in a shell script, explicitly add sudo before the command.
However, if you are creating a script on the assumption that it will be executed by a regular user, it is safer to only add sudo to the necessary parts and avoid executing the entire script with sudo.

Example (install.sh):

#!/bin/bash

echo "Installing package..."
sudo apt install -y nginx

There is also a pattern to check if it is root at the beginning of the script:

if [ "$EUID" -ne 0 ]; then
    echo "This script must be run as root"
    exit 1
fi

By including such controls, safe script operation becomes possible.

Frequently Used Convenient Commands

  • sudo !!
    → Re-executes the previous command with sudo. For example:
    apt update
    sudo !!

This has the same effect as sudo apt update.

  • sudo -k
    → Manually clears the sudo password cache. This is useful for security reasons, such as before temporarily leaving your terminal.
  • sudo -v
    → Extends the sudo privileges for the current session. This is convenient for long tasks.

5. Security and Best Practices

Adhere to the Principle of Least Privilege

The primary purpose of using sudo is to enable system operations with the minimum necessary privileges.
In other words, the ideal usage is not to “always be the all-powerful root user,” but to “borrow the power of root only when necessary and within the necessary scope.”

Following this principle, the following settings, for example, are desirable:

  • Allow users to execute only specific commands with sudo (e.g., systemctl restart nginx).
  • Minimize the use of NOPASSWD.
  • Manage users with administrative privileges in groups (e.g., sudo).

Logging and Auditing

sudo records executed commands in logs. This allows you to check later who used which command and when.

The main log destinations are as follows (may vary depending on the distribution):

  • /var/log/auth.log (Ubuntu, Debian-based)
  • journalctl (distributions with systemd)

For example, to check the sudo usage history in Ubuntu:

grep 'sudo' /var/log/auth.log

Or:

journalctl _COMM=sudo

This makes it possible to track who did what even in the event of unauthorized or accidental operations. This is an essential perspective in server management.

Actual sudo Vulnerability (CVE-2021-3156)

While sudo is a very reliable tool, significant vulnerabilities have been reported in the past.

A particularly famous example is CVE-2021-3156 (commonly known as Baron Samedit), released in 2021.
This was a serious vulnerability where, under certain conditions, a malicious input could allow a regular user to gain root privileges.

This issue has already been fixed, but as this case shows:

  • Always keep important packages including sudo at the latest version.
  • Regularly check official websites and vulnerability databases.

Such measures are necessary.

Introduction to sudo Alternative: doas

Among some minimal Linux environments and security-conscious users, a command called doas is also used as an alternative to sudo.

doas is a concise privilege escalation tool originating from OpenBSD, characterized by its simpler configuration and higher security compared to sudo.

Example:

doas apt update

The configuration file is written in /etc/doas.conf. The syntax is also simple:

permit nopass :wheel

As shown, you can easily write settings such as allowing users in the wheel group to use doas without a password.

However, since doas is not provided by default in some Linux environments, it takes some effort to install and configure.
Depending on the purpose and objective, it is good to choose whether sudo or doas is more suitable.

6. Common Errors and Troubleshooting

“User is not in the sudoers file” Error

username is not in the sudoers file. This incident will be reported.

This error is displayed when the current user does not have permission to use sudo. It typically occurs when a new user who has not been added to the sudo group executes a command.

Solution:

  1. Log in with another user who has root privileges.
  2. Add the target user to the sudo group.
sudo usermod -aG sudo username

After that, log out and log back in to the session, and sudo will be available.

“Permission denied” Error When Using Redirects or Pipes

Permission denied

This error occurs because even if you intend to execute a command with sudo, the redirection destination or pipe processing is being done outside of sudo.

Incorrect Example:

sudo echo "test" > /etc/test.conf

In this case, echo is executed with sudo, but writing to the file is done with the privileges of the regular user, resulting in an error.

Correct Usage:

echo "test" | sudo tee /etc/test.conf

Or, to write multiple lines at once, it is better to use sudo tee or sudo bash -c.

sudo bash -c 'echo "line1" > /etc/test.conf'

Inoperability Due to Errors in Editing the sudoers File

If you directly edit the sudoers file and make a syntax error, sudo itself may become unusable. This is a very dangerous state.

Solution:

  1. Log in with the root account (note that it is disabled by default in Ubuntu).
  2. Repair with the following command:
pkexec visudo

If pkexec cannot be used, you will need to boot into recovery mode or similar to modify the /etc/sudoers file.

Also, to prevent syntax errors, always use the following for editing:

sudo visudo

“sudo: command not found”

sudo: command not found

This error occurs when sudo is not installed on the system or cannot be found due to a problem with the PATH environment variable.

Solution:

  • Log in with root privileges and reinstall sudo as follows:
apt update
apt install sudo
  • Or execute by directly specifying the path to /usr/bin/sudo:
/usr/bin/sudo ls

7. FAQ: Frequently Asked Questions About sudo

Q1. What is the difference between sudo and su?

A:
sudo is a command to “temporarily execute only specific commands with administrator privileges,” whereas su is a command to “switch to the entire user (mainly root).”

  • sudo: Elevates privileges for only some operations while remaining the current user.
  • su: Completely switches to another user.

From the perspective of safety and operation history, the use of sudo is recommended in recent years.

Q2. Do I need the root password when using sudo?

A:
No, you usually enter your own login password, not the root password.
This is to reduce the risk of root password leakage and to make it easier to track the user’s operation history.

Q3. Where are sudo logs recorded?

A:
In many Linux distributions, the operation logs by sudo are recorded in one of the following:

  • Ubuntu/Debian-based: /var/log/auth.log
  • RHEL/CentOS-based: /var/log/secure
  • All systemd environments: journalctl _COMM=sudo

This makes it possible to track who did what even in the event of unauthorized or accidental operations.

Q4. I accidentally edited the sudoers file. What should I do?

A:
First, always make sure to use sudo visudo before editing.
If you can no longer use sudo due to a syntax error, try to repair it using one of the following methods:

  • Log in with the root account and fix it with visudo.
  • If it’s Ubuntu, boot as root from “Recovery Mode” and repair it.
  • pkexec visudo (in environments where polkit is enabled).

Since syntax errors affect the operation of the entire system, please test again after fixing.

Q5. Is there a way to get root privileges without using sudo?

A:
Yes, but it is not recommended due to increased security risks.

For example:

  • Switch to root with the su command (requires the root password).
  • Log in directly with the root account (disabled by default in Ubuntu).

Many Linux distributions have a policy of avoiding direct use of the root account, and using sudo is safer.

Q6. Is it okay to launch GUI apps using sudo?

A:
Basically, it is better to avoid it. For example, running something like sudo gedit can overwrite GUI configuration files with root privileges, which may cause permission inconsistencies or configuration corruption.

When using GUI applications, it is recommended to use gksudo or pkexec as follows (however, these tools may be deprecated or not installed depending on the environment):

pkexec gedit

8. Conclusion

Understand the Role of sudo Correctly

In this article, we have broadly explained “sudo,” a very important command in Linux and Unix-like systems, covering its basic role, usage, configuration methods, applications, security measures, common errors, and FAQs.

sudo is not just something to “put before a command,” but an important access control mechanism that enables necessary work while maintaining system security.

Proper Usage Prevents Trouble

Paying particular attention to the following points is the key to using sudo safely:

  • Operate with the minimum necessary privileges (principle of least privilege).
  • Manage settings safely using visudo.
  • Utilize logs to check and manage operation history.
  • Be careful about behavior when combining with pipes and redirects.
  • Basically avoid using it for GUI applications.

Failure to understand these points can lead to problems such as “files are corrupted,” “settings cannot be restored,” or “sudo has become unusable.”

Choose a Style That Suits Your System Operation

Linux is a very flexible system. In addition to using sudo, you can also use alternative tools such as doas as needed.
Depending on your operational policy and security policy, choose a style that suits you and properly configure and operate it, which will lead to better system management.

Finally

Understanding sudo is the first step in understanding Linux.
Please acquire the correct knowledge and usage not just as a convenient command, but as a “key” to protect the entire system.

We hope that the next time you use Linux, each of your commands will be executed with more confidence.

侍エンジニア塾