Skip to content

Instantly share code, notes, and snippets.

@aimerneige
Last active March 29, 2022 09:45
Show Gist options
  • Save aimerneige/93e6253d59483a3139e456e2325e0b04 to your computer and use it in GitHub Desktop.
Save aimerneige/93e6253d59483a3139e456e2325e0b04 to your computer and use it in GitHub Desktop.
Generate and install a simple service file for backend.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Aimer Neige
# Email: [email protected]
import os
import sys
service_template = '''[Unit]
Description={}
After=network.target
[Service]
Type=simple
ExecStart={}
Restart=always
[Install]
WantedBy=multi-user.target
'''
def generate_service_file(description, exec_start_script, file_name):
raw = str.format(service_template, description, exec_start_script)
with open(file_name, "w") as f:
f.write(raw)
print("Service file generated.")
def install_service(file_name):
os.system(f"sudo cp ./{file_name} /lib/systemd/system/{file_name}")
os.system(f"sudo systemctl enable {file_name}")
os.system(f"sudo systemctl start {file_name}")
print("Service installed.")
def main():
description = input("Please type service description.")
exec_start_script = input("Please type start command: ")
file_name = input("Please type service file name.")
generate_service_file(description, exec_start_script, file_name)
choice = input("Do you want to install it? [y/n] ")
if choice == "y":
install_service(file_name)
if __name__ == '__main__':
print("Welcome to use simple backend service generator.")
print("Author: Aimer Neige")
args = sys.argv
if len(args) == 1:
main()
elif len(args) == 4:
description = args[1]
exec_start_script = args[2]
file_name = args[3]
generate_service_file(description, exec_start_script, file_name)
install_service(file_name)
else:
print("Usage:")
print(" python service_generator.py")
print(" or exec without asking")
print(" ./service_generator.py description exec_start_script file_name")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment