Skip to content

Instantly share code, notes, and snippets.

@FLamparski
Created February 13, 2014 09:23
Show Gist options
  • Save FLamparski/8972198 to your computer and use it in GitHub Desktop.
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
#!/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