🛠️ToolsShed

Chmod计算器

计算Unix文件权限。在八进制和符号rwx格式之间转换。

读取 (r)写入 (w)执行 (x)八进制符号表示
所有者6rw-
4r--
其他4r--

八进制

644

符号表示

rw-r--r--

chmod命令

chmod 644 filename

Chmod 计算器帮助您理解和生成 Unix/Linux 文件权限设置。在基于 Unix 的系统中,每个文件和目录都有一组权限位,控制所有者、组和其他所有人谁可以读取、写入或执行它。`chmod` 命令使用符号表示法 (rwx) 或八进制数字(如 755)设置这些权限。

切换所有者、组和其他人列的读取、写入和执行复选框,工具会自动计算等效的八进制值和符号字符串。相反,输入像 644 这样的八进制值,工具会显示每个用户类别启用了哪些权限。

常见权限模式包括 755(所有者可以做任何事;组和其他人可以读取和执行——目录和可执行文件的典型设置)、644(所有者可以读写;其他人只能读取——Web 文件的典型设置)和 600(只有所有者可以读写——SSH 私钥的典型设置)。

常见问题

代码实现

import os
import stat

# Set permissions using octal notation
os.chmod('script.sh', 0o755)   # rwxr-xr-x (owner: rwx, group: r-x, others: r-x)
os.chmod('data.txt', 0o644)    # rw-r--r-- (owner: rw-, group: r--, others: r--)
os.chmod('private.key', 0o600) # rw------- (owner: rw-, no access for others)

# Read current permissions
file_stat = os.stat('script.sh')
mode = file_stat.st_mode
print(oct(stat.S_IMODE(mode)))  # e.g. '0o755'

# Check specific permissions using stat constants
is_owner_executable = bool(mode & stat.S_IXUSR)
is_group_readable   = bool(mode & stat.S_IRGRP)
is_others_writable  = bool(mode & stat.S_IWOTH)
print(f"Owner executable: {is_owner_executable}")

# Build permissions programmatically
perms = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH  # 644
os.chmod('config.ini', perms)

# Recursively set permissions on a directory tree
import pathlib
for path in pathlib.Path('/var/www/html').rglob('*'):
    if path.is_dir():
        os.chmod(path, 0o755)
    else:
        os.chmod(path, 0o644)

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.