45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
#!/usr/bin/python3
|
|
# Entrouvert 2019
|
|
import configparser
|
|
import importlib
|
|
import io
|
|
import json
|
|
import shlex
|
|
import sys
|
|
import psycopg2
|
|
import subprocess
|
|
|
|
|
|
def get_config():
|
|
configfile = sys.argv[1]
|
|
config = configparser.ConfigParser()
|
|
config.read(configfile)
|
|
return config['DEFAULT']
|
|
|
|
|
|
def tail(filename):
|
|
p = subprocess.Popen(shlex.split('tail -f %s' % filename), stdout=subprocess.PIPE)
|
|
for line in io.TextIOWrapper(p.stdout):
|
|
yield line
|
|
|
|
|
|
class Database:
|
|
def __init__(self, host, database, user, password, **kwargs):
|
|
self.conn = psycopg2.connect(host=host, database=database, user=user, password=password)
|
|
|
|
def write(self, entry):
|
|
with self.conn.cursor() as cursor:
|
|
json_data = json.dumps(entry['data'])
|
|
sql = 'insert into collection_entry (host, service, priority, timestamp, data) values (%s, %s, %s, %s, %s)'
|
|
args = (entry['host'], entry['service'], entry['priority'], entry['timestamp'], json_data)
|
|
cursor.execute(sql, args)
|
|
self.conn.commit()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
config = get_config()
|
|
database = Database(**config)
|
|
agent = importlib.import_module(config['agent'])
|
|
for entry in getattr(agent, 'main')():
|
|
database.write(entry)
|