Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/env python3
"""
Criticality: Low
This test check the current state of the fail2ban service.
"""
from pathlib import Path
import sys
# pylint: disable=E0401
import dbus
sys.path.append(str(Path(__file__).parents[1].resolve()))
# pylint: disable=wrong-import-position
from envsetup import utils as u # noqa: E402
def get_service_state(name: str) -> tuple:
"""Get the systemd service state.
:param name: Service name
:type name: str
:return: Active state, and running state.
:rtype: tuple
"""
bus = dbus.SystemBus()
systemd = bus.get_object("org.freedesktop.systemd1", "/org/freedesktop/systemd1")
manager = dbus.Interface(systemd, "org.freedesktop.systemd1.Manager")
unit = manager.LoadUnit("{}.service".format(name))
proxy = bus.get_object("org.freedesktop.systemd1", str(unit))
active = proxy.Get(
"org.freedesktop.systemd1.Unit",
"ActiveState",
dbus_interface="org.freedesktop.DBus.Properties",
)
state = proxy.Get(
"org.freedesktop.systemd1.Unit",
"SubState",
dbus_interface="org.freedesktop.DBus.Properties",
)
return str(active), str(state)
def check_service_running(name: str) -> bool:
"""Check that the given service is active and running.
:param name: Service name
:type name: str
:return: Wether the service active and running or not
:rtype: bool
"""
active, state = get_service_state(name)
if active != "active" or state != "running":
return False
return True
def get_jails() -> list:
"""Get the list of active jails.
:return: List of jails
:rtype: list
"""
_, output = u.exec_cmd(["fail2ban-client status | grep 'Jail list'"])
jails = output.split(":")[1].replace(" ", "").split(",")
return jails
def check_jail(name: str) -> int:
_, output = u.exec_cmd("fail2ban-client status {} | grep 'Jail list'".format(name))
print(output)
return 0
def main():
"""Run all checks and exits with corresponding exit code."""
# init
errors = 0
warnings = 0
print("Checking fail2ban state:")
if not check_service_running("fail2ban"):
u.warning("fail2ban is not running")
warnings += 1