参考资料
务必先看参考资料
# !/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)
其中代码
# 添加服务相关参数到注册表
reg.addSrvParam(srv, dir, app)
相关 reg.py 内容如下
参考资料
# !/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
附