赞
踩
本文介绍了一个实用工具,用于在Linux系统上管理systemctl服务。该工具提供了创建、安装、卸载、启动和停止服务的功能,帮助用户轻松地管理和控制正在运行的服务。
通过使用该代码,你可以轻松地执行以下操作:
这个工具使得服务管理更加简单和高效,无需手动执行复杂的命令。你可以在开发环境和生产环境中使用它来管理和控制服务,提高工作效率和减少错误。
总之,这段代码提供了一种简单而可靠的方式来管理systemctl服务,方便你对服务进行管理和控制。
import os import sys import subprocess # 服务名称:*.service SERVICE_NAME = "example.service" SERVICE_FILE_PATH = f"/etc/systemd/system/{SERVICE_NAME}" def create_service_file(): """服务文件内容 WorkingDirectory: 指需要执行命令的路径所在位置,也就是命令执行的当前工作目录 ExecStart:指服务启动命令,可以是已打包执行程序的完整路径,或者是python解释器的路径加上脚本的路径 """ service_content = """ [Unit] Description=Demo Services After=network.target network-online.target systemd-networkd-wait-online.service [Service] WorkingDirectory=/home/project ExecStart=/usr/local/python3/bin/python3 example.py Restart=on-failure RestartSec=10s KillMode=mixed [Install] WantedBy=multi-user.target """ # 去除第一行空格 service_content = service_content.lstrip() with open(SERVICE_FILE_PATH, 'w') as f: f.write(service_content) def install_service(): """创建systemctl服务""" # 检查文件是否存在,如存在则先停止,再覆盖安装 if os.path.exists(SERVICE_FILE_PATH): subprocess.run(f"systemctl stop {SERVICE_NAME}", shell=True) try: create_service_file() subprocess.run("systemctl daemon-reload", shell=True) subprocess.run(f"systemctl enable {SERVICE_NAME}", shell=True) subprocess.run(f"systemctl start {SERVICE_NAME}", shell=True) print(f"服务安装成功,请使用 `systemctl status {SERVICE_NAME}` 查看状态") except Exception as e: print("服务安装失败:", e) def uninstall_service(): """卸载systemctl服务""" if os.path.exists(SERVICE_FILE_PATH): try: subprocess.run(f"systemctl stop {SERVICE_NAME}", shell=True) subprocess.run(f"systemctl disable {SERVICE_NAME}", shell=True) subprocess.run(f"rm {SERVICE_FILE_PATH}", shell=True) print("服务卸载成功") except Exception as e: print("服务卸载失败:", e) else: print(f"{SERVICE_NAME} 服务不存在") def start_service(): """启动systemctl服务""" if os.path.exists(SERVICE_FILE_PATH): try: subprocess.run(f"systemctl start {SERVICE_NAME}", shell=True) print(f"服务启动成功,请使用 `systemctl status {SERVICE_NAME}` 查看状态") except Exception as e: print("服务启动失败:", e) else: print(f"{SERVICE_NAME} 服务不存在") def stop_service(): """停止systemctl服务""" if os.path.exists(SERVICE_FILE_PATH): try: subprocess.run(f"systemctl stop {SERVICE_NAME}", shell=True) print("服务停止成功") except Exception as e: print("服务停止失败:", e) else: print(f"{SERVICE_NAME} 服务不存在") if __name__ == "__main__": if len(sys.argv) > 1: if sys.argv[1] == 'install': install_service() elif sys.argv[1] == 'uninstall': uninstall_service() elif sys.argv[1] == 'start': start_service() elif sys.argv[1] == 'stop': stop_service() else: print("无效参数, 只支持:install、uninstall、start、stop") else: # 不传入参数时,运行功能代码 while True: print("程序运行中...")

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。