#! /usr/bin/env python import sys from subprocess import Popen, PIPE import syslog import mysql.connector mysql_opts = { "host": "localhost", "user": "dyndns_insert", "password": "your_password", "db": "dyndns" } # file to store new ip proxy_pass = "/var/cache/nginx/proxy_pass" # remote open port port = 443 def insert_into_database(ip): try: ip = {"ip": ip} insert_ip = ("INSERT INTO ip (ipv4) VALUES (%(ip)s)") connection = mysql.connector.connect(**mysql_opts) cursor = connection.cursor() cursor.execute(insert_ip, (ip)) connection.commit() cursor.close() connection.close() syslog.syslog(syslog.LOG_DEBUG, "Update database") except mysql.connector.errors.Error as error: syslog.syslog(syslog.LOG_ERR, "%s" % error) def get_ip(): lines = "" for line in sys.stdin: if line.startswith("Subject"): try: ip = line.split(" ")[2].strip() syslog.syslog(syslog.LOG_DEBUG, "Get new ip: %s" % ip) return ip except IndexError as error: syslog.syslog(syslog.LOG_ERR, "Missing ip in subject") def update_proxy_pass(ip): with open(proxy_pass, "w") as fd: fd.write("proxy_pass https://%s:%d;" % (ip, port)) return True def reload_nginx(): cmd = ["sudo", "/etc/init.d/nginx", "reload"] process = Popen(cmd, stdout=PIPE, stderr=PIPE) status, error = process.communicate() if error: syslog.syslog(syslog.LOG_ERR, error) if status: syslog.syslog(syslog.LOG_DEBUG, status) if __name__ == "__main__": ip = get_ip() if ip: insert_into_database(ip) if update_proxy_pass(ip): reload_nginx()