Complete re-write, BREAKING

This re-write uses different table names. Beware.
This commit is contained in:
Christopher Teutsch 2019-10-11 21:56:16 +02:00
parent 23d826c5c9
commit 617ba03ed3
Signed by: iwonder
GPG Key ID: 0EE33D788D50130D
6 changed files with 124 additions and 84 deletions

View File

@ -1,12 +1,13 @@
# Speed-test and IP change scripts # Monitoring scripts for IP changes and connection speed
## Requirements ## Requirements
* Python 3 with modules `mysql-connector-python` and `speedtest-cli` * Python 3 with the modules from `requirements.txt`
* A SQL database (MariaDB is recommended) * A MySQL database (I use MariaDB)
* A DynDNS server that supports the [Remote Access Update API](https://help.dyn.com/remote-access-api/)
## Usage ## Usage
1. Create tables in the database using `tables.sql` 1. Configure the two scripts using `config.ini`
2. Configure the scripts in the fields provided 1. Set cronjobs for the two scripts. I currently run them every 15 minutes.
3. Add cron-jobs for the scripts. I currently use an interval of 15 seconds

11
config.ini Normal file
View File

@ -0,0 +1,11 @@
[db]
user =
password =
host =
database =
[dyndns]
user =
password =
url =

44
ipch.py
View File

@ -2,23 +2,47 @@
import requests import requests
import mysql.connector import mysql.connector
import datetime import datetime
import configparser
import sys
# Configuration # Configuration
DYNDNS_AUTH = {'user':'','pass':''} cfg = configparser.ConfigParser()
DYNDNS_URL = '' with open('config.ini', 'r') as f:
DB_CONFIG = { cfg.read_file(f)
'user': '',
'password': '', DYN_CFG = cfg['dyndns']
'host': '',
'db': '' IPCH_TABLE_CMD = """CREATE TABLE IF NOT EXISTS ipch (
} time DATETIME,
result = requests.get(DYNDNS_URL, auth=(DYNDNS_AUTH['user'], DYNDNS_AUTH['pass'])) 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']))
s = result.content.decode("unicode_escape").rstrip('\n').split(' ') s = result.content.decode("unicode_escape").rstrip('\n').split(' ')
cx = mysql.connector.connect(**DB_CONFIG) cx = mysql.connector.connect(**DB_CONFIG)
c = cx.cursor() c = cx.cursor()
if s[0] in ['nochg', 'good']:
data = (datetime.datetime.now(), s[0], s[1]) 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)
try: try:
c.execute("INSERT INTO ipch_he (time,status,ip) values (%s,%s,%s)",data) c.execute(IPCH_TABLE_CMD)
c.execute('INSERT INTO ipch (time, status, ip) values (%s, %s, %s)', data)
cx.commit() cx.commit()
except: except:
cx.rollback() cx.rollback()

3
requirements.txt Normal file
View File

@ -0,0 +1,3 @@
speedtest-cli
mysql-connector-python
requests

54
st.py
View File

@ -1,24 +1,35 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import speedtest import sys
import csv
import datetime import datetime
import configparser
import mysql.connector import mysql.connector
import os import speedtest
from socket import timeout
db_config = { cfg = configparser.ConfigParser()
'user': 'm_imp', with open('config.ini') as f:
'password': '123', cfg.read_file(f)
'host': '127.0.0.1',
'database': 'speedtests' db_config = {k: v for k, v in cfg['db'].items() if k in ['user', 'password', 'host', 'database']}
}
SPEEDTEST_TABLE_CMD = """CREATE TABLE IF NOT EXISTS sts (
test_no INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT,
server_id INTEGER,
sponsor NATIONAL CHARACTER VARYING(40),
time DATETIME,
distance FLOAT UNSIGNED,
ping FLOAT UNSIGNED,
download FLOAT UNSIGNED,
upload FLOAT UNSIGNED
);
"""
try: try:
cx = mysql.connector.connect(**db_config) cx = mysql.connector.connect(**db_config)
c = cx.cursor() c = cx.cursor()
except mysql.connector.Error as err: upload_statement = """INSERT INTO sts (server_id, sponsor, time, distance, ping, download, upload)
exit('Could not open database') VALUES (%s, %s, %s, %s, %s, %s, %s)"""
upload_statement = "INSERT INTO sts (server_id,sponsor,serv_name,time,distance,ping,download,upload) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
try: try:
s = speedtest.Speedtest() s = speedtest.Speedtest()
@ -30,31 +41,36 @@ try:
u = ( u = (
d['server']['id'], d['server']['id'],
d['server']['sponsor'], d['server']['sponsor'],
d['server']['name'],
d['timestamp'], d['timestamp'],
d['server']['d'], # distance d['server']['d'], # distance
d['server']['latency'], d['server']['latency'],
d['download'], d['download'],
d['upload'] d['upload']
) )
except speedtest.SpeedtestException: except (speedtest.SpeedtestException, timeout):
u = ( u = (
None,
None, None,
str(datetime.datetime.utcnow().isoformat()) + 'Z', str(datetime.datetime.utcnow().isoformat()) + 'Z',
None, None,
None, None,
None, None,
None,
None,
None None
) )
print("Speedtest failed", file=sys.stderr)
try: try:
c.execute(SPEEDTEST_TABLE_CMD)
c.execute(upload_statement, u) c.execute(upload_statement, u)
cx.commit() cx.commit()
except: except mysql.connector.Error:
cx.rollback() cx.rollback()
raise raise
c.close() c.close()
cx.close() cx.close()
except mysql.connector.Error as err:
print(err)
exit('Could not open database')
# print("Uploaded" + str(u)) # print("Uploaded" + str(u))

View File

@ -1,15 +0,0 @@
CREATE TABLE IF NOT EXISTS ipch (
time datetime,
status text,
ip text
);
CREATE TABLE IF NOT EXISTS sts (
test_no integer unsigned primary key auto_increment,
server_id tinytext,
sponsor tinytext,
time datetime,
distance float unsigned,
ping float unsigned,
download float unsigned,
upload float unsigned
);