Linux sudo command
sudo stands for Super User DO and allows authorized users to execute commands as another user (usually root); in other words, commands executed through sudo are as if root executed them personally.
Access permission: users listed in /etc/sudoers.
Syntax
sudo [选项] 命令
** For example:**
sudo apt update # 以 root 权限更新软件包列表
sudo vim /etc/hosts # 编辑需要 root 权限的文件
Parameter Description:
- -i: simulate an initial login, loading the target user's environment
- -s: run a shell
- -u user: run as the specified user
- -l: list the sudo commands the current user can execute
- -v: verify the user's credentials (extend the sudo session)
- -k: revoke the cached sudo credentials
Example
Execute a single command with root privileges:
sudo apt update
sudo systemctl restart nginx
sudo mkdir /opt/myapp
Switch to the root user's 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 a system file:
sudo nano /etc/hosts
sudo vim /etc/nginx/nginx.conf
Configuration file
The sudo configuration is stored in the /etc/sudoers file and should be edited with the visudo command:
sudo visudo
Common configuration examples:
# Allow users to execute all commands without a password
username ALL=(ALL) NOPASSWD: ALL
# Allow user group to execute specific commands
%wheel ALL=(ALL) /bin/systemctl, /usr/bin/apt
Common questions
The user is not in the sudoers file:
# Root user needs to add the target user to the sudo group:
usermod -aG sudo username # Ubuntu/Debian
usermod -aG wheel username # CentOS/RHEL
Adjusting the cache timeout:
Modify timestamp_timeout in /etc/sudoers (unit: minutes):
Defaults timestamp_timeout=30
The difference between su and sudo
| Feature | su | sudo |
|---|---|---|
| Password required | Target user's password | Current user's password |
| Session duration | Until manually exiting with exit | A single command or a short cached period |
| Configuration complexity | Simple | Need to configure sudoers |
| Safety | Need to know the root password | More fine-grained permission control |
| Auditing | Limited | More detailed logs |
Although the su command is simple and direct, in modern system administration sudo is usually the more recommended choice because it offers better security and auditing capabilities.
Linux Command Reference