time.sleep(self.timeSlice) def SvcDoRun(self): self.logger.info('====================== IP Reporter Service Started ======================') try: self.loop() except Exception as e: self.logger.exception(e) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.isAlive = False self.logger.info('====================== IP Reporter Service Stoped ======================') if __name__=='__main__': if len(sys.argv) == 1: # 用户未输入参数则打印帮助信息 try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(IPReporterService) servicemanager.Initialize('IPReporterService', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error as e: import winerror if e.args[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(IPReporterService)
win32serviceutil.ServiceFramework.__init__(self, args) self.systray_task = None self.osm_task = None def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # TODO: how to terminate thread friendly ? def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.osm_task = OsmTask() self.osm_task.start() self.systray_task = SysTrayTask() self.systray_task.start() try: self.systray_task.join() self.osm_task.join() sys.exit(0) except SystemExit: pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(LyOsmService)
class CameraAppServerSvc(win32serviceutil.ServiceFramework): _svc_name_ = "DDONG CAM Monitor" _svc_display_name_ = "DDONG CAM Monitor Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_RUNNING) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) self.main() def main(self): main_app.app.run(host='0.0.0.0', port=5000, threaded=True) if __name__ == '__main__': #win32serviceutil.HandleCommandLine(AppServerSvc) if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(CameraAppServerSvc) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(CameraAppServerSvc)
def main(): """ Entry point for the WebSocket client tunnel service endpoint """ win32serviceutil.HandleCommandLine(wstuncltd)
win32serviceutil.RestartService(service) else: win32serviceutil.ControlService(service, control_codes[command]) class PyWebService(win32serviceutil.ServiceFramework): """Python Web Service.""" _svc_name_ = 'Python Web Service' _svc_display_name_ = 'Python Web Service' _svc_deps_ = None _exe_name_ = 'pywebsvc' _exe_args_ = None _svc_description_ = 'Python Web Service' def SvcDoRun(self): from cherrypy import process process.bus.start() process.bus.block() def SvcStop(self): from cherrypy import process self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) process.bus.exit() def SvcOther(self, control): process.bus.publish(control_codes.key_for(control)) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PyWebService)
def HandleCommandLine(allow_service=True): """ Handle command line for a Windows Service Prescribed name that will be called by Py2Exe. You MUST set 'cmdline_style':'custom' in the package.py! """ win32serviceutil.HandleCommandLine(SABHelper)
os.chdir(current_dir) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) win32evtlogutil.ReportEvent(self._svc_name_,servicemanager.PYS_SERVICE_STOPPED,0, servicemanager.EVENTLOG_INFORMATION_TYPE,(self._svc_name_, '')) self.ReportServiceStatus(win32service.SERVICE_STOPPED) return def handle_windowsservice(serviceclass): ''' This function handles a Windows service class. It displays the appropriate command line help, and validaes command line arguements. @param serviceclass: a reference to a overridden WindowsService class. ''' if len(sys.argv) == 1: try: import servicemanager, winerror evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(serviceclass) servicemanager.Initialize(serviceclass.__name__, evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error, details: if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(serviceclass)
def stop(self): if self.is_enabled: log.debug("Windows Service - Stopping Dogstatsd server") self.server.stop() self.reporter.stop() self.reporter.join() class PupProcess(multiprocessing.Process): def __init__(self, agentConfig): multiprocessing.Process.__init__(self, name='pup') self.config = agentConfig self.is_enabled = self.config.get('use_web_info_page', True) def run(self): self.pup = pup if self.is_enabled: log.debug("Windows Service - Starting Pup") self.pup.run_pup(self.config) def stop(self): if self.is_enabled: log.debug("Windows Service - Stopping Pup") self.pup.stop() if __name__ == '__main__': multiprocessing.freeze_support() if len(sys.argv) == 1: handle_exe_click(AgentSvc._svc_name_) else: win32serviceutil.HandleCommandLine(AgentSvc)
def handle_commandline(argv=None): win32serviceutil.HandleCommandLine(OpsiclientdService, argv=argv)
class EpsonFiscalDriverService(win32serviceutil.ServiceFramework): _svc_name_ = "epsonFiscalDriver" _svc_display_name_ = "Servidor de Impresora Fiscal" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) def SvcDoRun(self): import servicemanager from epsonFiscalDriver import socketServer servicemanager.LogInfoMsg("epsonFiscalDriver - Iniciando Servidor") self.server = socketServer("Hasar", "", 12345, "COM1", 9600, 60, True) servicemanager.LogInfoMsg( "epsonFiscalDriver - Servidor Construido, sirviendo eternamente") self.server.serve_forever() def SvcStop(self): import servicemanager servicemanager.LogInfoMsg("epsonFiscalDriver - Deteniendo el servicio") self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) self.server.shutdown() if __name__ == '__main__': win32serviceutil.HandleCommandLine(EpsonFiscalDriverService)
def SvcSessionChange(self, event_type): if event_type == WTS_SESSION_LOGON: self.vdsAgent.sessionLogon() elif event_type == WTS_SESSION_LOGOFF: self.vdsAgent.sessionLogoff() elif event_type == WTS_SESSION_LOCK: self.vdsAgent.sessionLock() elif event_type == WTS_SESSION_UNLOCK: self.vdsAgent.sessionUnlock() def SvcOtherEx(self, control, event_type, data): if control == win32service.SERVICE_CONTROL_SESSIONCHANGE: self.SvcSessionChange(event_type) def ReportEvent(self, EventID): try: win32evtlogutil.ReportEvent( self._svc_name_, EventID, 0, # category servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, '')) except: logging.exception("Failed to write to the event log") if __name__ == '__main__': # Note that this code will not be run in the 'frozen' exe-file!!! win32serviceutil.HandleCommandLine(OVirtGuestService)
username=alert_username) ''' @app.route('/slack', methods=['POST']) def receive_alert(self): if request.form.get('token') == slack_webhook: username = request.form.get('user_name') alert = request.form.get('text') received_message = 'Alert: {}, submitted by {}'.format(alert, username) ''' if __name__ == '__main__': if sys.platform.startswith('win'): win32api.SetConsoleCtrlHandler(ctrlHandler, True) win32serviceutil.HandleCommandLine(PyalertsService) cpu_threshold = config['config']['percent_threshold']['cpu_threshold'] ram_threshold = config['config']['percent_threshold']['ram_threshold'] disk_threshold = config['config']['percent_threshold']['disk_threshold'] # Alert if cpu, ram or disk usage is above the specified threshold in # config file alerts = AlertManager() threshold = 90 while True: for resource in ('cpu_usage', 'ram_usage', 'disk_usage'): alert = queue_job(pyalerts.jobs.usage.get_usage, str(resource)) time.sleep(2) usage = int(alert.result) if usage >= threshold:
# Do the actual stop self.stop() log('Stopped') win32event.SetEvent(self.stop_event) self.ReportServiceStatus(win32service.SERVICE_STOPPED) def start(self): self.processes = start_commands(self.config) def stop(self): if self.processes: end_commands(self.processes) self.processes = [] node_name = platform.node() clean = self.config.get(node_name, 'clean') if self.config.has_section(node_name) else self.config.get( 'services', 'clean') if clean: for file in clean.split(';'): try: os.remove(file) except: error("Error while removing %s\n%s" % (file, traceback.format_exc())) if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'test': test_commands() else: DjangoService._base_path = dirname(abspath(__file__)) win32serviceutil.HandleCommandLine(DjangoService)
try: sock = socket.socket() sock.connect(('localhost',27360)) time.slip(30) sock.close() except ConnectionRefusedError: os.chdir("F:\\") cmd = "harddiskprotect install" subprocess.run(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(10) cmd = "harddiskprotect start" subprocess.run(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pass if __name__ == '__main__': if len(sys.argv) > 1: win32serviceutil.HandleCommandLine(protectmyhddsvcstarter) else: servicemanager.Initialize() servicemanager.PrepareToHostSingle(protectmyhddsvcstarter) servicemanager.StartServiceCtrlDispatcher()
cursor = conn.cursor() currentime = datetime.datetime.now() delta = datetime.timedelta(seconds=300) pretime = currentime + delta currentimestr = currentime.strftime("%Y-%m-%d %H:%M:%S.0") pretimestr = pretime.strftime("%Y-%m-%d %H:%M:%S.0") for item in jsondata: time = item['time'] longitude = float(item['weidu']) latitude = float(item['jingdu']) depth = float(item['depth']) magnitude = float(item['Magnitude']) location = item['weizhi'] if time >= pretimestr and time < currentimestr: insertsql = "INSERT INTO earinfo\ (time,longitude,latitude,depth,earthquakeMagnitude,location)\ VALUES ('%s','%f','%f','%f','%f','%s')" % \ (time, longitude, latitude, depth, magnitude, location) try: cursor.execute(insertsql) db.commit() except Exception as e: print(e) db.rollback() conn.close() # db = pymysql.connect("222.18.158.202", user='******', passwd='Yuson000', db='EESS', charset='UTF8') if __name__ == '__main__': win32serviceutil.HandleCommandLine(PythonService)
print "Error initiating Proxy, already running?" sys.exit(1) except: traceback.print_exc() print("Failed to start proxy.") sys.exit(1) if self.debug == False: thread.start_new_thread(proxyserver.run, ()) thread.start_new_thread(server.run, ()) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) server.loop = False servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '')) sys.exit(0) else: thread.start_new_thread(server.run, ()) thread.start_new_thread(proxyserver.run, ()) print "Will exit in 10 seconds" try: time.sleep(10) except (KeyboardInterrupt, SystemExit): server.loop = False server.loop = False sys.exit(0) if __name__ == '__main__': # or hasattr(sys, 'frozen'): win32serviceutil.HandleCommandLine(proxyService)
def SvcDoRun(self): msg = 'SABHelper-service' self.Logger(servicemanager.PYS_SERVICE_STARTED, msg + ' has started') res = main() self.Logger(servicemanager.PYS_SERVICE_STOPPED, msg + ' has stopped' + res) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def Logger(self, state, msg): win32evtlogutil.ReportEvent(self._svc_display_name_, state, 0, servicemanager.EVENTLOG_INFORMATION_TYPE, (self._svc_name_, unicode(msg))) def ErrLogger(self, msg, text): win32evtlogutil.ReportEvent(self._svc_display_name_, servicemanager.PYS_SERVICE_STOPPED, 0, servicemanager.EVENTLOG_ERROR_TYPE, (self._svc_name_, unicode(msg)), unicode(text)) ############################################################################## # Platform specific startup code ############################################################################## if __name__ == '__main__': win32serviceutil.HandleCommandLine(SABHelper, argv=sys.argv)
''' Download install package ''' urllib.urlretrieve(latest_package_url, file_path) logger.info('Stopping scalarizr service.') try: win32serviceutil.StopService('Scalarizr') except: pass logger.info('Running package.') p = subprocess.Popen('start "Installer" /wait "%s" /S' % file_path, shell=True) err = p.communicate()[1] if p.returncode: raise Exception( "Error occured while installing scalarizr: %s" % err) logger.info('Successfully installed scalarizr') finally: shutil.rmtree(tmp_dir) except (Exception, BaseException), e: logger.info("Update failed. %s", e) sys.exit(1) if __name__ == '__main__': if '--install' in sys.argv: sys.argv = [sys.argv[0], '--startup', 'auto', 'install'] win32serviceutil.HandleCommandLine(ScalarizrDevTools) win32serviceutil.StartService(ScalarizrDevTools._svc_name_)
def SvcDoRun(self): rc = None while rc != win32event.WAIT_OBJECT_0: # write what your service should do ---- START ----- val_cpu_usage = psutil.cpu_percent() val_mem_usage = psutil.virtual_memory().percent BASEURL = 'https://api.thingspeak.com/update?api_key=' THINGSPEAK_APIKEY = 'XXXXXXXXXXXXXX' # <--- Put your API Key VALUES = '&field1={}&field2={}'.format(val_cpu_usage, val_mem_usage) postURL = BASEURL + THINGSPEAK_APIKEY + VALUES data = requests.post(postURL) # write what your service should do ---- END ----- # write the message to your local storage if you want # with open('C:\\Users\\XXXXX\Works\ThingSpeakLogService.log', 'a') as f: # <--- Put log file path # f.write(postURL) # f.write('\n') rc = win32event.WaitForSingleObject(self.hWaitStop, 20000) # <--- Logging interval if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(ThingSpeakLogService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(ThingSpeakLogService)
self.stop_event = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) self.stop_requested = False def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.stop_event) logging.info('Stopping service ...') http_server.stop() self.stop_requested = True def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() def main(self): logging.info('Automato Windows Service Started') # Simulate a main loop db.create_all() logging.info('Starting server') global http_server http_server = WSGIServer(('0.0.0.0', 80), app) http_server.serve_forever() webbrowser.open_new_tab('localhost') if __name__ == '__main__': win32serviceutil.HandleCommandLine(AutomatoSvc)
import servicemanager class NVDARemoteService(win32serviceutil.ServiceFramework): _svc_name_ = "NVDARemoteService" _svc_display_name_ = "NVDARemote relay server" _svc_deps_ = [] def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) serverThread.running = False win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): startAndWait() if len(sys.argv) == 1: servicemanager.Initialize(NVDARemoteService._svc_name_, os.path.abspath(servicemanager.__file__)) servicemanager.PrepareToHostSingle(NVDARemoteService) try: servicemanager.StartServiceCtrlDispatcher() except: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(NVDARemoteService) else: startAndWait()
while True: if not stop_pending and win32event.WaitForSingleObject(self.hWaitStop, 0) == win32event.WAIT_OBJECT_0: exit_event.set() stop_pending = True elif stop_pending and not exit_event.is_set(): break socks = daemon.getServerSockets() ins,outs,exs = select.select(socks,[],[],1) for s in socks: if s in ins: daemon.handleRequests() break p.join() daemon.shutdown() if __name__ == '__main__': if len(sys.argv) == 1: try: evtsrc_dll = os.path.abspath(servicemanager.__file__) servicemanager.PrepareToHostSingle(OpcService) servicemanager.Initialize('zzzOpenOPCService', evtsrc_dll) servicemanager.StartServiceCtrlDispatcher() except win32service.error, details: if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: win32serviceutil.usage() else: win32serviceutil.HandleCommandLine(OpcService)
# -*- coding:utf-8 -*- import win32serviceutil import win32service import win32event import sys import os #设置编码 reload(sys) sys.setdefaultencoding('utf-8') #windows服务中显示的名字 class zlsService(win32serviceutil.ServiceFramework): _svc_name_ = 'web_movie' ###可以根据自己喜好修改 _svc_display_name_ = 'web_movie' ###可以根据自己喜好修改 _svc_description_ = 'web_movie' ###可以根据自己喜好修改 def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.stop_event = win32event.CreateEvent(None, 0, 0, None) self.run = True def SvcDoRun(self): from web_movie import app while True: try: app.run() except: pass def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.stop_event) self.ReportServiceStatus(win32service.SERVICE_STOPPED)
sys.stderr = f port = config.getPort() httpd = httpserver.TivoHTTPServer(('', int(port)), httpserver.TivoHTTPHandler) for section, settings in config.getShares(): httpd.add_container(section, settings) b = beacon.Beacon() b.add_service('TiVoMediaServer:' + str(port) + '/http') b.start() while 1: sys.stdout.flush() (rx, tx, er) = select.select((httpd, ), (), (), 5) for sck in rx: sck.handle_request() rc = win32event.WaitForSingleObject(self.stop_event, 5) if rc == win32event.WAIT_OBJECT_0: b.stop() break def SvcStop(self): win32event.SetEvent(self.stop_event) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PyTivoService)
def parse_command_line(cls): ''' ClassMethod to parse the command line ''' win32serviceutil.HandleCommandLine(cls)
self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.hs = win32service.OpenService(hscm, "Audiosrv", win32service.SERVICE_ALL_ACCESS) self.status = win32service.QueryServiceStatus(self.hs) def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # And set my event. win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): # We do nothing other than wait to be stopped! win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) while True: status = win32service.QueryServiceStatus(self.hs) type, state = status[0], status[1] if type not in (win32service.SERVICE_STOP, win32service.SERVICE_STOP_PENDING): newstatus = win32service.ControlService( self.hs, win32service.SERVICE_CONTROL_PAUSE) if __name__ == '__main__': win32serviceutil.HandleCommandLine(SmallestPythonService)
def install(self): win32serviceutil.HandleCommandLine(self)
class TestService(win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): rc = None while rc != win32event.WAIT_OBJECT_0: with open('C:\\TestService.log', 'a') as f: f.write('test service running...\n') rc = win32event.WaitForSingleObject(self.hWaitStop, 5000) if __name__ == '__main__': if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(TestService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(TestService)
def start(self): time.sleep(10000) def stop(self): pass def _getLogger(self): # logdir = os.path.abspath(os.path.dirname(inspect.getfile(inspect.currentframe())))#日志目录 logger = logging.getLogger('fix logger') # handler = logging.FileHandler(filename=os.path.join(logdir,'Fix.log')) handler = logging.FileHandler(filename=r'c:\Fix.log') formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s-%(filename)s:%(module)s:%(funcName)s:%(lineno)d - %(message)s' ) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger def sleep(self, minute): win32api.Sleep((minute * 1000), True) if __name__ == "__main__": if len(sys.argv) == 1: servicemanager.Initialize() servicemanager.PrepareToHostSingle(MyService) servicemanager.StartServiceCtrlDispatcher() else: win32serviceutil.HandleCommandLine(MyService)
from os.path import splitext, abspath from sys import modules cls = TestService try: module_path=modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path=executable module_file = splitext(abspath(module_path)) cls.__svc_reg_class = "%s.%s" % (module_file,cls.__name__) win32api.SetConsoleCtrlHandler(lambda x: True,True) try: win32serviceutil.QueryServiceStatus(cls.__name__) except: win32serviceutil.InstallService( cls.__svc_reg_class, cls.__svc_name_, cls.__svc_display_name_, startType=win32service.SERVICE_AUTO_START ) print "[+] Service Has been installed" else: win32serviceutil.HandleCommandLine(cls,argv=["update"]) finally: win32serviceutil.HandleCommandLine(cls,argv=["debug"]) try: while True: time.sleep(1) except: exit()