如何写一个脚本批量授权

wen 实用脚本 1

本文目录导读:

如何写一个脚本批量授权

  1. Windows 批量授权(PowerShell)
  2. Linux Shell 批量授权
  3. 批量授权文件访问(Linux ACL)
  4. 数据库批量授权
  5. 企业级批量授权脚本
  6. 快速使用指南
  7. 注意事项

我来为你提供几种批量授权脚本的写法,涵盖不同场景:

Windows 批量授权(PowerShell)

文件/文件夹授权脚本

# batch_permissions.ps1
param(
    [string]$Path = "C:\Data",
    [string]$User = "Everyone",
    [string]$Permission = "Read", # Read, Write, FullControl
    [switch]$Recurse
)
# 设置权限
function Grant-Permission {
    param(
        [string]$ItemPath,
        [string]$Account,
        [string]$AccessType
    )
    try {
        $acl = Get-Acl $ItemPath
        $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule(
            $Account, $AccessType, "ContainerInherit,ObjectInherit", "None", "Allow"
        )
        $acl.SetAccessRule($accessRule)
        Set-Acl $ItemPath $acl
        Write-Host "✓ 已授权: $ItemPath -> $Account ($AccessType)" -ForegroundColor Green
    }
    catch {
        Write-Host "✗ 失败: $ItemPath - $_" -ForegroundColor Red
    }
}
# 批量授权
if ($Recurse) {
    Get-ChildItem -Path $Path -Recurse -Directory | ForEach-Object {
        Grant-Permission -ItemPath $_.FullName -Account $User -AccessType $Permission
    }
}
# 授权根目录
Grant-Permission -ItemPath $Path -Account $User -AccessType $Permission
Write-Host "`n批量授权完成!" -ForegroundColor Cyan

使用方法:

# 给Everyone读取权限
.\batch_permissions.ps1 -Path "C:\SharedFolder" -User "Everyone" -Permission "Read" -Recurse
# 给特定用户完全控制权
.\batch_permissions.ps1 -Path "D:\Project" -User "DOMAIN\UserName" -Permission "FullControl"

Linux Shell 批量授权

文件/目录权限脚本

#!/bin/bash
# batch_permissions.sh
# 配置
TARGET_DIR="${1:-/data}"          # 目标目录
USER="${2:-user1}"                # 用户名
GROUP="${3:-users}"               # 用户组
PERMISSIONS="${4:-755}"           # 权限值
# 检查目录是否存在
if [ ! -d "$TARGET_DIR" ]; then
    echo "错误: 目录 $TARGET_DIR 不存在"
    exit 1
fi
echo "开始批量授权..."
echo "目录: $TARGET_DIR"
echo "用户: $USER"
echo "组: $GROUP"
echo "权限: $PERMISSIONS"
echo "------------------------"
# 设置目录权限
find "$TARGET_DIR" -type d -exec chmod "$PERMISSIONS" {} \;
find "$TARGET_DIR" -type f -exec chmod "644" {} \;
# 设置所有者
chown -R "$USER:$GROUP" "$TARGET_DIR"
echo "完成: 已批量授权 $TARGET_DIR"

使用方法:

chmod +x batch_permissions.sh
./batch_permissions.sh /shared/folder www-data www-data 755

批量授权文件访问(Linux ACL)

#!/bin/bash
# batch_acl.sh
# 批量设置ACL权限
grant_acl_recursive() {
    local dir=$1
    local user=$2
    local perm=$3  # rwx, r-x, r--
    echo "对目录 $dir 中的用户 $user 授予 $perm 权限"
    # 设置默认ACL
    setfacl -R -m u:$user:$perm "$dir"
    setfacl -R -d -m u:$user:$perm "$dir"
    # 验证
    getfacl "$dir" | head -20
}
# 读取配置文件并应用
while IFS=',' read -r dir user perm; do
    [ -z "$dir" ] && continue
    [ "${dir:0:1}" = "#" ] && continue
    grant_acl_recursive "$dir" "$user" "$perm"
done < "permissions.csv"

permissions.csv 配置文件示例:

# 目录,用户,权限
/project,alice,rwx
/project/docs,bob,r-x
/project/public,guest,r--

数据库批量授权

MySQL 批量授权脚本

#!/bin/bash
# mysql_batch_grants.sh
DB_USER="root"
DB_PASS="password"
DB_HOST="localhost"
# 用户和权限配置
declare -A GRANTS
GRANTS["user1"]="SELECT,INSERT,UPDATE ON database1.*"
GRANTS["user2"]="SELECT ON database2.*"
GRANTS["app_user"]="ALL PRIVILEGES ON app_db.*"
# 批量授权
for user in "${!GRANTS[@]}"; do
    mysql -u$DB_USER -p$DB_PASS -h$DB_HOST -e "
        CREATE USER IF NOT EXISTS '$user'@'localhost' IDENTIFIED BY 'password123';
        GRANT ${GRANTS[$user]} TO '$user'@'localhost';
        FLUSH PRIVILEGES;
    "
    echo "已授权用户: $user"
done

企业级批量授权脚本

#!/usr/bin/env python3
# batch_permission_manager.py
import os
import stat
import pwd
import grp
from pathlib import Path
class BatchPermissionManager:
    def __init__(self, config_file=None):
        self.config = self.load_config(config_file) if config_file else {}
        self.change_log = []
    def load_config(self, filepath):
        """加载配置文件"""
        import json
        with open(filepath, 'r') as f:
            return json.load(f)
    def set_permissions(self, path, user, group, mode):
        """设置文件和目录权限"""
        path = Path(path)
        # 设置所有者
        try:
            uid = pwd.getpwnam(user).pw_uid if user else -1
            gid = grp.getgrnam(group).gr_gid if group else -1
            os.chown(path, uid, gid)
        except KeyError as e:
            self.log(f"用户/组不存在: {e}")
            return False
        # 设置权限
        try:
            path.chmod(mode)
            self.log(f"已设置: {path} -> {user}:{group} {oct(mode)}")
            return True
        except PermissionError:
            self.log(f"权限不足: {path}")
            return False
    def batch_process(self, base_path, rules):
        """批量处理"""
        for rule in rules:
            pattern = rule.get('pattern', '*')
            user = rule.get('user')
            group = rule.get('group')
            mode = rule.get('mode', 0o755)
            for item in Path(base_path).rglob(pattern):
                self.set_permissions(item, user, group, mode)
        self.generate_report()
    def log(self, message):
        """记录日志"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.change_log.append(f"[{timestamp}] {message}")
        print(message)
    def generate_report(self):
        """生成报告"""
        report_file = f"permission_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        with open(report_file, 'w') as f:
            f.write("批量授权报告\n")
            f.write("=" * 50 + "\n")
            f.write(f"总操作数: {len(self.change_log)}\n\n")
            for log in self.change_log:
                f.write(log + "\n")
        print(f"报告已保存: {report_file}")
# 使用示例
if __name__ == "__main__":
    # 配置文件示例
    config = {
        "base_path": "/var/www",
        "rules": [
            {"pattern": "*.php", "user": "www-data", "group": "www-data", "mode": 0o644},
            {"pattern": "*.html", "user": "www-data", "group": "www-data", "mode": 0o644},
            {"pattern": "*/cache", "user": "www-data", "group": "www-data", "mode": 0o755}
        ]
    }
    manager = BatchPermissionManager()
    manager.batch_process(config["base_path"], config["rules"])

快速使用指南

Windows 快捷脚本

:: grant_admin.bat
@echo off
echo 正在批量授权管理员权限...
:: 给当前用户添加运行权限
icacls "C:\Program Files\MyApp" /grant "%USERNAME%:F" /T /Q
:: 给 Users 组添加读取权限
icacls "D:\SharedFolder" /grant "Users:R" /T
echo 授权完成!
pause

Linux 一行命令

# 批量授权目录
find /data -type d ! -perm 755 -exec chmod 755 {} \;
# 批量修改所有者
chown -R user:group /data
# 使用 xargs 批量处理
find /data -type f -name "*.sh" | xargs chmod +x

注意事项

  1. 测试环境验证:先在小范围测试
  2. 备份权限:授权前先备份
    getfacl -R /path > permissions_backup.txt
  3. 权限最小化:只给需要的权限
  4. 日志记录:记录所有变更
  5. 回滚方案:准备权限恢复脚本

选择适合你场景的脚本,建议先在小范围测试再应用到生产环境。

抱歉,评论功能暂时关闭!