Skip to content

Instantly share code, notes, and snippets.

@ahmedsadman
Last active January 26, 2023 12:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ahmedsadman/097234c47a3b493aa219c7538daa78ef to your computer and use it in GitHub Desktop.
Save ahmedsadman/097234c47a3b493aa219c7538daa78ef to your computer and use it in GitHub Desktop.
Python script to create systemd service
"""
Create systemd service file in Linux from given JSON data file
Author: Ahmed Sadman Muhib
"""
"""
Sample JSON file:
{
"service_name": "test_service",
"description": "Netcore dev server",
"package_path": "dotnet",
"service_path": "/home/muhib/DevOps/loopdatetime/Output/BuildApp.dll",
"service_url": "localhost:6000"
}
"""
import os
import json
import subprocess
class ServiceCreator:
def __init__(self, data_file):
self.data_file = data_file
# check if given file is valid json
if (not os.path.isfile(data_file)) or (
not data_file.endswith(".json")
):
raise Exception("Invalid data file. It should be JSON")
self.data = self.parse_json_file()
def parse_json_file(self):
with open(self.data_file, "r") as f:
data = json.load(f)
return data
def get_service_file_template(self):
return """[Unit]
Description={desc}
After=network.target
[Service]
ExecStart={pkg} {service_path} {service_url}
Restart=on-failure
[Install]
WantedBy=multi-user.target
"""
def create_service_file(self):
with open(
"/etc/systemd/system/{}.service".format(self.data["service_name"]),
"w",
) as f:
template = self.get_service_file_template()
f.write(
template.format(
desc=self.data["description"],
pkg=self.data["package_path"],
service_path=self.data["service_path"],
service_url=self.data["service_url"],
)
)
def restart_service(self):
os.system(
"sudo systemctl restart {}".format(self.data["service_name"])
)
def restart_daemon(self):
"""restart daemon and start the service"""
os.system("sudo systemctl daemon-reload")
os.system("sudo systemctl enable {}".format(self.data["service_name"]))
os.system("sudo systemctl start {}".format(self.data["service_name"]))
def create_or_restart_service(self):
"""Check if the service is running. If yes, then restart it. Otherwise,
create a new service file and start the new service"""
service_status = subprocess.Popen(
["sudo", "systemctl", "is-active", self.data["service_name"]],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
output, stderr = service_status.communicate()
output = output.decode("utf-8").strip()
if output == "active":
# service is running
print("Restarting service...")
self.restart_service()
print("Done")
else:
# service is not running
print("Creating service file...")
self.create_service_file()
print("Starting service...")
self.restart_daemon()
print("Done")
if __name__ == "__main__":
sc = ServiceCreator("test.json")
sc.create_or_restart_service()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment