ungleich-game/check.py

123 lines
3 KiB
Python
Raw Normal View History

2019-04-14 18:06:45 +00:00
import subprocess
2019-04-14 18:30:04 +00:00
import logging
logging.basicConfig()
log = logging.getLogger("checks")
2019-04-14 17:13:22 +00:00
class CheckException(Exception):
pass
class WrongParameterException(CheckException):
pass
class BaseCheck(object):
def check(self):
""" Should return tuple:
(true/false, data)
data is the raw result and can be saved in a database
"""
pass
2019-04-14 18:06:45 +00:00
2019-04-14 17:13:22 +00:00
class DNSCheck(BaseCheck):
2019-04-14 18:06:45 +00:00
def __init__(self, name, rr_type="AAAA", expected_result=None, server=None):
2019-04-14 17:13:22 +00:00
self.rr_types = [ "AAAA", "A", "PTR", "TXT" ]
self.name = name
self.rr_type = rr_type
self.server = server
2019-04-14 18:06:45 +00:00
self.expected_result = expected_result
2019-04-14 17:13:22 +00:00
if not self.rr_type in self.rr_types:
raise WrongParameterException("Unsupported rr_type: {}".format(self.rr_type))
2019-04-14 18:06:45 +00:00
self.command = self.rr_type_to_command()
2019-04-14 17:13:22 +00:00
def rr_type_to_command(self):
base_cmd="dig +short"
if self.rr_type == "AAAA":
command = "{} {} aaaa".format(base_cmd, self.name)
elif self.rr_type == "A":
command = "{} {} a".format(base_cmd, self.name)
elif self.rr_type == "PTR":
command = "-x {}".format(base_cmd, self.name)
elif self.rr_type == "TXT":
2019-04-14 18:06:45 +00:00
command = "{} {} txt".format(base_cmd, self.name)
if self.server:
command = "{} @{}".format(command, self.server)
2019-04-14 17:13:22 +00:00
2019-04-14 18:06:45 +00:00
return command.split()
2019-04-14 17:13:22 +00:00
def check(self):
2019-04-14 18:06:45 +00:00
res = subprocess.run(self.command,
capture_output=True,
encoding="utf-8")
if not res.returncode == 0:
return (False, "")
if self.expected_result:
if not self.expected_result == res.stdout:
return (False, res.stdout)
else:
if res.stdout == "":
return (False, res.stdout)
# Has (correct) data
return (True, res.stdout)
def __repr__(self):
return "<Check {}>".format(self.__str__())
def __str__(self):
name = "{}/{}".format(self.name, self.rr_type)
if self.server:
name = "{}@{}".format(name, self.server)
return name
2019-04-14 18:30:04 +00:00
class DFCheck(BaseCheck):
def __init__(self, name, username="root", path="/"):
self.name = name
self.username = username
self.path = path
self.command = self.create_command()
log.info("Command = {}".format(self.command))
def create_command(self):
base_command ='ssh {}@{}'.format(self.username, self.name).split()
base_command.append("df {}".format(self.path))
return base_command
def check(self):
res = subprocess.run(self.command,
capture_output=True,
encoding="utf-8")
if not res.returncode == 0:
return (False, "")
return (True, res.stdout)
def __repr__(self):
return "<df {}>".format(self.__str__())
def __str__(self):
name = "{}:{}".format(self.name, self.path)
return name