py program is converted into .exe and runs perfectly on windows to implement windows service program (watchdog instance)

pyInstaller installation configuration
1, open the URL: pyInstalller download URL

pip install pyinstaller
    or upgrade to a newer version:
    pip install --upgrade pyinstaller
    To install the current development version use:
    pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz

3. Download a pywin32 ( pywin32 website )
and check your own version before downloading.

4. Double-click pywin32-221.win-amd64-py3.5.exe to install. Note that the previously installed Python will be automatically detected during installation. Next step, next step.
//Omit 5, enter the Scripts directory under the Python3.5 directory on the CMD command line and execute: python pywin32_postinstall.py -install command
//Omit 6, enter the D:\Programs\Python\pyinstaller-pyinstaller directory on the CMD command line (The pyInstaller folder you unzipped before), then execute: python setup.py install

7. Make exe
1, first write a hello.py
2, and put hello.py in the directory D:\Programs\Python\pyinstaller-pyinstaller.
3. Enter the directory on the CMD command line and execute the command: pyinstaller -FD:\study\python\test.py
4. Generate a new directory D:\study\python\build\dist
in the dist folder of the directory A test.exe is generated under.

5. Run test.exe

---------------------------------------------------------------------

Install the python running environment
and quickly install the packaging plug-in:
pip install pyinstaller
2. Generate exe command:
pyinstaller -FD:\study\python\test.py
I will expand the parameters of the command:
-F: Generate a folder with multiple files in it File mode, fast startup.
-D: Only generates a file, does not expose other information, and starts slowly.
-w: Window mode packaging, does not display the console.
-c: Follow the icon path as the application icon.

-----------------------------------

Implement windows service service program

You must use the third-party module pywin32
download address: https://pypi.python.org/pypi/pywin32/214

win32serviceutil.ServiceFramework is a well-encapsulated Windows service framework, which we can implement by inheriting it.

  • Through the SvcDoRun method, the service is started and the business code in the service is run.
  • Stop the service through the SvcStop method.

WinPollManager.py

import win32serviceutil
import win32service
import win32event
import winerror
import servicemanager
import time
import sys
import os
 
 
class WinPollManager(win32serviceutil.ServiceFramework):
    """
    #1.安装服务
    python WinPollManager.py install
 
    #2.让服务自动启动
    python WinPollManager.py --startup auto install
 
    #3.启动服务
    python WinPollManager.py start
 
    #4.重启服务
    python WinPollManager.py restart
 
    #5.停止服务
    python WinPollManager.py stop
 
    #6.删除/卸载服务
    python WinPollManager.py remove
    """
 
    _svc_name_ = "py_agent_poll_manager"  # 服务名
    _svc_display_name_ = "py_agent_poll_manager"  # 服务在windows系统中显示的名称
    _svc_description_ = "python windows monitor agent"  # 服务的描述
 
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.isAlive = True
        self._poll_intvl = 30
 
    def SvcDoRun(self):
        while self.isAlive:
            print 'monitor testing'
            time.sleep(self._poll_intvl)
 
    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.isAlive = False
 
if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(WinPollManager)
            servicemanager.Initialize('WinPollManager', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error, details:
            if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(WinPollManager)  # 括号里参数可以改成其他名字,但是必须与class类名一致;

After successful packaging, the exe file is generated in the dist directory.

Implementation modalities

  • Install service WinPollManager.exe install
  • The service starts automatically WinPollManager.exe --startup auto install
  • Start the service WinPollManager.exe start
  • Restart the service WinPollManager.exe restart
  • Stop the service WinPollManager.exe stop
  • Remove/uninstall service WinPollManager.exe remove

--------------------------------------

Watchdog program:

New: test.py

import os
import time
import subprocess
import psutil
import threading
import datetime
import configparser
import re
 
cf = configparser.ConfigParser()
cf.read("wailaizhu.conf")
 
app01 = cf.get("desk", "app_name")
path01 = cf.get("desk", "path")

def look_cpu(process_name):
    res = subprocess.Popen('wmic cpu get LoadPercentage', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    res_str = res.stdout.read().decode(encoding='gbk')
    print(res_str)
    num = re.findall('\d+', res_str)[0]
    if int(num) > 80:
        print('cup负载超过10%')
        time.sleep(10)
        res_twice = subprocess.Popen('wmic cpu get LoadPercentage', stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
        res_twice_str = res_twice.stdout.read().decode(encoding='gbk')
        num_twice = re.findall('\d+', res_twice_str)[0]
        # 判断两次监测稳定在5%以内 杀死进程并重启
        if abs(int(num) - int(num_twice)) < 5:
            tasklist = subprocess.Popen('tasklist | findstr CloudControlServer.exe', stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
            res = tasklist.stdout.read().decode(encoding='gbk')
            pid = re.search('\d{1,4}', res).group()
            cmd = 'taskkill -f /pid %s' % pid
            time.sleep(0.5)
            print(cmd)
            os.system('taskkill -f /pid %s' % pid)
            os.system(process_name)
    print('正在监测cpu,cpu占用率:%s,爷爷还是活的!' % num)
    global timer
    timer = threading.Timer(30, look_cpu, (path01,))
    timer.start()

def restart_process(process_name):
    red = subprocess.Popen('tasklist', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    tasklist_str = red.stdout.read().decode(encoding='gbk')
    re_path = process_name.split("\\")[-1]
    formattime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    if re_path not in tasklist_str:
        # obj = connect_emai()
        # sendmail('程序卡掉正在重启。。。', obj)
        # 发送HTTP请求
        # url = "http://159.138.131.148/server_offline.html"
        # request = urllib.request(url)
        global count
        count += 1
        print(formattime + '第' + str(count) + '次检测发现异常:爷爷要挂了,抢救成功!')
        cmd = process_name
        os.system(process_name)
        # res = subprocess.Popen(cmd,stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True)
        # print(res.stderr.read().decode(encoding='gbk'),res.stdout.read().decode(encoding='gbk'))
        # sendmail('重启连接成功!',obj)
        print('yes,connected')
    else:
        global error_count
        error_count += 1
        print(formattime + '第' + str(error_count) + '次检测:OK,爷爷和小妖精在赏月……')
    global timer
    timer = threading.Timer(10, restart_process(app01), (path01,))
    timer.start()



count = 0
error_count = 0
look_cpu(app01)   #检查cpu占用率
timer = threading.Timer(10, restart_process(app01), (path01,))
timer.start()

New: wailaizhu.conf
 

[desk]
app_name = notepad.exe
path = start notepad.exe

Execute under cmd: pyinstaller -F d:\study\python\temp\test.py -id:\wailaizhu.ico to generate exe file

文本编辑器修改wailaizhu.conf配置文件中的:
-------------------------
app_name 检查程序名
path 检查程序路径

-------------------------
当守护程序中断异常时  :尝试重启应用
当系统CPU占用率>80%时 :尝试重启应用
当系统守护程序未启动时:尝试启动应用

Packaging program download address:

https://download.csdn.net/download/wailaizhu/12624634

 

Guess you like

Origin blog.csdn.net/wailaizhu/article/details/107266918