Grep IPs from DNS ping

#!/bin/bash

# Input file containing hostnames
input_file="hostnames.txt"

# Output file to store ping results
output_file="ping_results.txt"

# Function to ping a host and get its IP address
ping_host() {
    host="$1"
    ip=$(ping -c 1 "$host" | grep -oP '(\d+\.){3}\d+' | head -n 1)
    echo "$host $ip"
}

# Loop through each host in the input file
while IFS= read -r host; do
    # Skip empty lines
    if [ -z "$host" ]; then
        continue
    fi
    
    # Call ping_host function for each host
    ping_host "$host"
done < "$input_file" > "$output_file"

echo "Ping results saved to $output_file"

Last updated