Last active
December 18, 2015 09:39
-
-
Save adam-stokes/5762654 to your computer and use it in GitHub Desktop.
Python generator to search for a running service from an output of initctl on Ubuntu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from subprocess import Popen, PIPE, STDOUT | |
def is_executable(command): | |
"""Returns if a command matches an executable on the PATH""" | |
paths = os.environ.get("PATH", "").split(os.path.pathsep) | |
candidates = [command] + [os.path.join(p, command) for p in paths] | |
return any(os.access(path, os.X_OK) for path in candidates) | |
def shell_out(command, timeout=300): | |
cmdfile = command.strip("(").split()[0] | |
cmd_env = os.environ | |
# ensure consistent locale for collected command output | |
cmd_env['LC_ALL'] = 'C' | |
if is_executable(cmdfile): | |
# use /usr/bin/timeout to implement a timeout | |
if timeout and is_executable("/usr/bin/timeout"): | |
command = "/usr/bin/timeout %ds %s" % (timeout, command) | |
p = Popen(command, shell=True, | |
stdout=PIPE, stderr=STDOUT, | |
bufsize=-1, env = cmd_env) | |
stdout, stderr = p.communicate() | |
return (p.returncode, stdout, 0) | |
else: | |
return (127, "", 0) | |
def services(): | |
""" Generator that returns all services found on system | |
""" | |
(ret, res, stat) = shell_out("initctl list") | |
for svc in res.split("\n")[:-1]: | |
is_running = True if "start" in svc else False | |
yield (svc.split()[0], is_running) | |
def is_running(service): | |
""" Checks if a service is running | |
""" | |
# (ret, res, stat) = shell_out("initctl status %s" % (service,)) | |
# return True if "start" in res else False | |
return any((service and True) in x for x in services()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment