Created
February 13, 2014 09:23
-
-
Save FLamparski/8972198 to your computer and use it in GitHub Desktop.
For those who don't want to or can't use dynamic DNS but need to be able to access their network from anywhere
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from time import sleep | |
from urllib.parse import urlencode | |
import subprocess as sp | |
import httplib2 | |
import json | |
import sys | |
import re | |
IP_COMMAND = """curl -s http://checkip.dyndns.org | sed 's/[a-zA-Z/<> :]//g'""" | |
PUSHBULLET_API_KEY = # Your Pushbullet key here | |
IP_REGEX = re.compile("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") | |
devices = None | |
current_ip = None | |
http = httplib2.Http(".cache") | |
http.add_credentials(PUSHBULLET_API_KEY, None) | |
def valid_ip(candidate): | |
if IP_REGEX.match(candidate): | |
return True | |
else: | |
return False | |
def pusbullet_devices(): | |
req, body = http.request("https://api.pushbullet.com/api/devices") | |
return json.loads(body.decode('utf-8'))['devices'] | |
def check_ip(): | |
ipstr = sp.check_output(IP_COMMAND, shell=True) | |
ipstr = ipstr.decode("ascii")[:-2] | |
return ipstr | |
def upload_ip(): | |
global devices | |
for device in devices: | |
body = { "type": "note", "title": "[auto] My Public IP", | |
"body": current_ip, "device_iden": device["iden"]} | |
body = urlencode(body) | |
req, respbody = http.request("https://api.pushbullet.com/api/pushes", 'POST', body=body) | |
if(int(req['status']) == 400): | |
raise AttributeError("Bad Request returned by server") | |
elif(int(req['status']) == 401 or int(req['status']) == 403): | |
raise PermissionError("No or invalid API key") | |
elif(int(req['status']) >= 500): | |
raise RuntimeError("Pushbullet returned HTTP code {}".format(req['status'])) | |
def run_once(): | |
global current_ip | |
new_ip = check_ip() | |
if not current_ip == new_ip: | |
if not valid_ip(new_ip): | |
run_once() | |
else: | |
print("New IP detected: {}.".format(new_ip)) | |
current_ip = new_ip | |
upload_ip() | |
def setup(): | |
global devices | |
devices = pusbullet_devices() | |
global current_ip | |
current_ip = "0.0.0.0" | |
if __name__ == '__main__': | |
setup() | |
while(True): | |
try: | |
run_once() | |
sleep(60) | |
except KeyboardInterrupt: | |
print("Exitting.") | |
sys.exit(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment