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

Linux shell脚本创建用户时如何分配标签并存入root仅可访问文件

Shell脚本创建用户时分配标签的实现方案

核心实现逻辑

  • 固定标签存储路径为/etc/user_tags,初始化时自动设置权限为600,仅root用户可读写,符合安全要求
  • 在原有用户创建流程中新增标签输入交互
  • 仅当用户创建成功后,才将用户名与对应标签追加写入存储文件

修改后完整脚本

#!/bin/bash
# 标签存储文件配置
TAG_FILE="/etc/user_tags"

if [ $(id -u) -eq 0 ]; then
    read -p "Enter username : " username
    read -s -p "Enter password : " password
    # 解决-s参数不换行的显示问题
    echo ""
    read -p "Enter user tag : " usertag
    
    egrep "^$username" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        echo "$username exists!"
        exit 1
    else
        pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
        useradd -m -p "$pass" "$username"
        if [ $? -eq 0 ]; then
            echo "User has been added to system!"
            # 初始化标签文件,设置仅root可访问
            if [ ! -f "$TAG_FILE" ]; then
                touch "$TAG_FILE"
                chmod 600 "$TAG_FILE"
            fi
            # 写入用户标签
            echo "$username:$usertag" >> "$TAG_FILE"
            echo "User tag has been saved successfully!"
        else
            echo "Failed to add a user!"
            exit 1
        fi
    fi
else
    echo "Only root may add a user to the system."
    exit 2
fi

使用说明

  • 存储文件每行格式为用户名:标签,查询指定用户标签可执行命令:grep "^<用户名>:" $TAG_FILE | cut -d':' -f2
  • 如需限制标签可选范围,可在读取usertag后增加校验逻辑,不符合规则直接终止流程即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:18:00