動態獲取樹莓派的變動外網ip
阿新 • • 發佈:2019-01-03
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()