Recently I needed to incorporate in a script my current external IP address, that is the address the internet knows in order to reach my web server. The easiest way I found was to fetch the web page http://checkip.dyndns.org/ using a command like:
lynx -dump http://checkip.dyndns.org/
But, since I have a dynamic IP, I thought that it was not a good solution to fetch the above page every 10 minutes. After all, my router knows its IP before everyone else (ok, besides my ISP), so it is better just to ask the router.
Actually this is a nice thought, but the router wants the user to be authorized to get the information. So, after some searching, I found the following solution from the example scripts of Python’s pexpect documentation (the file I used in my system is /usr/share/doc/python-pexpect/examples/ftp.py). All I had to do was to adjust it to my problem. The final script is this:
child = pexpect.spawn('telnet router')
child.sendline('get ip address')
child.expect('nr([0-9]+.[0-9]+.[0-9]+.[0-9]+) *[^ ]+ *ppp-0')
ip = child.match.group(1)
print "Current IP Address:", ip
# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
child.sendline('exit') # Try to ask ftp child to exit.
# Print the final state of the child. Normally isalive() should be FALSE.
print 'Child did not exit gracefully.'
Of course, for another router, the prompts and the commands might be different, so the above inputs/outputs will have to be adjusted as well.
Visit The Light of the LAMP blog for more…