ダイナミック取得ベリーパイの変動外網ip


ip変更時メール通知
このディレクトリの下に/home/configを作成する.pyメールボックス情報の構成
#!/usr/bin/env python
#-*-coding:utf-8-*-
smtpServer='smtp.126.com' #       smtp     
smtpPort='25' #       smtp       
smtpUser='[email protected]' #       
smtpPwd='xxxx' #        ,    X   ,       
sendTo='[email protected]' #      

このディレクトリの下に/home/sendIPを作成します.pyスクリプトは送信をチェックします.そして/etc/rc.localに次の行/usr/bin/python/home/sendIPを加える.py起動時の実行コードは以下の通りです.
#!/usr/bin/env python
#-*-coding:utf-8-*-
import smtplib,config,email,sys,socket,threading
from email.Message import Message
import re,urllib2

class Getmyip:
        def getip(self):
                try:
                        myip = self.visit("http://www.whereismyip.com/")
#                   return myip
                except:
                        try:
                                myip = self.visit("http://www.bliao.com/ip.phtml")
#                           return myip
                        except:
                                try:
                                        myip = self.visit("http://www.whereismyip.com/")
#                                   return myip
                                except:
                                        myip = "So sorry!!!"
                return myip

        def visit(self,url):
                opener = urllib2.urlopen(url)
                if url == opener.geturl():
                        str = opener.read()
#                        print str
                        asd=re.search('\d+\.\d+\.\d+\.\d+',str).group(0)
                        return asd

def connect():
        try:
                server=smtplib.SMTP(config.smtpServer,config.smtpPort)
                server.ehlo()
                server.login(config.smtpUser,config.smtpPwd)
                return server
        except Exception:
                print 'connect smtp server failed!'

def sendmessage(server,to,subj,content):
        msg = Message()
        msg['Mime-Version']='1.0'
        msg['From']        = config.smtpUser
        msg['To']          = to
        msg['Subject'] = subj
        msg.set_payload(content)
        try:        
                failed = server.sendmail(config.smtpUser,to,str(msg))
        except Exception ,ex:
                print Exception,ex
                print 'Error - send failed'
        else:
                print 'send succeed!'

#  10s    IP,            
def checkIP():
        global text
        #getmyip = Getmyip()
        print text
        ipnow=getmyip.getip()
        print ipnow
        if  text!=ipnow:
                text=ipnow
                server=connect()
                sendmessage(server,to,subj,text)
        t = threading.Timer(600.0, checkIP)
        t.start()

if __name__=="__main__":
        getmyip = Getmyip()
        to=config.sendTo
        subj='ip changed' 
        text = getmyip.getip() #        IP 
        server=connect()
        sendmessage(server,to,subj,text)
        t = threading.Timer(600.0, checkIP)
        t.start()