Created
September 17, 2019 18:12
-
-
Save Taiiwo/e6ef1333b86008981d60dfd6f9f552f3 to your computer and use it in GitHub Desktop.
Python script for automatically creating systemd services
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
#!/usr/bin/env python3.6 | |
import sys | |
import os | |
import pwd | |
import pipes | |
import subprocess | |
# Usage: servicize.py python3 main.py | |
# OR: servicize.py ./somefile.sh | |
# It will attempt to complete abs paths and automatically name the service. | |
# Then do: sudo systemctl enable <name> | |
string = """[Unit] | |
Description={basename} | |
After=network.target | |
[Service] | |
Type=simple | |
# Another Type: forking | |
User={current_user} | |
WorkingDirectory={cwd} | |
ExecStart={exec} | |
Restart=on-failure | |
# Other restart options: always, on-abort, etc | |
# The install section is needed to use | |
# `systemctl enable` to start on boot | |
# For a user service that you want to enable | |
# and start automatically, use `default.target` | |
# For system level services, use `multi-user.target` | |
[Install] | |
WantedBy=default.target""" | |
# if argv1 is a relative path, convert it to absolute | |
if sys.argv[1][0] == ".": | |
argv1 = os.path.abspath(sys.argv[1]) | |
else: | |
argv1 = subprocess.check_output( | |
["which", pipes.quote(sys.argv[1])] | |
).decode("ascii").strip("\n") | |
string = string.format_map({ | |
"basename": os.path.basename(os.getcwd()), | |
"current_user": pwd.getpwuid(os.getuid())[0], | |
"cwd": os.getcwd(), | |
"exec": argv1 + " " + " ".join(sys.argv[2:]) | |
}) | |
if os.getuid() != 0: | |
cmd = " ".join([ | |
"echo", pipes.quote(string), "|", "sudo", "tee", | |
os.path.join( | |
"/etc/systemd/system/", pipes.quote(os.path.basename(os.getcwd())) + ".service" | |
) | |
]) | |
os.system(cmd) | |
print(cmd.splitlines()[-1][len(string.splitlines()[-1]):]) | |
print("reloading daemon...") | |
os.system("sudo systemctl daemon-reload") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment