操作实践
1、编写python程序,按照自己的需求编写
以下是案例
# -*- coding:utf-8 -*-
import win32serviceutil
import win32service
import win32event
import win32timezone #不加导入,打包后运行会报错,原因未知,暂时不去刨根
from flask import Flask
from flask import request
import sys
import os
#windows服务中显示的名字
class kqsService(win32serviceutil.ServiceFramework):
_svc_name_ = 'kqs_agent'
_svc_display_name_ = 'kqs_agent'
_svc_description_ = 'kqs_agent'
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.stop_event = win32event.CreateEvent(None, 0, 0, None)
self.run = True
def SvcDoRun(self):
app = Flask(__name__)
#测试路由,用来测试agent是否正在运行,返回ok表示正在运行
@app.route('/', methods=['GET', 'POST'])
def test():
if request.method == "GET":
return "ok"
app.run(host='0.0.0.0', port=50000)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.stop_event)
self.ReportServiceStatus(win32service.SERVICE_STOPPED)
self.run = False
if __name__ == '__main__':
import sys
import servicemanager
if len(sys.argv) == 1:
try:
evtsrc_dll = os.path.abspath(servicemanager.__file__)
servicemanager.PrepareToHostSingle(kqsService)
servicemanager.Initialize('kqsService',evtsrc_dll)
servicemanager.StartServiceCtrlDispatcher()
except win32service.error as details:
import winerror
if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
win32serviceutil.usage()
else:
win32serviceutil.HandleCommandLine(kqsService)
2、通过pip install pyinstaller 指令安装pyinstaller ,运行pyinstaller -F .\serve.py
3、提取exe文件至目标服务器,用管理员权限运行powershell,输入指令 .\serve.exe install
4、成功之后在系统服务中可以找到自己命名的服务,选择开机自启即可