Skip to content

实现 chmod 权限计算器 工具

分类:developer | 标签:chmod、权限、Linux、rwx 数字与符号权限互转,可视化展示 rwx 位

2.1 功能说明

数字与符号权限互转,可视化展示 rwx 位

2.1.1 使用指南

使用指导

数字(如 755)与符号(如 u=rwx,g=rx,o=rx)权限互转。r=4 w=2 x=1。

角色

u 所有者、g 所属组、o 其他人、a 全部。

2.2 代码实现

2.2.1 组件结构

本工具是一个基于 Vue 3 <script setup> 语法的单文件组件(SFC),统一包裹在 ToolPageShell 组件内,由它提供页面标题、工具 ID、分类与「使用指南」插槽等通用外壳;核心业务逻辑(响应式状态、计算属性、事件处理函数)全部写在 <script setup> 中,输入/输出通过 el-inputel-button 等 Element Plus 组件与用户交互,所有数据均在浏览器本地处理,不会上传服务器。

2.2.2 核心逻辑概览

<script setup> 中定义的主要函数/方法:

  • applyDigit()
  • toSym()
  • m()
  • apply()
  • fromNum()
  • fromSym()
  • bit()

2.2.3 关键实现代码

以下是该工具的完整 <script setup> 实现(核心代码)。模板(<template>)与样式(<style>)已省略。

vue
import { ref, reactive } from 'vue'
import ToolPageShell from '@/components/ToolPageShell.vue'

const num = ref('755')
const sym = ref('u=rwx,g=rx,o=rx')
const err = ref('')
const rows = reactive([
  { role: 'u 所有者', num: 0, r: false, w: false, x: false },
  { role: 'g 组', num: 0, r: false, w: false, x: false },
  { role: 'o 其他', num: 0, r: false, w: false, x: false }
])

function applyDigit(d) {
  return { num: d, r: !!(d & 4), w: !!(d & 2), x: !!(d & 1) }
}
function toSym(d) {
  const m = (v) => (v & 4 ? 'r' : '-') + (v & 2 ? 'w' : '-') + (v & 1 ? 'x' : '-')
  return { u: m(d.u), g: m(d.g), o: m(d.o) }
}
function apply(d) {
  const u = applyDigit(d.u), g = applyDigit(d.g), o = applyDigit(d.o)
  rows[0] = { ...rows[0], ...u }
  rows[1] = { ...rows[1], ...g }
  rows[2] = { ...rows[2], ...o }
}
function fromNum() {
  err.value = ''
  const v = num.value.trim()
  if (!v) { sym.value = ''; return }
  if (!/^[0-7]{1,4}$/.test(v)) { err.value = '数字模式应为 1~4 位 0-7'; return }
  const pad = v.padStart(3, '0')
  const d = { u: +pad[0], g: +pad[1], o: +pad[2] }
  apply(d)
  const s = toSym(d)
  sym.value = `u=${s.u},g=${s.g},o=${s.o}`
}
function fromSym() {
  err.value = ''
  const v = sym.value.trim()
  if (!v) { num.value = ''; return }
  // 支持 u=rwx,g=rx,o=rx 或 rwxr-xr-x
  let u = 0, g = 0, o = 0
  if (/^[rwx-]{9}$/.test(v)) {
    const bit = (c) => (c === 'r' ? 4 : c === 'w' ? 2 : c === 'x' ? 1 : 0)
    u = bit(v[0]) + bit(v[1]) + bit(v[2])
    g = bit(v[3]) + bit(v[4]) + bit(v[5])
    o = bit(v[6]) + bit(v[7]) + bit(v[8])
  } else {
    const parts = v.split(',').map((s) => s.trim()).filter(Boolean)
    const map = { r: 4, w: 2, x: 1 }
    for (const p of parts) {
      const m = p.match(/^([ugoa]+)=([rwx]*)$/)
      if (!m) { err.value = '符号格式应为 u=rwx,g=rx,o=rx'; return }
      const who = m[1].includes('a') || m[1].includes('u') ? 'u' : ''
      const val = [...m[2]].reduce((a, c) => a + (map[c] || 0), 0)
      if (m[1].includes('a') || m[1].includes('u')) u = val
      if (m[1].includes('a') || m[1].includes('g')) g = val
      if (m[1].includes('a') || m[1].includes('o')) o = val
    }
  }
  const d = { u, g, o }
  apply(d)
  num.value = `${u}${g}${o}`
}
fromNum()

2.3 效果截图

chmod 权限计算器 效果截图

工具访问地址:https://www.i91tools.com/tools/chmod