-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsystemd-service-status.py
executable file
·148 lines (119 loc) · 4.93 KB
/
systemd-service-status.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#!/usr/bin/env python3
import logging
import os
import re
import subprocess
import sys
import time
class SystemdServiceStatus:
def __init__(self, oid_prefix):
"""Object containing information about systemd services and their status"""
self.oid_prefix = oid_prefix
# self.data is a dictionary that contains all systemd service data using programmatically
# generated OID as the key:
#
# --- snip ---
# '1.3.9950.1.115.115.115.100.45.115.101.99.114.101.116.115': ('integer', 3, 'sssd-secrets'),
# '1.3.9950.1.115.115.115.100': ('integer', 0, 'sssd'),
# --- snip ---
self.data = {}
# self.sorted_oids enables iterating over the OIDs in correct order
# while having the data in a non-ordered dictionary (self.data).
self.sorted_oids = []
# Get systemd service status and store it in self.data. Also populate
# self.sorted_oids.
self.cache_service_status()
def cache_service_status(self):
"""Cache service status"""
# Temporary data structure used to create sorted oid list later
oids = [self.oid_prefix]
lines = subprocess.check_output(["/bin/systemctl", "list-units", "-a", "-t", "service", "--no-legend"]).decode("UTF-8").split("\n")
for line in lines:
# Filter out systemd services that are service instance "templates" and
# not real services, e.g. [email protected].
if line and not "@." in line:
# This pattern will get the service name and current status. The test string will be something like
#
# accounts-daemon.service loaded active running Accounts Service
#
# Regular expression can be easily tested online, e.g. here: https://pythex.org
#
result = re.search(r"^(.+)\.service\s+[\w|-]+\s+\w+\s+(\w+)\s+.*$", line)
service_name = result.group(1)
service_status = result.group(2)
if service_status == 'running':
service_status = 0
else:
service_status = 2
service_oid = self.create_oid(service_name)
self.data[service_oid] = ('integer', service_status, service_name)
oids.append(service_oid)
# Sort the oids array. Lovingly borrowed from here:
#
# https://rosettacode.org/wiki/Sort_a_list_of_object_identifiers#Python
#
# The array sorted array is then used to output data in the correct order when using
# getnext (snmpwalk)
self.sorted_oids = sorted(oids, key=lambda x: list(map(int, x.split('.'))))
def create_oid(self, name):
"""Generate oid programmatically from the service name"""
oid = self.oid_prefix
for char in name:
oid += "."
oid += str(ord(char))
return oid.lstrip(".")
def getline():
return sys.stdin.readline().strip()
def output(line):
sys.stdout.write(line + "\n")
sys.stdout.flush()
def main():
oid_prefix = "1.3.9950.1"
s = SystemdServiceStatus(oid_prefix)
# The main loop that talks with snmpd. Mostly taken from
#
# https://net-snmp.sourceforge.io/wiki/index.php/Tut:Extending_snmpd_using_shell_scripts#Pass_persist
try:
while True:
command = getline()
# It seems that snmpd never outputs an empty line, so this is
# redundant.
if command == "":
sys.exit(0)
# snmpd 5.4.2.1 sends a PING before every snmp command
elif command == "PING":
output("PONG")
elif command == "set":
oid = getline()
type_and_value = getline()
output("not-writable")
elif command == "get":
oid = getline()
output(str(oid))
output(str(s.data[oid.lstrip(".")][0]))
output(str(s.data[oid.lstrip(".")][1]))
sys.exit(0)
elif command == "getnext":
oid = getline()
ni = s.sorted_oids.index(oid.lstrip(".")) + 1
if ni >= len(s.sorted_oids) - 1:
sys.exit(0)
else:
output("." + str(s.sorted_oids[ni]))
output(str(s.data[s.sorted_oids[ni]][0]))
output(str(s.data[s.sorted_oids[ni]][1]))
else:
pass
logging.error("Unknown command: %s" % command)
sys.exit(0)
# If we get an exception, spit it out to the log then quit
# (by propagating exception).
# snmpd will restart the script on the next request.
except Exception as ep:
f = open("/var/lib/snmp/systemd-service-status.err.log", "a")
f.write(ep)
f.close()
logging.error(e)
raise
if __name__ == "__main__":
main()