At home, my boxes are connected to internet by Beijing ADSL.
when connected, Beijing ADSL gives me a dynamic ip and it changes about every 24 hours.
Before I get the dynamic ip by a service provided by oray.net.
However recently the service is broken.
So I have to write a python script to check the dynamic ip from my tp-link router every 3 minutes and if it changed, emails the new dynamic ip to my gmail.
I also write a bash script to run the above python script at boot on my gentoo linux.
The python script:
#!/usr/bin/python import urllib import urllib2 import libgmail import cookielib import sys import re import base64 import socket import time from urlparse import urlparse nowip='' logfile=open('/var/log/ipsender.log','w') def log(s): now=time.strftime('%Y-%m-%d %X') logfile.write('%s %sn'%(now,s)) logfile.flush() def gmailsender(to_addr,subject,msg): username='xxx@gmail.com' password='xxx' ga=libgmail.GmailAccount(username,password) ga.login() gmsg=libgmail.GmailComposedMessage(to_addr,subject,msg) ga.sendMessage(gmsg) def check(): global nowip timeout=10 socket.setdefaulttimeout(timeout) username = 'admin' password = 'xxx' try: theurl='http://192.168.1.1/userRpm/StatusRpm.htm' req = urllib2.Request(theurl) base64string = base64.encodestring('%s:%s' % (username, password))[:-1] authheader = "Basic %s" % base64string req.add_header("Authorization", authheader) handle = urllib2.urlopen(req) str=handle.read() ss='var wanPara = new Array' start=str.index(ss)+ss.__len__() end=str.index(';',start) s2=str[start:end] log(s2) t=eval(s2) log(t[2]) handle.close() if nowip!=t[2]: nowip=t[2] gmailsender('mygmail@gmail.com','ddnsip===%s'%nowip,s2) log('send %s successfully.'%nowip) else: log('ddnsip remains %s.'%nowip) except: log('Unexpected error:', sys.exc_info()[0]) def main(): while True: check() time.sleep(3*60) main()
The bash script put in /etc/init.d/:
#!/sbin/runscript # Copyright 1999-2004 Gentoo Foundation start() { ebegin "Starting ipsender" nohup python /home/zeaster/amp/ipsender.py >> /var/log/ipsender-nohup.log& eend $? } stop() { ebegin "Stopping ipsender unsuccessfully" eend $? }
No Comment Received
Leave A Reply