Linux shell Script 获取域名IP对应关系

385人浏览   2024-05-24 12:02:44

需求:读取一个ip_list查看某个DNS的解析结果,如果解析的A记录发生变化,我这里用md5sum,告警或者发送通知

下面是一个事例

cat /tmp/a.txt
www.baidu.com 14.215.177.38 
www.sohu.com 119.96.200.204

生成的事例也就是扫描之后的一个结果

/tmp/b.txt
www.baidu.com 14.215.177.38
www.sohu.com 119.96.200.20

通过如下脚本来实现

check_domain.sh

#!/bin/bash
# define domain list
domain_ip=/tmp/a.txt
collect_ip=/tmp/b.txt
# Specify DNS server
dnsserver="119.29.29.29"
# function to get IP address
function get_ipaddr {
  local hostname=$1
  local query_type=A
  ip_address=""
    # use host command for DNS lookup operations
    host -t ${query_type}  "${hostname}" &>/dev/null ${dnsserver}
    if [ "$?" -eq "0" ]; then
      # get ip address
      ip_address="$(host -t ${query_type} "${hostname}" ${dnsserver}| awk '/has.*address/{print $NF; exit}')"
    else
        echo "############"
    fi
# display ip
    echo "$ip_address"
}

true > $collect_ip
#cat /home/lex/dns/a.txt| while IFS=" " read -r line;do domain_array+=("$line");done
domain_array=($(awk '{print$1}' < $domain_ip))
for ((i=0;i<${#domain_array[@]};i++))
do
    echo -e "\033[31m ${domain_array[$i]} \033[0m"
    #echo ${domain_array[$i]}
    get_ipaddr "${domain_array[$i]}"
    echo "${domain_array[$i]}" "$(get_ipaddr "${domain_array[$i]}")" >> $collect_ip
done
if [ $? -eq 0 ]
then
     echo "generate record successfully"
fi
echo "now compare file"
function checkfilesume() {
    local_file_sum=$(md5sum $domain_ip|cut -d" " -f1)
    gener_file_sum=$(md5sum $collect_ip|cut -d" " -f1)
    if [ "$local_file_sum" == "$gener_file_sum" ];then
        echo "checksum success"
    else
        echo "checksum failure"
    fi
}
checkfilesume

测试执行结果:当然可以根据个人的需求来修改就是了

  shell ./check_domain.sh
 www.baidu.com
14.215.177.38
 www.sohu.com
119.96.200.204
generate record successfully
now compare file
checksum success

过程中,比如我这里要过滤下,仅仅是公网IP,排除下私有IP地址如下,这个正则就可以过滤出来

cat /tmp/b.txt |grep -vP "(10.|192.168|172.1[6-9].|172.2[0-9].|172.3[01].).*"

当然获取DNS记录的办法有如下可以自己去探索:

nslookup

dig

等等都可以实现解析A记录

相关推荐