Skip to main content

Python & BASH Script to flag change of External IP address

This script reads the external IP address, stored in file ext_ip_add.txt (full path), then gets the new external IP address and compares the two, then overwrites previous stored address. Replace LT with proper less than sign and GT with greater than sign. Following cron job pipes output to a text to speech converter.

#!usr/bin/python
#
# Program gets your external IP address
#
# This program reads the title from
# myip.dk website and prints out from
# 12th char after <
#
# Prog checks for change in ip address
#
# The ip address is written to file
# ext_ip_add.txt (overwritten)
#
# Version 1.0 Geoff Robinson July 09

fileobject1=open('/home/geoff/python/ext_ip_add.txt','r')
oldipaddress = fileobject1.readline()
fileobject1.close


import urllib

url = urllib.URLopener()
resp = url.open('http://myip.dk')
html = resp.read()
start = html.find("LTtitleGT") + 12
end = html.find("LT/titleGT")


newipaddress = html[start:end].strip()

if newipaddress == oldipaddress:
print 'your external inter net address has not changed'
else:
print 'you have a new external inter net address, your'
print newipaddress

# This section writes the external
# IP address to ext_ip_add.txt file

fileobject=open('/home/geoff/python/ext_ip_add.txt','w')
fileobject.write(html[start:end])
fileobject.close()

OR (simpler bash script)
#!/bin/bash
#
#  Script to write external ip address to syslog.
#  Note this script passes environment variable
back to parent shell so run with cmd
#  . ./my_address.

#


IP_ADD=`/usr/bin/curl -s http://ip.nefsc.noaa.gov/ | /bin/grep -Eo "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+"`
NEW_IP=$IP_ADD
if [ $OLD_IP = $NEW_IP ]; then
   echo "no change - external ip is $IP_ADD" | logger
else
   echo " New ip address is $NEW_IP " | logger
   export OLD_IP=$NEW_IP
fi

Comments