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

编写Bash脚本提取文件中域名IP时程序卡顿,求问题排查

Bash脚本卡顿无响应:文件域名解析IP问题排查

我编写了一段Bash脚本,用于检查文件中的域名并打印对应IP地址,但传入包含域名的文件运行时,程序出现卡顿且无响应。脚本代码如下:

is_valid_domain() {
    local domain="$1"
    if host "$domain" &> /dev/null; then
        return 0
    else
        return 1
    fi
}


if [ "$#" -eq 1 ]; then
    filename="$1"
    # Check if the file exists
    if [ ! -f "$filename" ]; then
        echo "Error: File '$filename' not found."
        exit 1
    fi
    
    #if the file exists
    #Process each domain in the file
    while IFS= read -r domain_name;  do
        if  is_valid_domain "$domain_name"; then
echo -e "Domain name: $domain_name\nIP Address: $(host "$domain_name" | awk '/has address/ {print $4}')"
        else
            echo "No domain names found"
        fi
    done < "$filename"

问题原因分析

  1. DNS查询无超时限制:默认host命令的DNS查询超时时间很长,遇到无效域名或DNS服务器响应缓慢时,会导致脚本长时间卡住。
  2. 重复DNS查询:is_valid_domain函数调用一次host验证域名,输出IP时又再次调用host,重复查询既浪费资源又增加卡顿概率。
  3. 错误提示逻辑错误:每遇到一个无效域名就输出"No domain names found",不符合预期且干扰输出,同时没有处理空行等无效输入。

修复后的脚本

is_valid_domain() {
    local domain="$1"
    # 设置2秒超时,同时捕获查询输出
    local host_output=$(host -W 2 "$domain" 2>&1)
    # 检查是否存在IP记录
    if echo "$host_output" | grep -q "has address"; then
        # 提取并返回IP地址
        echo "$host_output" | awk '/has address/ {print $4}'
        return 0
    else
        return 1
    fi
}

# 检查参数数量
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

filename="$1"
# 检查文件是否存在
if [ ! -f "$filename" ]; then
    echo "Error: File '$filename' not found."
    exit 1
fi

valid_count=0

while IFS= read -r domain_name; do
    # 跳过空行
    [[ -z "$domain_name" ]] && continue
    
    # 调用函数获取IP并验证
    ip=$(is_valid_domain "$domain_name")
    if [ $? -eq 0 ]; then
        echo -e "Domain name: $domain_name\nIP Address: $ip"
        ((valid_count++))
    else
        echo "Invalid domain or no IP found: $domain_name"
    fi
done < "$filename"

# 全局提示:如果没有有效域名
if [ $valid_count -eq 0 ]; then
    echo "No valid domain names found in the file."
fi

关键修改点

  • 添加DNS查询超时:使用host -W 2设置2秒超时,避免脚本因DNS查询卡住。
  • 合并查询操作:一次host查询同时完成域名验证和IP提取,减少重复操作。
  • 优化输入处理:跳过空行,避免无效查询。
  • 修正提示逻辑:针对单个无效域名给出准确提示,处理完所有行后再提示全局结果。
  • 增加参数校验:提示用户正确的脚本使用方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:17:49