1. 程式人生 > >【原創】Linux基礎之sudo

【原創】Linux基礎之sudo

section systems 常用 username linux dde share col users


sudo允許用戶以其他用戶的身份(比如root)執行命令,比如切換用戶、執行命令、讀寫文件等;

配置

sudo配置在:/etc/sudoers

## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the ‘visudo‘ command.
...
## Next comes the main part: which users can run what software on
## which machines (the sudoers file can be shared between multiple
## systems).
## Syntax:
##
## user MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere
root ALL=(ALL) ALL
...
## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d

從這個配置文件可以看到3點:

  • 配置的格式(user MACHINE=COMMANDS)以及示例(在末尾附近),比如root的權限;
  • /etc/sudoers.d/* 這個目錄下邊的文件也會被加載,這樣就可以把不同類別的權限配置分開到不同的文件;
  • 使用visudo編輯,使用vi或vim編輯也可以,不過visudo在保存前會做檢查,如果配置有問題會報錯,直接保存錯誤的配置可能導致難以預料的後果,千萬不要嘗試;

常用場景

1 切換用戶

username ALL=(root) NOPASSWD: /bin/su - targetuser

允許username切換到targetuser

%groupname ALL=(root) NOPASSWD: /bin/su - targetuser

允許groupname裏邊的用戶切換到targetuser

2 執行命令

username ALL=(root) NOPASSWD: /usr/sbin/iptables

允許username執行iptables命令

【原創】Linux基礎之sudo