Skip to content

Instantly share code, notes, and snippets.

@harjitmoe
Last active January 6, 2017 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harjitmoe/6c8f869b83634a069a1e3b7ada45634a to your computer and use it in GitHub Desktop.
Save harjitmoe/6c8f869b83634a069a1e3b7ada45634a to your computer and use it in GitHub Desktop.
Send a service stop, start, restart or status instruction to Upstart (via initctl) or systemd (via systemctl) as appropriate. Relevant on e.g. Ubuntu Xenial, which uses systemd for its init, but still retains Upstart for certain Unity-related purposes.
#!/usr/bin/env python
import subprocess, os, sys
DEVNULL = open(os.devnull,"r+")
ctlexes = ["initctl","systemctl"]
provides = ["start","stop","restart","status"]
sys.argv[0] = os.path.basename(sys.argv[0])
if sys.argv[0] not in provides:
sys.argv.pop(0)
if (not sys.argv) or (sys.argv[0] not in provides): #ie still
raise RuntimeError("must be used for commands of %r only (not %s)"%(provides,sys.argv[0]))
for a in sys.argv[1:]:
if a[0] != "-":
dae = a
break
else:
raise RuntimeError("no daemon specified")
for myctl in ctlexes:
ret = subprocess.call([myctl,"status",dae],stdout=DEVNULL,stderr=DEVNULL,stdin=DEVNULL)
if not ret:
ctl = myctl
break
else:
raise RuntimeError("daemon name %s not recognised by any of %r"%(dae,ctlexes))
sys.exit(subprocess.call([myctl]+sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment