Bash

腳本來查詢 MX 記錄的域列表,然後查詢 IP 地址的答案?

  • January 28, 2021

我需要從域列表中檢查郵件伺服器的 IP 地址,以查看它們是否與某個 IP 地址匹配。具體來說:

  1. 建構我要查詢的域列表
  2. 探勘每個域的 MX 記錄
  3. 探勘 IP 地址的 MX 記錄查詢結果的 A 記錄
  4. 如果任何 IP 與特定 IP 匹配,則返回“是”或“否”

我被困在第3步。

到目前為止,這是我腳本的相關部分

#!/bin/bash
# Bulk DNS Lookup
#
# File name/path of domain list:
domain_list='domains.txt' # One FQDN per line in file.

# File name of output text
output='ns_output.txt'

# Clears previous output
> $output

# IP address of the nameserver used for lookups:
ns_ip='192.168.250.67'
#
# Seconds to wait between lookups:
loop_wait='1' # Is set to 1 second.

for domain in `cat $domain_list` # Start looping through domains
do
   echo $domain "Mail servers" >> $output
   MX=$(dig @$ns_ip MX $domain +short) #query MX records from domain list and store it as varial $MX
   echo $MX >> $output;
   echo " " >> $output
   echo " " >> $output
   sleep $loop_wait # Pause before the next lookup to avoid flooding NS
done;

問題是我不知道如何將輸出轉換為變數,以便我可以執行另一個 A 記錄探勘。

c****s.com Name Servers
c****s.com. 14400 IN NS ns1.a****l.com. yes

c****s.com Mail servers
10 mail.c*****s.com. 20 mail2.c****s.com.

有沒有辦法查詢結果以返回從 MX 查詢返回的每個伺服器的 IP 地址?

編輯:我嘗試了每個人的答案,雖然他們都可以工作,但我發現 Gilles 最容易實現。這是我的最終程式碼:

   MX=$(dig @$ns_ip MX $domain +short) #query MX records from domain list and store it as variable $MX
   arr=( $MX ) #creates array variable for the MX record answers
   for ((i=1; i<${#arr[@]}; i+=2)); #since MX records have multiple answers, for loop goes through each answer
     do
       echo ${arr[i]} >> $output; #outputs each A record from above MX dig
       dig A +short "${arr[i]}" >> $output #queries A record for IP and writes answer
       MX_IP=$(dig A +short "${arr[i]}") #sets IP address from the dig to variable MX_IP
       if [[ "${arr[i]}" == *"a****d"* ]] #if the mail server host name contains a***d
         then
           echo "yes - spam filter" >> $output
         else
         if [[ $MX_IP == $CHECK_IP ]] #if not, check to see if the mail server's IP matches ours.
           then
             echo "yes - mail server"  >> $output
           else
             echo "no" >> $output
         fi
       fi

這是範例輸出(以偏執狂審查的域和 IP):

a***l.com Mail servers  lastmx.a****d.net. 
85.x.x.x 
209.x.x.x
95.x.x.x yes - spamfilter
....
mail.b***c.com.
72.x.x.x yes - mail server

backup.b***c.com.
50.x.x.x no

mail2.b***c.com.
50.x.x.x no

要走的路:

arr=( $MX )
for ((i=1; i<${#arr[@]}; i+=2)); do dig A +short "${arr[i]}"; done

 輸出:

108.177.15.26
209.85.233.27
172.253.118.27
108.177.97.26
173.194.202.26

以下命令將僅返回主機名列表(它會刪除權重和尾隨句點):

MX_HOSTS=$(dig MX google.com +short | sed 's/.* \(.*\)\.$/\1/')

然後,您可以對其執行 for 循環:

for h in ${MX_HOSTS} ; do
 MX_IPS="${MX_IPS} $(dig $h +short)"
done

並測試:

[[ "${MX_IPS}" =~ "${CHECK_IP}" ]] && echo "yes" || echo "no"

引用自:https://unix.stackexchange.com/questions/557548