dsl-checker/ipch.py

52 lines
1.4 KiB
Python
Raw Permalink Normal View History

2019-03-24 16:16:11 +01:00
#!/usr/bin/env python3
import requests
import mysql.connector
import datetime
import configparser
import sys
2019-03-24 16:16:11 +01:00
# Configuration
cfg = configparser.ConfigParser()
with open('config.ini', 'r') as f:
cfg.read_file(f)
DYN_CFG = cfg['dyndns']
IPCH_TABLE_CMD = """CREATE TABLE IF NOT EXISTS ipch (
time DATETIME,
status NATIONAL CHARACTER VARYING(8),
ip NATIONAL CHARACTER VARYING(15)
);
"""
for s in 'user', 'password', 'url':
if s not in DYN_CFG:
print(f'{s} missing. Please add the {s} property to your config.ini\'s [dyndns] section.')
exit(1)
DB_CONFIG = {k: v for k, v in cfg['db'].items() if k in ['user', 'password', 'host', 'database']}
result = requests.get(DYN_CFG['url'], auth=(DYN_CFG['user'], DYN_CFG['password']))
2019-03-24 16:16:11 +01:00
s = result.content.decode("unicode_escape").rstrip('\n').split(' ')
cx = mysql.connector.connect(**DB_CONFIG)
c = cx.cursor()
if s[0] in ['nochg', 'good']:
data = (datetime.datetime.now(), s[0], s[1])
elif s[0] == 'badauth':
exit('Bad DynDNS authentication provided. Please check the [dyndns] section in config.ini.')
elif s[0] == 'nohost':
exit('The server says this host does not exist.')
else:
print(f'status unknown: {s[0]}', file=sys.stderr)
data = (datetime.datetime.now(), s[0], None)
2019-03-24 16:16:11 +01:00
try:
c.execute(IPCH_TABLE_CMD)
c.execute('INSERT INTO ipch (time, status, ip) values (%s, %s, %s)', data)
2019-03-24 16:16:11 +01:00
cx.commit()
except:
cx.rollback()
raise
c.close()