Use dbus-python to query system state and failed units

master
Mike Gerber 8 years ago
parent ece5647c25
commit e95167262b

@ -12,5 +12,7 @@ these commands:
$ systemctl list-units $ systemctl list-units
$ systemctl status $ systemctl status
Requires python-dbus.
License: Public Domain. Keep my name in it if you like. License: Public Domain. Keep my name in it if you like.
Author: Mike Gerber 2015 Author: Mike Gerber 2015, 2016

@ -7,29 +7,39 @@ import subprocess
import sys import sys
def find_systemctl(): try:
systemctls = [ '/bin/systemctl', '/usr/bin/systemctl' ] import dbus
for systemctl in systemctls: except ImportError:
if posixpath.exists(systemctl): print("UNKNOWN: Please install python-dbus")
return systemctl sys.exit(3)
systemctl = find_systemctl() bus = dbus.SystemBus()
if not systemctl: proxy = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1')
print('System WARN: systemctl not found')
sys.exit(1)
def get_system_state():
"""Get system state."""
properties_manager = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')
system_state = properties_manager.Get('org.freedesktop.systemd1.Manager', 'SystemState')
return system_state
try:
state = subprocess.check_output([systemctl, 'is-system-running'])
state = state.strip()
except subprocess.CalledProcessError as e:
state = e.output.strip()
print('System NOT OK: {}'.format(state))
sys.exit(2)
if state in ['running', 'starting']: def get_failed_units():
print('System OK: {}'.format(state)) """Get a list of failed system units."""
units = proxy.ListUnits(dbus_interface='org.freedesktop.systemd1.Manager')
failed_units = []
for u in units:
service, _, loaded, active, state = u[:5]
if active == 'failed':
failed_units.append(service)
return failed_units
system_state = get_system_state()
if system_state in ['running', 'starting']:
print('System OK: {}'.format(system_state))
sys.exit(0) sys.exit(0)
else: else:
print('System NOT OK: {}'.format(state)) print('System NOT OK: {}, failed: {}'.format(system_state, " ".join(get_failed_units())))
sys.exit(0) sys.exit(2)

Loading…
Cancel
Save