Linux sudo Command

Linux 命令大全Linux Command Reference

sudo stands for "Super User DO", which allows authorized users to execute commands as another user (usually the root user). In other words, commands executed via sudo are as if root executed them personally.

Usage permissions: users that appear in /etc/sudoers.

Syntax

sudo [选项] 命令

For example:

sudo apt update          # 以 root 权限更新软件包列表
sudo vim /etc/hosts     # 编辑需要 root 权限的文件

Parameter description:

  • -i: Simulate initial login, load the target user's environment
  • -s: Run a shell
  • -uuser: Run as the specified user
  • -l: List the sudo commands the current user can execute
  • -v: Verify user credentials (extend the sudo session)
  • -k: Revoke the sudo credential cache

Examples

Execute a single command with root privileges:

sudo apt update
sudo systemctl restart nginx
sudo mkdir /opt/myapp

Switch to the root user shell:

sudo -i    # 登录shell,加载root环境变量
sudo -s    # 非登录shell
sudo su -  # 另一种方式

Execute a command as another user:

sudo -u username command
sudo -u postgres psql  # 以 postgres 用户运行 psql

Check available permissions:

sudo -l

Edit system files:

sudo nano /etc/hosts
sudo vim /etc/nginx/nginx.conf

Configuration File

sudo's configuration is stored in the /etc/sudoers file and should be edited using the visudo command:

sudo visudo

Common configuration examples:

# 允许用户免密码执行所有命令
username ALL=(ALL) NOPASSWD: ALL

# 允许用户组执行特定命令
%wheel ALL=(ALL) /bin/systemctl, /usr/bin/apt

Frequently Asked Questions

User not in the sudoers file:

# 需要 root 用户将目标用户加入 sudo 组:
usermod -aG sudo username  # Ubuntu/Debian
usermod -aG wheel username # CentOS/RHEL

Adjusting the cache duration:

Modify timestamp_timeout in /etc/sudoers (unit: minutes):

Defaults timestamp_timeout=30

Differences between su and sudo

Feature su sudo
Password required Target user's password Current user's password
Session duration Until manual exit Single command or short-term cache
Configuration complexity Simple Requires configuring sudoers
Security Requires knowing the root password More granular permission control
Auditing Limited More detailed logs

Although the su command is simple and direct, sudo is usually the more recommended choice in modern system administration because it provides better security and auditing capabilities.

Linux 命令大全Linux Command Reference

Other Extensions