Python实现Windows服务的添加、删除、启动、关闭

参考资料

《bat 做Windows服务》

《Python实现环境变量持久化修改》

《Python实现管理员权限运行CMD指令》

 

务必先看参考资料

 

# !/usr/bin/python3
# coding: utf-8
import os
import time
import traceback

from tool import bat, reg


class Service(object):

    def __init__(self, name, dir, app):
        # 服务名称
        self.name = name
        # 服务程序路径
        self.dir = dir
        # 服务启动程序.bat或.exe
        self.app = app

        cwd = os.getcwd()
        self.instsrv = os.path.join(cwd, r"\extra\instsrv.exe")
        self.srvany = os.path.join(cwd, r"\extra\srvany.exe")
    
    def install(self):
        try:
            self.remove()

            print("Install service ..")
            # 管理员权限运行CMD命令
            bat.runAdmin("%s %s %s" % (self.instsrv, self.name, self.srvany))
            # 添加服务相关参数到注册表
            reg.addSrvParam(self.name, self.dir, self.app)
            print("%s install success" % self.name)
        except Exception as e:
            traceback.print_exc()
            raise e

    def status(self):
        status = os.popen("sc query %s" % self.name).read()
        if "未安装" in status:
            return -1
        elif "START_PENDING" in status:
            return 0
        if "RUNNING" in status:
            return 1
        elif "STOP_PENDING" in status:
            return 2
        elif "STOPPED" in status:
            return 3
        else:
            return 4

    def auto(self):
        try:
            # 管理员权限运行CMD指令
            bat.runAdmin("sc config %s start = auto" % self.name)
        except Exception as e:
            raise e

    def start(self):
        status = self.status()
        if -1 == status:
            print("%s is uninstalled" % self.name)
            return
        elif 0 == status:
            print("%s is starting .." % self.name)
            return
        elif 1 == status:
            print("%s is running" % self.name)
            return
        elif 2 == status:
            print("%s is stopping .." % self.name)
            time.sleep(10)
            while 2 == self.status():
                time.sleep(10)

            print("Start service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc start %s" % self.name)
            print("%s startup success" % self.name)
        elif 3 == status:
            print("%s is stopped" % self.name)

            print("Start service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc start %s" % self.name)
            print("%s startup success" % self.name)
        else:
            print("%s is in other status" % self.name)

    def stop(self):
        status = self.status()
        if -1 == status:
            print("%s is uninstalled" % self.name)
            return
        elif 0 == status:
            print("%s is starting .." % self.name)
            time.sleep(10)
            while 0 == self.status():
                time.sleep(10)

            print("Stop Service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc stop %s" % self.name)
            print("%s shutdown success" % self.name)
        elif 1 == status:
            print("%s is running" % self.name)

            print("Stop Service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc stop %s" % self.name)
            print("%s shutdown success" % self.name)
        elif 2 == status:
            print("%s is stopping .." % self.name)
            return
        elif 3 == status:
            print("%s is stopped" % self.name)
            return
        else:
            print("%s is in other status" % self.name)

    def restart(self):
        status = self.status()
        if -1 == status:
            print("%s is uninstalled" % self.name)
            return
        elif 0 == status:
            print("%s is starting .." % self.name)
            return
        elif 1 == status:
            try:
                print("Stop Service ..")
                # 管理员权限运行CMD指令
                bat.runAdmin("sc stop %s" % self.name)
            except:
                print(str(traceback.format_exc()))

            print("Start service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc start %s" % self.name)
            print("%s startup success" % self.name)
        elif 2 == status:
            print("%s is stopping .." % self.name)
            time.sleep(10)
            while 2 == self.status():
                time.sleep(10)

            print("Start service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc start %s" % self.name)
            print("%s startup success" % self.name)
        elif 3 == status:
            print("%s is stopped" % self.name)

            print("Start service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("sc start %s" % self.name)
            print("%s startup success" % self.name)
        else:
            print("%s is in other status" % self.name)

    def remove(self):
        try:
            status = self.status()
            if -1 == status:
                print("%s is uninstalled" % self.name)
                return

            self.stop()

            print("Remove service ..")
            # 管理员权限运行CMD指令
            bat.runAdmin("%s %s remove" % (self.instsrv, self.name))
            print("%s remove success" % self.name)
        except Exception as e:
            raise e

 

其中代码

# 管理员权限运行CMD指令
bat.runAdmin(cmd)

方法参考 《Python实现管理员权限运行CMD指令》

 

其中代码

# 添加服务相关参数到注册表
reg.addSrvParam(srv, dir, app)

相关 reg.py 内容如下

参考资料

《Python实现环境变量持久化修改》

# !/usr/bin/python3
# coding: utf-8
import os
import subprocess
import traceback


def addSrvParam(srv, dir, app):
    # only \\ in path, / or \ is not allowed
    dir = format(dir).replace("\\", "\\\\")
    app = format(app).replace("\\", "\\\\")

    # 版本声明
    c = 'Windows Registry Editor Version 5.00\n'

    # 必须空行
    c += '\n'
    # 添加主键
    c += '[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\%s\Parameters]\n' % srv
    # 添加键值
    c += '"AppDirectory"="%s"\n' % dir
    # 添加键值
    c += '"Application"="%s"\n' % app

    path = os.getcwd() + r"\tool\script\srv.reg"

    f = None
    try:
        f = open(path, 'w')
        f.write(c)
    except Exception as e:
        traceback.print_exc()
        raise e
    finally:
        if f:
            f.close()

    command(path, 1800000)


def command(cmd, timeout=1800000):
    try:
        sp = subprocess.Popen(
            cmd,
            shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        print("[PID] %s: %s" % (sp.pid, cmd))
        sp.wait(timeout=timeout)

        stderr = str(sp.stderr.read().decode("gbk")).strip()
        stdout = str(sp.stdout.read().decode("gbk")).strip()
        if "" != stderr:
            raise Exception(stderr)
        if stdout.find("失败") > -1:
            raise Exception(stdout)
    except Exception as e:
        raise e


def format(path):
    if path is None:
        return ""

    path = path.lstrip()
    path = path.rstrip()

    while path.find("/") >= 0:
        path = path.replace("/", "\\")
    while path.find("\\\\") >= 0:
        path = path.replace("\\\\", "\\")

    return path

 

 

《Python 写Windows Service服务程序》

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值