用户与权限
用户管理
whoami
id # uid、gid 及所属组
id username
# 列出所有本地用户
dscl . list /Users | grep -v '^_'
# 切换用户
su - username
sudo -i # 切换到 root
sudo -u username command # 以指定用户运行命令
sudo
sudo command # 以管理员权限运行
sudo !! # 对上一条命令加 sudo 重新执行
sudo -l # 列出当前用户的 sudo 权限
# 安全编辑 sudoers
sudo visudo
组管理
groups # 当前用户所属组
groups username
dscl . list /Groups # 列出所有组
# 将用户加入组
sudo dseditgroup -o edit -a username -t user groupname
# 查看组成员
dscl . read /Groups/staff GroupMembership
文件权限
ls -la
# -rw-r--r-- 1 user staff 0 Jan 1 00:00 file.txt
# ↑↑↑ ↑↑↑ ↑↑↑
# owner group others
chmod 755 script.sh # rwxr-xr-x
chmod 644 config.txt # rw-r--r--
chmod +x script.sh # 添加执行权限
chmod -R 755 dir/ # 递归
chown user:group file
chown -R user dir/
特殊权限位
| 位 | 说明 |
|---|
setuid 4xxx | 以文件所有者权限执行 |
setgid 2xxx | 以文件所属组权限执行 |
sticky 1xxx | 只有所有者可删除(如 /tmp) |
chmod 4755 binary
chmod +t /tmp
ACL(访问控制列表)
ls -le file.txt # 查看 ACL
chmod +a "group:staff allow read,write" file.txt # 添加
chmod -a "group:staff allow read,write" file.txt # 删除
chmod -N file.txt # 清除所有 ACL
SIP(系统完整性保护)
SIP 保护 /System、/usr、/bin、/sbin,即使 root 也无法修改。
csrutil status # 查看状态
# 禁用/启用需进入恢复模式(开机按住 ⌘R 或长按电源键)
# 在恢复模式终端中执行:
csrutil disable
csrutil enable
Keychain(钥匙串)
# 读取密码
security find-generic-password -a "$USER" -s "service-name" -w
# 添加密码
security add-generic-password -a "$USER" -s "service-name" -w "password"
# 删除
security delete-generic-password -a "$USER" -s "service-name"
相关链接