How To Use Python To Get Your External IP
By Daniel Miessler on July 15th, 2005: Tagged as Linux | Programming | Python
I was having some issues involving losing connectivity to a system of mine due to a dynamic IP. Normally one would just use a dynamic DNS service to solve the problem, but in this case there were complications that kept that from being a solution.
So that’s where Python comes in. I threw this “solution” (It’s in quotes for a reason) together, which goes to my own rudimentary IP-finding site, pulls my address, and returns it to me. Here’s the code:
#!/usr/bin/env python
A small application that will pull your external IP address
and return it.
import urllib import re
Pull the website and read it
site = urllib.urlopen("http://dmiessler.com/ip").read()
Grab the IP out of it as a list with one item in it (re.findall returns a list)
grab = re.findall('\d{2,3}.\d{2,3}.\d{2,3}.\d{2,3}',site)
Define the address as the first item in the list (in this case the only item)
address = grab[0]
Return the address
print address
So then in cron.hourly (Gentoo) I can do:
/usr/bin/address | mailx -s "New IP" me@mysecondaddress &> /etc/cron_output
It’s ghetto, but it works. :)