I have this bash code:
#!/bin/bash
# Change to the script's directory
cd /var/www/html/fqdn || exit
# Input and output files
INPUT_FILE="fqdnlist.txt"
OUTPUT_FILE="resolvedfqdnlist.txt"
DNS_SERVERS=("8.8.8.8" "1.1.1.1")
# Function to resolve domains and write to output file
resolve_domains() {
local resolved_ips=()
# Check if the input file exists
if [[ ! -f "$INPUT_FILE" ]]; then
echo "Input file $INPUT_FILE does not exist."
exit 1
fi
echo "Reading domains from $INPUT_FILE..."
# Loop through each domain in the input file
while IFS= read -r domain || [[ -n "$domain" ]]; do
echo "Resolving domain: $domain"
# Initialize a variable to track if a valid IP is found
local valid_ip_found=false
# Try each DNS server for resolution
for dns_server in "${DNS_SERVERS[@]}"; do
echo "Using DNS server: $dns_server"
# Run dig and capture the full output
dig_output=$(dig @"$dns_server" "$domain" +short)
echo "Raw dig output: $dig_output"
# Extract the IP addresses
ip=$dig_output
# If we get a valid IP address, break out of the loop
if [[ -n "$ip" && "$ip" =~ ^[0-9]+.[0-9]+.[0-9]+.[0-9]+$ ]]; then
echo "Resolved IP for $domain using $dns_server: $ip"
resolved_ips+=("$ip")
valid_ip_found=true
break # Stop trying other DNS servers if we get a valid IP
fi
done
# If no valid IP is found after checking all DNS servers
if [[ "$valid_ip_found" == false ]]; then
echo "No valid IP found for $domain"
fi
done < "$INPUT_FILE"
# Remove duplicates and write the results to the output file
if [[ ${#resolved_ips[@]} -gt 0 ]]; then
printf "%sn" "${resolved_ips[@]}" | sort -u > "$OUTPUT_FILE"
echo "Resolved domains and updated $OUTPUT_FILE"
else
echo "No valid IPs were resolved. Output file remains empty."
fi
}
# Main loop to run every 5 minutes and flush every 24 hours
while true; do
resolve_domains
sleep 300 # Run every 5 minutes
# Check if 24 hours have passed and flush the output file
if [[ $(date +%H:%M) == "00:00" ]]; then
> "$OUTPUT_FILE" # Flush the file
echo "Flushed the output file at midnight"
fi
done
and for some reason which I am not able to find out, the output file is empty.
I have tested the dig command manually and it works fine.
Runnig the script is giving this output:
root@IP-Threat:/var/www/html/fqdn# ./fqdnscript.sh
Reading domains from fqdnlist.txt...
Resolving domain: tls-ech.dev
Using DNS server: 8.8.8.8
Raw dig output:
Using DNS server: 1.1.1.1
Raw dig output:
No valid IP found for tls-ech.dev
Resolving domain: cnn.com
Using DNS server: 8.8.8.8
Raw dig output:
Using DNS server: 1.1.1.1
Raw dig output:
No valid IP found for cnn.com
Resolving domain: google.com
Using DNS server: 8.8.8.8
Raw dig output:
Using DNS server: 1.1.1.1
Raw dig output:
No valid IP found for google.com
No valid IPs were resolved. Output file remains empty.