树莓派动态IP更新器

这是一个python3的脚本,每隔10分钟监控一次IP地址,如果发生变化则会通过AutoRemote消息通知你。 关于AutoRemote的使用可参考这里

这里推荐使用ipgetter来获取外网IP,地址为https://github.com/phoemur/ipgetter

安装ipgetter

sudo apt-get install python3 pip
sudo pip3 install ipgetter

你可以从以下地址获取每个通知设备的AutoRemote所需google key

​ http://autoremotejoaomgcd.appspot.com/?key=[it’s the part that is here]

以下为python3脚本:

import ipgetter
import urllib.request
import requests

currentIP = ipgetter.myip()
#AutoRemote function to send a notification YOUR_KEY goes here
def sendAR(x):
	AR_key = 'YOUR_KEY'
	AR_url = 'http://autoremotejoaomgcd.appspot.com/sendmessage?key='+ AR_key +'&message=IP%20'
	message = AR_url + x
	response = urllib.request.urlopen(message).read()
	print(x)	
#check the internet  and check if previous file is present
try:
	requests.get('http://www.google.com')
	print('Internet present')
	IPfile = open('ipfile.txt', 'r')
	lastIP = IPfile.read()	
	if lastIP == currentIP:
		print('No changes last IP: ' + lastIP + ' current IP: ' + currentIP)
	else:
		with open('ipfile.txt', 'w+') as f:
			f.write(currentIP)
			f.close()
			sendAR(currentIP)
			print('IP updated')
#handle no file			
except IOError:
	#print(IOError)
	with open('ipfile.txt', 'w+') as f:
		IPfile = ipgetter.myip()
		f.write(IPfile)
		f.close()
		print('created file with current IP')
		sendAR(currentIP)
		quit()
#Handle no internet		
except requests.ConnectionError:
	quit()

运行脚本后,会监视ip变化,如果发生变化则通知最新ip,如果未发生变化则不通知。