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
相关产品推荐
相关产品推荐

