Linux终端手动枚举子域名:脚本输出为空求助
子域名枚举脚本输出为空的排查与解决
问题背景
在Linux终端通过带通配符过滤方式手动枚举子域名,编写的Shell脚本逻辑看似合理,但输出文件始终为空。已确认字典文件格式正确。
用户编写的脚本如下:
#!/bin/bash WORDLIST="dictionary2.txt" OUTPUT_FILE="found_subdomains.txt" TXT_FILE="txt_records.txt" # Clear output files > "$OUTPUT_FILE" > "$TXT_FILE" # Detect wildcard IP wildcard_ip=$(dig +short thisshouldnotexist123456.penconsultants.com | tail -n1) echo "[*] Wildcard IP detected: $wildcard_ip" echo "[*] Running parallel subdomain resolution..." # Main logic using xargs and inline Bash cat "$WORDLIST" | xargs -P 20 -I{} bash -c ' sub="$1" fqdn="${sub}.penconsultants.com" ip=$(dig +short "$fqdn" | tail -n1) if [ -n "$ip" ] && [ "$ip" != "'"$wildcard_ip"'" ]; then echo "$fqdn -> $ip" >> "'"$OUTPUT_FILE"'" txt=$(dig +short TXT "$fqdn") if [ -n "$txt" ]; then { echo "===== $fqdn TXT Records =====" echo "$txt" echo "" } >> "'"$TXT_FILE"'" fi fi ' _ {} echo "[*] Finished!" echo " → Found subdomains: $OUTPUT_FILE" echo " → TXT records: $TXT_FILE"
排查与修复方案
1. 修正通配符IP判断逻辑
如果目标域没有配置通配符解析,thisshouldnotexist123456.penconsultants.com会返回空,此时wildcard_ip为空值,原脚本中[ "$ip" != "" ]的条件会过滤掉所有有效IP,导致输出为空。
修复方式:先判断通配符IP是否存在,不存在则跳过过滤逻辑:
# Detect wildcard IP wildcard_ip=$(dig +short thisshouldnotexist123456.penconsultants.com | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -n1) echo "[*] Wildcard IP detected: $wildcard_ip" echo "[*] Running parallel subdomain resolution..." # Main logic using xargs and inline Bash export OUTPUT_FILE TXT_FILE wildcard_ip cat "$WORDLIST" | xargs -P 20 -I{} bash -c ' sub="$1" fqdn="${sub}.penconsultants.com" ip=$(dig +short "$fqdn" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -n1) if [ -n "$ip" ]; then # 仅当通配符IP存在时才做过滤 if [ -z "$wildcard_ip" ] || [ "$ip" != "$wildcard_ip" ]; then echo "$fqdn -> $ip" >> "$OUTPUT_FILE" txt=$(dig +short TXT "$fqdn") if [ -n "$txt" ]; then { echo "===== $fqdn TXT Records =====" echo "$txt" echo "" } >> "$TXT_FILE" fi fi fi ' _ {}
2. 优化dig输出过滤
dig +short可能返回CNAME记录或多个IP,直接用tail -n1可能取到无效值。改用正则过滤出纯IP地址,确保比对准确性:
ip=$(dig +short "$fqdn" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -n1)
3. 简化变量传递
原脚本中内联Bash的变量嵌套引号容易出错,改用export传递环境变量,避免转义问题:
export OUTPUT_FILE TXT_FILE wildcard_ip # 内联Bash中直接使用$OUTPUT_FILE等变量即可
4. 添加调试输出(可选)
临时添加调试信息,查看每个子域名的解析结果,快速定位问题:
ip=$(dig +short "$fqdn" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -n1) echo "Debug: $fqdn -> $ip" # 调试完成后可删除
内容的提问来源于stack exchange,提问作者Julius Santiago
相关产品推荐
相关产品推荐

