使用Python和systemctl管理Linux系统服务的简便工具

前言

   本文介绍了一个实用工具,用于在Linux系统上管理systemctl服务。该工具提供了创建、安装、卸载、启动和停止服务的功能,帮助用户轻松地管理和控制正在运行的服务。

通过使用该代码,你可以轻松地执行以下操作:

  • 创建服务文件:根据指定的内容创建一个systemctl服务文件。
  • 安装服务:创建一个服务文件,将其复制到系统的服务目录中,并添加为系统服务。
  • 卸载服务:从系统中移除已安装的服务。
  • 启动服务:使用systemctl命令启动已安装的服务。
  • 停止服务:使用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("程序运行中...")

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值