您所在的位置:小祥子 » 编程 » Python » 正文

Python 写Windows Service服务程序

时间:2015-05-12 编辑:dcb3688 来源:本站整理

1.需求

为什么要开发一个windows服务呢?之前做一个程序,必须要读取指定目录文件License, 因为其他程序也在读取这指定目录的License文件,且License不同时会修改License的内容,
修改了License后导致我们的程序无法运行,所以想做个windows 的服务时时检测这个License文件是否被修改,如果检测到被修改就覆盖该License。

2.依赖的第三方库

必须要借助第三方模块pywin32
下载地址: https://pypi.python.org/pypi/pywin32/214

3.实现过程

实例化win32serviceutil.ServiceFramework的时候,windows系统会自动调用SvcDoRun方法,
这个函数的执行不可以结束,因为结束就代表服务停止。所以当我们放自己的代码在SvcDoRun函数中执行的时候,必须确保该函数不退出,类似与这样的效果:

 def SvcDoRun(self):
        while True:
             self._LicenseExist()
             time.sleep(2)

当停止服务的时候,系统会调用SvcDoStop函数,该函数通过设置标志位等方式让SvcDoRun函数退出,就是正常的停止服务。
win32event.SetEvent(self.hWaitStop) 通过事件退出

服务操作命令:

 #1.安装服务
 
 python PythonService.py install
 
 #2.让服务自动启动
 
 python PythonService.py --startup auto install 
 
 #3.启动服务
 
 python PythonService.py start
 
 #4.重启服务
 
 python PythonService.py restart
 
 #5.停止服务
 
 python PythonService.py stop
 
 #6.删除/卸载服务
 
 python PythonService.py remove

4.完整代码:

 # -*- coding: UTF8 -*-
 # 
 import win32serviceutil 
 import win32service 
 import win32event
 import winerror
 import servicemanager
 import os, sys, time
 
 class PythonService(win32serviceutil.ServiceFramework): 
 
     _svc_name_ = "ALicense"   #  服务名
     _svc_display_name_ = "ALicense Is Exist "   # 服务在windows系统中显示的名称
     _svc_description_ = "ALicense  Is Exist License windows"   #服务的描述
 
     def __init__(self, args): 
         win32serviceutil.ServiceFramework.__init__(self, args) 
         self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
         self.License = self._LicenseExist()
         self.run = True
         
     def _LicenseExist(self):
         is_exist=os.path.exists('C:\License.dat')
         string_key='d8838bccad0c19e847b9e73f4432b951b6f035fd8c19f5474e30db5a0e4fa4c99b57c01af79161850b95d3f99a6b0b6074f18224ec7c44f28bc243be06f8f2b96e370f5ca724c01f1bd0e289afdd9eeef7e33d42a5113ddd4818a47b33449487baec2099a50d5e3dde32bdf66d979982a68d0d60a1200990ebf8a4827b7db3d1e83f9ad9d9946267fe830c48bbe025a5ebb99b85c7f1cf93de2beb22c8e9766e5ef526242b01f5251d8a768780026add2d2d8fb9ffccb86f8779221b01d206e586d96b83839b30006910a4bca6438fb5d5b2900431f8ecab50a9f18d0e7e8abec7b212fdc9ab667f08dd3eef14ecbdb24910466f45be92d0a085ff81d7362b828847c29be579942b63b9eb26b2441b5ef20f5a012431d263ded3f5fe434111b833612464bf4df18ae06c536b6895d240387774c3b438d5f0745c7a0d3ce963e82fc8df603f6fa526e8bd1fc51e2509e0840f3bbbde7bc3fec9e837b5aa744a9ae4449c974e26d787e475f73dbc3ee9c73cc258f38b79c413453fd4fe732bed57ba9d0312d2bcaf333a5c82d92a269a7ccaf27273a178feb95028f8f0805675a6199abbd8b47756b4543269a35025438794cd32410ac19c77526c4b94b93d091069056df1dda0f49298d753a317850c7104f94067ac9cc4d5b3d377f10627d21c12a4c066347eb05370fbe9e0658c1ec1803d43ed71509f5cdb25d60f505ef7527c405d3ea05bb381436dd3622484a1ff7263e4d93f275493332af3f77d28a13a0fa0eb810b7d25a378f6b8313ab3bcb44131ca3500670b0321aa95b077cef85d348e13315c2d2d42795e41569162986755709d099b59ee320e6caf422497234251d07d697bb3f3e5ad6d15d80fd85da016e7075bf84522aa6339e8b66ecd4b71d02fd01f4f57a0147ceaddbf9e5f32e7ec60ae35ff73d2f386d9d0133cb697731773b55fc2615c584e9f4013253d3fc53fa13a9e982a2493e1145861759c30cf9064d333bb184e378b52e7dd8bbbd0c17774549fabb44014dab2e0a903c53d0da1c9d3a223c69f3b9bcc7925ba21a464fc9fa43e20574ffedb7a27f2cd7ae7b6b46c5cb4e0b176ece7d59ff199b74b3436ead185df5c79d74b35d644bb02315130131772db21fcd1d535014b10c4cbbb8e1f847cd00be52992ab94a7b5a7b1c27d87abe3fc605972ceb3463a07924c816a04642adcabbc7b18a40a24a3af217d0390c1102cb5b4573b1816c76667f50d33631a97e986255644e8e0c26d63cd1f29f501ff51673509822c1bf8158ceee752024dcbe0e24941803ebd8afc0bded3598012ba5431060f0db7fad7fd4960972da9a6cfaa0850c43470498236ef7b22fbf79d491e054cf142815e6c04e573a52e22ccaa2d406167c6442db40456cd93752349b2968132388b51edbe13aa349abc34696453d1a4b39f8311284f8afbae'
         if is_exist:
             for line in open("C:\License.dat"):
                 if line!=string_key:
                     self.writer(string_key)
         else:
             self.writer(string_key)
     # 写入License        
     def writer(self, string_key):
         f=open('C:\License.dat','w')
         f.write(string_key)
         f.close()
         
     def SvcDoRun(self):
         while self.run:
             # 已经运行
             self._LicenseExist()
             time.sleep(2)   #推迟调用线程的运行2秒
                 
     def SvcStop(self): 
         # 服务已经停止
         self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) 
         win32event.SetEvent(self.hWaitStop) 
         self.run = False
 
 if __name__=='__main__':
     if len(sys.argv) == 1:
         try:
             evtsrc_dll = os.path.abspath(servicemanager.__file__)
             servicemanager.PrepareToHostSingle(PythonService)
             servicemanager.Initialize('PythonService', evtsrc_dll)
             servicemanager.StartServiceCtrlDispatcher()
         except win32service.error, details:
             if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                 win32serviceutil.usage()
     else:
         win32serviceutil.HandleCommandLine(PythonService)

5.效果与问题

当直接运行py文件访问是可以添加服务,且服务也可运行,但是使用pyinstaller打包exe后程序就不能正常执行,
提示:错误1053 服务没有及时相应启动或控制请求

google 后找到解决方法,
原理我也不是很懂,貌似是要在实例化windows服务类时候,监控服务调度

     if len(sys.argv) == 1:
         try:
             evtsrc_dll = os.path.abspath(servicemanager.__file__)
             servicemanager.PrepareToHostSingle(PythonService)
             servicemanager.Initialize('PythonService', evtsrc_dll)
             servicemanager.StartServiceCtrlDispatcher()
         except win32service.error, details:
             if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                 win32serviceutil.usage()
     else:
         win32serviceutil.HandleCommandLine(PythonService)

pyinstaller 打包为控制台文件

 if __name__ == '__main__':
     from PyInstaller.main import run
     params=['windows_services_in_python.py', '-F', '-c', '--icon=favicon.ico']
     run(params)

打包后CMD到改目录:

放行杀毒软件拦截

6.管理window服务操作

完整代码:

 #!/usr/bin/env python
 # -*- coding: UTF8 -*-
 #
 import win32service
 import win32con
 import time, sys
 import datetime
 reload(sys)
 sys.setdefaultencoding("utf8")
 class ServiceManager(object):
     """管理window服务"""
 
     def __init__(self, name):
         """
         name: 服务的名称
         """
         self.name = name
         
         #启动或停止服务时等待操作成功等待时间
         self.wait_time = 0.5
         #启动或停止服务时最大等待时间,超过时返回超时提示
         self.delay_time = 10
         self.scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
 
 
         if self.is_exists():
             try:
                 self.handle = win32service.OpenService(self.scm, self.name, win32service.SC_MANAGER_ALL_ACCESS)
             except Exception, e:
                 self.log(e)
         else:
             print '服务 %s 没有安装'.encode('gbk') % self.name
             
 
     def is_stop(self):
         """检查服务是否停止"""
         flag = False
         try:
             if self.handle:
                 ret = win32service.QueryServiceStatus(self.handle)
                 flag = ret[1] != win32service.SERVICE_RUNNING
         except Exception, e:
             self.log(e)
         return flag
 
     def start(self):
         """开启服务"""
         try:
             if self.handle:
                 win32service.StartService(self.handle, None)
         except Exception, e:
             self.log(e)
         status_info = win32service.QueryServiceStatus(self.handle)
 
         if status_info[1] == win32service.SERVICE_RUNNING:
             return '启动服务%s成功'.encode('gbk') % self.name
         elif status_info[1] == win32service.SERVICE_START_PENDING:
             #如果服务正在启动中则延迟返回启动信息,直到启动成功,或返回启动时间过长信息
             start_time = datetime.datetime.now()
             while True:
                 if (datetime.datetime.now() - start_time).seconds > self.delay_time:
                     return '启动服务%s时间太长'.encode('gbk') % self.name
 
                 time.sleep(self.wait_time)
                 if win32service.QueryServiceStatus(self.handle)[1] == win32service.SERVICE_RUNNING:
                     return '启动服务%s成功'.encode('gbk') % self.name
         else:
             return '启动服务%s失败'.encode('gbk') % self.name
 
     def stop(self):
         """停止服务"""
         try:
             status_info = win32service.ControlService(self.handle, win32service.SERVICE_CONTROL_STOP)
         except Exception, e:
             self.log(e)
         if status_info[1] == win32service.SERVICE_STOPPED:
             return '停止服务%s成功'.encode('gbk') % self.name
         elif status_info[1] == win32service.SERVICE_STOP_PENDING:
             start_time = datetime.datetime.now()
             while True:
                 if (datetime.datetime.now() - start_time).seconds > self.delay_time:
                     return '停止服务%s时间太长'.encode('gbk') % self.name
 
                 time.sleep(self.wait_time)
                 if win32service.QueryServiceStatus(self.handle)[1] == win32service.SERVICE_STOPPED:
                     return '停止服务%s成功'.encode('gbk') % self.name
         else:
             return '停止服务%s失败'.encode('gbk') % self.name
 
     def restart(self):
         """重启服务"""
         if not self.is_stop():
             self.stop()
         self.start()
         return win32service.QueryServiceStatus(self.handle)
 
     def status(self):
         """获取运行的状态"""
         try:
             status_info = win32service.QueryServiceStatus(self.handle)
             status = status_info[1]
             if status == win32service.SERVICE_STOPPED:
                 return "STOPPED"
             elif status == win32service.SERVICE_START_PENDING:
                 return "STARTING"
             elif status == win32service.SERVICE_STOP_PENDING:
                 return "STOPPING"
             elif status == win32service.SERVICE_RUNNING:
                 return "RUNNING"
         except Exception, e:
             self.log(e)
 
     def close(self):
         """释放资源"""
         try:
             if self.scm:
                 win32service.CloseServiceHandle(self.handle)
                 win32service.CloseServiceHandle(self.scm)
         except Exception, e:
             self.log(e)
 
     def is_exists(self):
         """windows服务是否已安装"""
         statuses = win32service.EnumServicesStatus(self.scm, win32service.SERVICE_WIN32, win32service.SERVICE_STATE_ALL)
         for (short_name, desc, status) in statuses:
             if short_name == self.name:
                 return True
         return False
 
     def log(self, exception):
         
         print(exception)
         
         
 
 if __name__=='__main__':
 
     app= ServiceManager('AAaservice')
     msg= app.is_exists()  # 判断是否安装  (以下操作必须先判断服务是否存在)
     #msg= app.is_stop()  # 判断服务是否停止
     #msg= app.status()  # 查看服务的状态
     #msg= app.start()  # 开启服务
     #msg= app.stop()  # 暂停服务   (服务开启才能停止,else error)
     #msg= app.restart()  # 重启服务
     
     print(msg)

7.参考地址:

python添加服务:         http://blog.csdn.net/kmust20093211/article/details/42169323
python添加服务:         http://www.chrisumbel.com/article/windows_services_in_python
打包无法运行服务:        http://zhangweide.cn/archive/2013/pyinstaller-package-windows-service.html
python管理window服务  https://github.com/zhulin3141/PPServ/edit/master/service_manager.py

关键词:服务