Bash脚本未识别/home目录下未授权用户问题求助
问题分析
原脚本仅实现了验证合法用户列表中的用户是否存在于/home目录的逻辑,完全遗漏了核心需求的反向检查:/home目录中存在的用户是否属于合法列表。这就是ruslan.test这类不在server.info内的用户未被检测到的根本原因。
修正后的脚本
#!/bin/bash public_ip=$(curl -s checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//') # 收集/home下的现有用户到数组(避免ls的潜在问题,直接遍历目录提取用户名) declare -a existing_users for user_dir in /home/*/; do # 提取目录名作为用户名(去除/home/前缀和末尾的斜杠) username="${user_dir%/}" username="${username##*/}" existing_users+=("$username") done # 用关联数组存储合法用户,快速判断用户是否合法 declare -A valid_users echo "Start execution of user-check.sh" while read -r line; do # 分割server.info的行数据:拆分出服务器IP、包类型,剩余部分为用户列表 IFS=',' read -r server_ip package_type user_list <<< "$line" # 将用户列表拆分为数组 IFS=',' read -r -a users_array <<< "$user_list" echo "$server_ip $package_type ${users_array[*]}" if [[ "$public_ip" == "$server_ip" ]]; then # 先验证合法用户是否存在于/home(保留原需求的正向检查) for user in "${users_array[@]}"; do valid_users["$user"]=1 if [[ " ${existing_users[*]} " =~ " $user " ]]; then echo "$user is valid and should be present in server $server_ip" else echo "$user should be created and is missing from server $server_ip" fi done # 核心新增:遍历现有用户,检查是否在合法列表中(反向检查) echo -e "\n=== Checking for invalid users in /home ===" for user in "${existing_users[@]}"; do if [[ -z ${valid_users["$user"]} ]]; then echo "$user is INVALID and should be deleted from server $server_ip" fi done fi done < server.info
关键改动说明
- 修正数组赋值逻辑:原脚本中
FILELIST[${#FILELIST[@]}+1]的索引计算错误,改用+=语法直接追加元素,更简洁可靠。 - 使用关联数组优化检查效率:用
valid_users关联数组存储合法用户,避免字符串匹配的潜在误差(比如用户名含空格的场景),判断存在性更快。 - 新增反向检查逻辑:遍历/home下所有用户,逐个验证是否属于合法列表,输出无效用户信息,完全匹配你的需求。
- 优化行分割逻辑:针对
server.info的格式,拆分出IP、包类型后再处理用户列表,避免原脚本中用户列表分割不彻底的问题。
预期运行效果
执行后会新增无效用户的检测输出:
Start execution of user-check.sh 104.248.245.89 rpm auditor igor.test ivan.test michael.test vova.test testbot auditor is valid and should be present in server 104.248.245.89 igor.test is valid and should be present in server 104.248.245.89 ivan.test is valid and should be present in server 104.248.245.89 michael.test is valid and should be present in server 104.248.245.89 vova.test is valid and should be present in server 104.248.245.89 testbot is valid and should be present in server 104.248.245.89 === Checking for invalid users in /home === ruslan.test is INVALID and should be deleted from server 104.248.245.89
内容的提问来源于stack exchange,提问作者Ruslan Pylypiuk
相关产品推荐
相关产品推荐

