monutil/log.py

87 lines
3.2 KiB
Python

#!/usr/bin/python3
# MIT License
# Copyright (c) 2024 Thomas Williams - https://git.server.wales/thomas
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import pyodbc
from datetime import datetime
class logsManager:
def __init__(self, server, database, username, password):
self.conn_str = 'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password
def insertHost(self, hostname, ipAddress):
try:
conn = pyodbc.connect(self.conn_str)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM monutil_hosts WHERE hostname = ?", hostname)
if cursor.fetchone()[0] == 0:
cursor.execute("INSERT INTO monutil_hosts (hostname, ipAddress) VALUES (?, ?)", hostname, ipAddress)
conn.commit()
else:
cursor.execute("UPDATE monutil_hosts SET ipAddress = ? WHERE hostname = ?", ipAddress, hostname)
except pyodbc.Error as ex:
print("Error inserting data: {}".format(str(ex)))
def insertHostLog(self, hostname, ipAddress, log_time, cpu, memory):
try:
self.insertHost(hostname, ipAddress)
conn = pyodbc.connect(self.conn_str)
cursor = conn.cursor()
cursor.execute("INSERT INTO monutil_hostlogs (hostname, logTime, cpu, memory) VALUES (?, ?, ?, ?)", hostname, log_time, cpu, memory)
conn.commit()
conn.close()
except pyodbc.Error as ex:
print("Error inserting data: {}".format(str(ex)))
def insertURLLog(self, hostname, ipAddress, log_time, url, responseTime):
try:
self.insertHost(hostname, ipAddress)
conn = pyodbc.connect(self.conn_str)
cursor = conn.cursor()
cursor.execute("INSERT INTO monutil_urlLogs (hostname, url, logTime, responseTime) VALUES (?, ?, ?, ?)", hostname, url, log_time, responseTime)
conn.commit()
conn.close()
except pyodbc.Error as ex:
print("Error inserting data into monutil_urlLogs:", ex)