树莓派+Prowl 监控PPPOE的IP地址变更
前段时间买的树莓派用着一直很爽,不爽的动态DNS解析,这两天总是出现莫名其妙的问题。经过仔细排查与联系客服后,最终还是解决了问题。
但是在解决问题的过程中,因为白天要到公司,所以当DNS动态解析失败时,无法准确获得家里的公网IP地址。也就是说当DNS动态解析失败时,根本就无法从公网对家里的TP-LINK路由器进行远程管理。
So,动手写了下面这个脚本,与crontab来配合执行,实现了PPPOE拨号宽带IP地址变更后,将新IP地址推送到Prowl手机客户端的功能(有了家里路由器的新IP,就可以直接进行远程管理了)。
Prowl是一个Growl的iOS客户端,允许用户从Mac、Windows或其他应用程序向iPhone、iPad或iPod Touch进行消息推送。
脚本中未对各类型的异常进行处理,如有需要,请自行添加。另外,如果不希望使用Prowl,也可以稍微改一下脚本,向支持Push mail的邮箱中发送邮件,也可以达到实时提醒的目的。
代码 ip_push.py:
#!/usr/bin/env python #coding=utf-8 import os, urllib, urllib2, cPickle prowl_api_key = 'your_prowl_api_key' strfilepath = os.path.dirname(os.path.realpath(__file__)) def get_ip(): _api_addr = 'http://pv.sohu.com/cityjson?ie=utf-8' _request = urllib2.Request(_api_addr) _res = urllib2.urlopen(_request).readline() exec(_res[4:]) return returnCitySN['cip'] def push_message(content, url): _api_addr = 'http://api.prowlapp.com/publicapi/add' _data = { 'apikey':prowl_api_key, 'application':'服务器IP地址更新', 'url':url, 'description':content, } _request = urllib2.Request(_api_addr) return urllib2.urlopen(_request, urllib.urlencode(_data)).read() def check_up_update(ip_address): storefile = strfilepath + '/ip_push.dat' if os.path.exists(storefile): fp = open(storefile) old_ip_address = cPickle.load(fp) fp.close() else: old_ip_address = '' if ip_address != old_ip_address: fp = open(storefile, 'w') cPickle.dump(ip_address, fp) fp.close() return True else: return False if __name__ == '__main__': ip_address = get_ip() if check_up_update(ip_address): message = '新的服务器IP地址更新为:' + ip_address url = 'http://' + ip_address + ':8080' print(message) print(push_message(message, url))
在树莓派的系统环境中编辑crontab:
crontab -e
添加下面行,每分钟执行脚本一次(依个人情况需要):
*/1 * * * * /scripts/ip_push.py