You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本改造需求:生成各子目录专属SELinux上下文文件

改造Bash脚本生成子目录专属SELinux上下文文件

需求说明

  • 读取包含3个及以上子目录的目标目录
  • 为每个子目录生成以{子目录名}_file_context命名的SELinux上下文文本文件
  • 每个文件仅包含对应子目录下的内容
  • 路径中含有点的文件/目录,生成上下文时需转义点(如com.google.metadata需转换为com\.google\.metadata)

原脚本

#!/bin/bash

dirprev=$PWD
extracted_dir=$1
file_context=$2
partition=${extracted_dir##*/}
IFS=$'\n'

echo "Checking fs config..."
echo ""

cd $extracted_dir
for i in $(find .); do
   j=${i:2}
   if [[ ! $(grep -rF "$partition/$j" $file_context) ]]; then
      test -f $extracted_dir/$j
      if [[ $? == 0 ]]; then
         if [[ $(echo /$j | grep "/bin/") ]]; then
            echo $partition/$j 0 2000 0755 >> $file_context
         else
            echo $partition/$j 0 0 0644 >> $file_context
         fi
      else
         echo $partition/$j 0 0 0755 >> $file_context
      fi
   fi
done
cd $dirprev

改造后的脚本

#!/bin/bash

# 检查参数数量
if [ $# -ne 1 ]; then
    echo "用法: $0 <目标目录>"
    exit 1
fi

target_dir="$1"

# 验证目标目录存在且包含至少3个子目录
subdirs=("$target_dir"/*/)
if [ ${#subdirs[@]} -lt 3 ]; then
    echo "错误: 目标目录需包含至少3个子目录"
    exit 1
fi

# 遍历每个子目录
for subdir in "${subdirs[@]}"; do
    # 获取子目录名称(去掉末尾斜杠)
    subdir_name=$(basename "$subdir")
    # 定义输出文件路径
    output_file="${target_dir}/${subdir_name}_file_context"
    
    echo "正在生成 ${output_file}..."
    
    # 清空输出文件(避免重复内容)
    > "$output_file"
    
    # 遍历子目录下的所有文件和目录(处理含空格/特殊字符的路径)
    while IFS= read -r -d '' item; do
        # 计算相对目标目录的路径
        rel_path="${item#$target_dir/}"
        # 转义路径中的点
        escaped_path=$(echo "$rel_path" | sed 's/\./\\./g')
        # 转换为SELinux要求的绝对路径格式
        selinux_path="/${escaped_path}"
        
        # 判断是文件还是目录,设置对应权限规则
        if [ -f "$item" ]; then
            if [[ "$rel_path" == */bin/* ]]; then
                echo "${selinux_path} 0 2000 0755" >> "$output_file"
            else
                echo "${selinux_path} 0 0 0644" >> "$output_file"
            fi
        else
            echo "${selinux_path} 0 0 0755" >> "$output_file"
        fi
    done < <(find "$subdir" -print0)
    
    echo "${output_file} 生成完成"
done

echo "所有SELinux上下文文件生成完毕"

脚本说明

  • 参数校验:仅需传入目标目录路径,自动检查子目录数量是否达标
  • 子目录专属文件:为每个子目录生成独立的上下文文件,避免内容混杂
  • 路径转义:通过sed工具自动转义路径中的点,符合SELinux上下文格式要求
  • 安全遍历:使用find -print0配合read -d ''处理含空格或特殊字符的路径,避免遍历错误
  • 权限规则保留:沿用原脚本的权限逻辑,bin目录下文件使用0 2000 0755,普通文件用0 0 0644,目录用0 0 0755

示例效果

假设目标目录结构如下:

myfolder/
├── product_a/
│   ├── app/
│   │   └── com.google.metadata
│   └── bin/
│       └── test_bin
├── system_a/
└── system_ext_a/

生成的product_a_file_context内容示例:

/product_a 0 0 0755
/product_a/app 0 0 0755
/product_a/app/com\.google\.metadata 0 0 0644
/product_a/bin 0 0 0755
/product_a/bin/test_bin 0 2000 0755

内容的提问来源于stack exchange,提问作者Gilmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 14:22:47