Skip to content

Automating IP Address Tracking for HTTP Links: A Simple Shell Script

We wanted to keep track of an HTTP link and receive email alerts when there were any changes to its IP addresses. To accomplish this, we developed a shell script that compares the current list of IP addresses with the previous ones saved in a text file, current_ips.txt, on our Linux server.

Since the HTTP link is load balanced and has multiple (4) IP addresses, we used an array function in the shell script to compare each IP address one-by-one. The current_ips.txt file contains a pool of IP addresses, with one IP address per line.

By using this script, we can ensure that any changes to the IP addresses associated with the HTTP link are immediately flagged, and our team is notified via email. This helps us to stay on top of any changes and quickly take appropriate actions if necessary.

#!/bin/bash

# Define the URL of the load-balanced HTTP link
url="<PUT URL, example: google.com"

# Define the filename where the current IP addresses are stored
filename="current_ips.txt"
newipfilename="new_ips.txt"
maillist="<PUT YOUR EMAIL>"

# Retrieve the current IP addresses of the URL
current_ips=$(nslookup $url | grep Address | awk '{print $2}')
echo "PRINT CURRENT IP"
echo $current_ips
echo ""
# Read the saved IP addresses from the file
echo "PRINT SAVED IPS"
saved_ips=$(cat $filename)
echo $saved_ips
echo ""

# Split the current IP addresses into an array
current_ips_array=($(echo "$current_ips" | awk '{print $1}'))

# Split the saved IP addresses into an array
saved_ips_array=($(echo "$saved_ips"))

# Flag to check if any new IP addresses are found
new_ips_found=0
rm -rf $newipfilename

# Loop through each element in array1
for current_ip in "${current_ips_array[@]}"; do

# Check if the element is not in array2
if ! [[ "${saved_ips_array[@]}" =~ "${current_ip}" ]]; then
echo ${current_ip}>>$newipfilename
# Increase the counter
new_ips_found=$((new_ips_found+1))
fi
done
echo "number of new IP"
echo $new_ips_found
new_ips=$(cat new_ips.txt)


# Send an email if IP changed

if [[ "$new_ips_found" -gt 0 ]]; then

# Remove the comment below to update the file with the new IP addresses if you want.
# echo "$current_ips" > $filename

# Send an email notification
echo -e "Below $new_ips_found IP addresses(s) of $url have changed:\n $new_ips \n \n Current IP addresses for this URLs are:\n \n $current_ips \n \n " | mail -s "IP addresses of $url have changed" $maillist
fi

 

Brijesh Gogia
Leave a Reply