
chmod(change mode)是Linux/Unix系统中用于修改文件和目录权限的核心命令。在Linux安全模型中,每个文件和目录都有三组权限(所有者、所属组、其他用户)和三种基本权限(读、写、执行),chmod正是管理这些权限的工具。
chmod既支持直观的符号模式(如u+x),也支持简洁的数字模式(如755),能够精细控制文件和目录的访问权限。正确的权限设置是系统安全的基础,掌握chmod对于保护敏感文件、确保程序正常运行、管理多用户环境至关重要。
1. 基本语法
| 命令 | 说明 |
|---|
chmod MODE FILE | |
chmod 644 file.txt | |
chmod u+x script.sh | |
chmod g-w file.txt | |
chmod o=r file.txt | |
chmod a+x script.sh | |
2. 数字权限模式
| 权限 | 说明 |
|---|
600 | |
644 | |
640 | |
664 | |
700 | |
755 | 所有者完全控制,组和其他读和执行(标准目录、可执行文件) |
750 | |
775 | |
777 | |
444 | |
555 | |
3. 符号权限模式
| 命令 | 说明 |
|---|
chmod u+x file | |
chmod g-w file | |
chmod o-rwx file | |
chmod ug+rw file | |
chmod a+r file | |
chmod a-x file | |
chmod u=rw,go=r file | |
chmod u=rwx,go=rx dir/ | |
chmod go= file | |
符号模式说明:
- 用户标识:
u(所有者)、g(组)、o(其他)、a(所有)
4. 文件和目录的典型权限
| 命令 | 说明 |
|---|
chmod 644 file.txt | |
chmod 755 script.sh | |
chmod 755 directory/ | |
chmod u=rw,go=r file.txt | |
chmod u=rwx,go=rx directory/ | |
chmod +x script.sh | |
chmod -x file.txt | |
5. 递归更改权限
| 命令 | 说明 |
|---|
chmod -R 755 project/ | |
chmod -R u+rwX project/ | |
find project -type f -exec chmod 644 {} + | |
find project -type d -exec chmod 755 {} + | |
chmod -R g-w shared/ | |
chmod -R a+r public/ | |
智能执行(X)说明:大写的X表示仅当目标是目录或已有执行权限时才添加执行权限,对普通文件不会意外添加执行权限。
6. 特殊权限位
| 命令 | 说明 |
|---|
chmod 4755 /usr/local/bin/tool | |
chmod 2755 /srv/shared | |
chmod 1777 /tmp/mytmp | |
chmod u+s file | |
chmod g+s directory | |
chmod +t directory | |
chmod -s file | |
特殊权限说明:
- **SUID (4)**:执行时以文件所有者身份运行(如
/usr/bin/passwd) - **SGID (2)**:目录中新建文件继承目录的组
- **Sticky Bit (1)**:目录中仅文件所有者可删除(如
/tmp)
7. 安全操作模式
| 命令 | 说明 |
|---|
chmod 600 ~/.ssh/id_ed25519 | |
chmod 700 ~/.ssh | |
chmod 644 ~/.ssh/id_ed25519.pub | |
chmod 750 /var/www/app | |
chmod 755 script.sh | |
chmod 600 .pgpass | |
chmod 400 backup.key | |
8. 实用组合模式
| 命令 | 说明 |
|---|
chmod -R 755 public_html/ && find public_html -type f -exec chmod 644 {} + | |
chmod 600 config.yml && chmod +x deploy.sh | |
chmod -R u+rwX,go+rX project/ | |
chmod 2770 /srv/teamproject && chmod g+s /srv/teamproject | |
chmod -R --silent 755 /path 2>/dev/null | |
9. 常用选项速查
| 选项 | 完整名称 | 说明 |
|---|
-R | | |
-v | | |
-c | | |
-f | | |
--reference=RFILE | | |
10. 权限验证命令
| 命令 | 说明 |
|---|
ls -l file.txt | |
ls -ld directory/ | |
stat file.txt | |
namei -l /path/to/file | |
getfacl file.txt | |
11. 故障排查
| 问题 | 解决方法 |
|---|
| Operation not permitted | 检查文件所有权:ls -l;使用sudo或以文件所有者身份执行 |
| Permission still denied after chmod | 父目录可能缺少执行权限(需要x才能进入);检查ACL:getfacl |
| Cannot chmod symlink | chmod |
| 递归模式破坏了应用文件 | |
| 更改在挂载分区上无效 | 检查挂载选项(如noexec、nosuid)和文件系统类型 |
| umask导致新文件权限不符预期 | 检查umask设置:umask;在脚本中设置适当umask |
| 粘滞位没有生效 | |
温馨提示: 权限设置遵循最小权限原则——只授予必要的权限。常用模式牢记于心:文件644/640,目录755/750,私密文件600,可执行脚本755。使用-R递归时要格外谨慎,避免破坏系统文件。对于生产环境,建议先测试更改,或使用find精确控制文件和目录的不同权限。
关注公众号(haopython),请回复: CHMOD