def SvcDoRun(self): self.isAlive = True logging.info("Service running") servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() # win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) # Write a stop message. logging.info("Service Stopped") servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ''))
def SvcDoRun(self): self.isAlive = True # Make sure we are listening for device insert events self.ListenForDeviceEvents() # Generic exception catch to protect app try: self.ReportServiceStatus(win32service.SERVICE_RUNNING) p("}}cb***** OPEService running *****}}xx", log_level=1) # Do we need a seprate event entry for this? servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main() # win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) # Write a stop message. p("}}cb***** OPEService Stopping *****}}xx", log_level=1) # Do we need a seperate event entry for this? servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, '')) except Exception as ex: p("}}rbUnknown Exception: }}xx\n" + str(ex), log_level=1) pass try: p("}}cn***** Cleaning up worker threads: " + \ str(len(self.running_command_threads)) + "}}xx", log_level=3) for t in self.running_command_threads: try: t.join(3) if t.is_alive(): # Still alive? kill it p("}}rnThread hasn't exited yet (" + t.name + ")}}xx") t.stop() except Exception as ex: p("}}rnError trying to join thread!}}xx\n" + str(ex), log_level=1) except Exception as ex: p("}}rb Unknown exception when shutting down threads }}xx\n" + \ str(ex), log_level=1) p("}}cn***** Threads cleaned up. *****}}xx", log_level=3) p("}}cb***** OPEService Fully Stopped *****}}xx", log_level=1)
def SvcDoRun(self): # pylint: disable=C0103 """Start service.""" self.start() servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main()
def SvcDoRun(self): self.is_running = True servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, ("hello", "")) #current_location = str(os.path.abspath(os.path.dirname(sys.argv[0]))) # 현재 위치 체크 while self.is_running: # self.is_running이 True인 경우에만 while 실행 rc = win32event.WaitForSingleObject(self.hWaitStop, 5000) if rc == win32event.WAIT_OBJECT_0: break else: #subprocess.Popen([current_location + "\\Main.exe"]) # 현재 경로에 위치한 Main.exe # TEST #f = open('e:/download/1/a.log', 'a') #f.write(datetime.datetime.now().isoformat()) #f.close() reg = WinRegistry() path = r'HKCU\Control Panel\Desktop' keyvalue = reg.read_key(path) for v in keyvalue['values']: if v['value'] == 'SCRNSAVE.EXE': if v['data'] != 'c:\\Windows\\System32\\PhotoScreensaver.scr': reg.delete_value(path, 'SCRNSAVE.EXE') reg.write_value( path, 'SCRNSAVE.EXE', 'c:\\Windows\\System32\\PhotoScreensaver.scr') time.sleep(60)
def SvcStop(self): #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - import servicemanager as sm sm.LogMsg(sm.EVENTLOG_INFORMATION_TYPE, sm.PYS_SERVICE_STOPPED, (self._svc_name_, '')) self.logmsg("$$ %s STOPPING" % self._svc_name_) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self): self.isrunning = True self.Run() win32event.WaitForSingleObject(self.stop_event, win32event.INFINITE) servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ''))
def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.timeout = 1000 #1 seconds # This is how long the service will wait to run / refresh itself (see script below) while 1: # Wait for service stop signal, if I timeout, loop again rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # Check to see if self.hWaitStop happened if rc == win32event.WAIT_OBJECT_0: # Stop signal encountered servicemanager.LogInfoMsg( "SomeShortNameVersion - STOPPED!") #For Event Log break else: #what to run try: file_path = r"C:\Users\Gerard\Dropbox\code\biz\app\service_content.py" execfile(file_path) except: pass
def SvcDoRun(self): '''Called when the service is asked to start''' self.start() servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.main()
def SvcDoRun(self): PLATDIR = os.environ["ProgramFiles"] PLATDIR = '"' + PLATDIR + '"' servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.timeout = 1000 #1 seconds # This is how long the service will wait to run / refresh itself (see script below) while 1: # Wait for service stop signal, if I timeout, loop again rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # Check to see if self.hWaitStop happened if rc == win32event.WAIT_OBJECT_0: # Stop signal encountered servicemanager.LogInfoMsg( "aiWinSrvDaemon - STOPPED!") #For Event Log break else: #what to run try: file_path = PLATDIR + "\\AppInventor\\aiWinDaemon.exe" os.system(file_path) except: pass
def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.timeout = 640000 #640 seconds / 10 minutes (value is in milliseconds) #self.timeout = 120000 #120 seconds / 2 minutes # This is how long the service will wait to run / refresh itself (see script below) errfile = open(filename, 'a') while 1: # Wait for service stop signal, if I timeout, loop again rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # Check to see if self.hWaitStop happened if rc == win32event.WAIT_OBJECT_0: # Stop signal encountered servicemanager.LogInfoMsg( "SomeShortNameVersion - STOPPED!") #For Event Log break else: #Ok, here's the real money shot right here. #[actual service code between rests] try: runfile = os.path.join(__file__, 'test1.py') if not os.path.exists(runfile): winsound.Beep(440, 50) errfile.write('not found test1.py') execfile(runfile) #Execute the script #inc_file_path2 = "C:\whereever\MORE_REAL_py_work_to_be_done.py" #execfile(inc_file_path2) #Execute the script except: winsound.Beep(440, 50) errfile.write('cannot run test1.py')
def SvcDoRun(self): self.logger.info("Starting {} service".format(self._svc_display_name_)) import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name, '')) # Start monitor p_mon = mp.Process(target=run_monitor) p_mon.start() self.logger.info("Started {} service".format(self._svc_display_name_)) # Wait for Monitor to finish while True: try: # Watch monitor process for 2 seconds p_mon.join(timeout=2) if not p_mon.is_alive(): self.logger.warning("Service stopped prematurely.") self.SvcStop() # Check if we've received a stop command rc = win32event.WaitForSingleObject(self.hWaitStop, 500) if rc == win32event.WAIT_OBJECT_0: p_mon.terminate() p_mon.join() break self.logger.debug("Still running...") except KeyboardInterrupt: self.logger.warning("Interrupted {} service".format( self._svc_display_name_)) break self.logger.info("Stopped {} service".format(self._svc_display_name_))
def write_dtl_00393(self, id_fbl, email_data): # ************ WHIRPOOL utilizza file txt separato da ; servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, # Messaggio generico (datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00393", "")) # logging.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00393") num_bolla = 0 data_bolla = datetime.datetime.now().strftime("%Y%m%d") for file_row in email_data["raw_file"].decode().split("\n"): riga_lista = file_row.split(";") # Filtro le righe spuria if len(riga_lista) >= 19: qta = riga_lista[19] if self.is_number(qta): num_bolla = riga_lista[0].strip()[-6:] # Leggo codice EAN dal file e lo scrivo nel database frontiera. Non necessita di alcuna riconversione cod_art = riga_lista[16].replace("/", "").strip() # In questo caso serve solo per compilare il messaggio mail da inviare altrimenti # mi accorgerei della mancanza del codice soltanto a livello pistole!! self.get_ean_from_cod_alias(cod_art, "341.00393") data_bolla = riga_lista[1].strip() self.cursor.execute( "INSERT TDtb_DettaglioBolle (iFblId, sDtbCodArt, fDtbQta) VALUES (%d, '%s', %d)" % (id_fbl, cod_art, float(qta))) return [num_bolla, datetime.datetime.strptime(str(data_bolla), "%Y%m%d").strftime("%Y-%m-%d"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), id_fbl]
def write_dtl_00420(self, id_fbl, email_data): # ************ VIBO utilizza foglio excel! servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, # Messaggio generico (datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00420", "")) # logging.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00420") num_bolla = 0 data_bolla = datetime.datetime.now().strftime("%Y%m%d") import xlrd xl_workbook = xlrd.open_workbook(file_contents=email_data["raw_file"]) xl_sheet = xl_workbook.sheet_by_index(0) for row in xl_sheet.get_rows(): # Considero soltanto le righe di tipo R. Assumo che le rige D siano descrizioni if row[69].value == "R": num_bolla = int(row[4].value) data_bolla = ''.join([str(s) for s in xlrd.xldate_as_tuple(row[6].value, 0) if s != 0]) qta = row[50].value # Leggo codice EAN dal file e lo scrivo nel database frontiera. Non necessita di alcuna riconversione cod_art = row[80].value if cod_art[:3] != "400": # Da quello che vedo i codici che iniziano per 400 sono Imballi. # In questo caso serve solo per compilare il messaggio mail da inviare altrimenti # mi accorgerei della mancanza del codice soltanto a livello pistole!! self.get_ean_from_cod_alias(cod_art, "341.00393") if self.is_number(qta): self.cursor.execute( "INSERT TDtb_DettaglioBolle (iFblId, sDtbCodArt, fDtbQta) VALUES (%d, '%s', %d)" %(id_fbl, cod_art, float(qta))) return [num_bolla, datetime.datetime.strptime(str(data_bolla), "%Y%m%d").strftime("%Y-%m-%d"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), id_fbl]
def write_dtl_00118(self, id_fbl, email_data): # ************ BOSCH utilizza file csv servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, # Messaggio generico (datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00018", "")) # logging.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00018") num_bolla = 0 data_bolla = datetime.datetime.now().strftime("%d/%m/%Y") for file_row in email_data["raw_file"].decode().split("\n"): riga_lista = file_row.replace("\n", "").replace("\r", "").split(";") if len(riga_lista) >= 5: qta = riga_lista[3] if self.is_number(qta): num_bolla = riga_lista[0].replace("'", "")[-6:] cod_art = riga_lista[1] row_cod_art_ean = self.get_ean_from_cod_forn(cod_art, "341.00118") if row_cod_art_ean is not None: cod_art = row_cod_art_ean[0] self.cursor.execute( "INSERT TDtb_DettaglioBolle (iFblId, sDtbCodArt, fDtbQta) VALUES (%d, '%s', %d)" %(id_fbl, cod_art, float(qta))) # N.B.: il secondo parametro è la data bolla che al momento non mi viene passata nel file. DA GESTIRE. return [num_bolla, datetime.datetime.strptime(str(data_bolla), "%d/%m/%Y").strftime("%Y-%m-%d %H:%M:%S"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), id_fbl]
def write_dtl_00034(self, id_fbl, email_data): # ************ ELMI utilizza file xls servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, # Messaggio generico (datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00034", "")) # logging.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00034") import xlrd num_bolla = 0 data_bolla = datetime.datetime.now().strftime("%d/%m/%Y") xl_workbook = xlrd.open_workbook(file_contents=email_data["raw_file"]) xl_sheet = xl_workbook.sheet_by_index(0) for row in xl_sheet.get_rows(): qta = row[13].value if self.is_number(qta): num_bolla = int(row[1].value) cod_art = row[9].value row_cod_art_ean = self.get_ean_from_cod_forn(cod_art, "341.00034") if row_cod_art_ean is not None: cod_art = row_cod_art_ean[0] data_bolla = row[2].value self.cursor.execute( "INSERT TDtb_DettaglioBolle (iFblId, sDtbCodArt, fDtbQta) VALUES (%d, '%s', %d)" % (id_fbl, cod_art, float(qta))) return [num_bolla, datetime.datetime.strptime(str(data_bolla), "%d/%m/%Y").strftime("%Y-%m-%d"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), id_fbl]
def write_dtl_00031(self, id_fbl, email_data): # ************ NEW FORM utilizza file csv servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, # Messaggio generico (datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00031", "")) # logging.info(datetime.datetime.now().strftime("%Y-%m-%d %H:%M") + " write_dtl_00031") num_bolla = 0 for file_row in email_data["raw_file"].decode().split("\n"): riga_lista = file_row.replace("\n", "").replace("\r", "").split(";") if len(riga_lista) >= 5: qta = riga_lista[5].replace(",", ".") if self.is_number(qta): data_bolla = riga_lista[1].replace('"', '') num_bolla = str(int(riga_lista[0].replace('"', '')[-6:])) # Leggo codice EAN dal file e lo scrivo nel database frontiera. Non necessita di alcuna riconversione cod_art = riga_lista[4].replace(".", "").replace('"', '') # In questo caso serve solo per compilare il messaggio mail da inviare altrimenti # mi accorgerei della mancanza del codice soltanto a livello pistole!! self.get_ean_from_cod_alias(cod_art, "341.00031") self.cursor.execute( "INSERT TDtb_DettaglioBolle (iFblId, sDtbCodArt, fDtbQta) VALUES (%d, '%s', %d)" %(id_fbl, cod_art, float(qta))) return [num_bolla, datetime.datetime.strptime(data_bolla, "%Y%m%d").strftime("%Y-%m-%d"), datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), id_fbl]
def SvcDoRun(self): # do nothing at all - just wait to be stopped win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) # Write a stop message. servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ''))
def SvcDoRun(self): server = Server() # in practice, you will want to specify a value for # log.error_file below or in your config file. If you # use a config file, be sure to use an absolute path to # it, as you can't be assured what path your service # will run in. cherrypy.config.update({ 'global': { 'log.screen': False, 'engine.autoreload.on': False, 'engine.SIGHUP': None, 'engine.SIGTERM': None, 'log.error_file': os.path.join(server.base_dir, 'libreosteo_error.log'), 'tools.log_tracebacks.on': True, 'log.access_file': os.path.join(server.base_dir, 'libreosteo_access.log'), 'server.socket_port': 8085, 'server.socket_host': '0.0.0.0', } }) self.ReportServiceStatus(win32service.SERVICE_RUNNING) servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) server.run()
def SvcDoRun(self): servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'') ) self.main()
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.isAlive = True # Create new threads self.main()
def SvcDoRun(self): self.isAlive = True servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) self.main()
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) import gramex gramex.shutdown() win32event.SetEvent(self.hWaitStop) servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, ''))
def SvcDoRun(self): """Core service logic""" # Go to module install directory install_dir_ = os.path.dirname(__file__) if install_dir_: os.chdir(install_dir_) # "Service started" message to Windows Event Log sm.LogMsg( # pylint: disable-msg=E1101 sm.EVENTLOG_INFORMATION_TYPE, # pylint: disable-msg=E1101 sm.PYS_SERVICE_STARTED, # pylint: disable-msg=E1101 (self._svc_name_, "")) try: rc_ = None # if the stop event hasn't been fired keep looping while rc_ != w32e.WAIT_OBJECT_0: # pylint: disable-msg=E1101 # Actuate job self.__actuate() # Pause for EXEC_INTERVAL and listen for a stop event every STOP_CHECK_INTERVAL ei_ = getattr(_conf.m, "EXEC_INTERVAL", EXEC_INTERVAL) si_ = getattr(_conf.m, "STOP_CHECK_INTERVAL", STOP_CHECK_INTERVAL) ic_ = ei_ / si_ while ic_ > 0 and rc_ != w32e.WAIT_OBJECT_0: # pylint: disable-msg=E1101 ic_ -= 1 rc_ = w32e.WaitForSingleObject(self.hWaitStop, si_) # pylint: disable-msg=E1101 except Exception: # pylint: disable-msg=W0703 sm.LogErrorMsg(traceback.format_exc()) # pylint: disable-msg=E1101
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) status = {} while not self.halt: cron(status)
def SvcOtherEx(self, control, event_type, data): # This is only showing a few of the extra events - see the MSDN # docs for "HandlerEx callback" for more info. if control == win32service.SERVICE_CONTROL_DEVICEEVENT: info = win32gui_struct.UnpackDEV_BROADCAST(data) msg = "A device event occurred: %x - %s" % (event_type, info) scanNics() elif control == win32service.SERVICE_CONTROL_HARDWAREPROFILECHANGE: msg = "A hardware profile changed: type=%s, data=%s" % (event_type, data) elif control == win32service.SERVICE_CONTROL_POWEREVENT: msg = "A power event: setting %s" % data elif control == win32service.SERVICE_CONTROL_SESSIONCHANGE: # data is a single elt tuple, but this could potentially grow # in the future if the win32 struct does msg = "Session event: type=%s, data=%s" % (event_type, data) else: msg = "Other event: code=%d, type=%s, data=%s" \ % (control, event_type, data) logging.info("Event " + msg) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, 0xF000, # generic message (msg, ''))
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) logging.info('Iniciando serviço') self._loop = True self.iniciar()
def SvcDoRun(self): # pylint: disable=invalid-name servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) main([], windows_service=True)
def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) #self.timeout = 640000 #640 seconds / 10 minutes (value is in milliseconds) self.timeout = 3600000 #3600 seconds / 1 hour # This is how long the service will wait to run / refresh itself (see script below) while 1: # Wait for service stop signal, if I timeout, loop again rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # Check to see if self.hWaitStop happened if rc == win32event.WAIT_OBJECT_0: # Stop signal encountered servicemanager.LogInfoMsg( "SomeShortNameVersion - STOPPED!") #For Event Log break else: #Ok, here's the real money shot right here. #[actual service code between rests] try: # file_path = "C:\whereever\my_REAL_py_work_to_be_done.py" # execfile(file_path) #Execute the script # inc_file_path2 = "C:\whereever\MORE_REAL_py_work_to_be_done.py" # execfile(inc_file_path2) #Execute the script # pyinstaller -F seed_spider.py ss._main() except: pass
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, 'Service is starting')) # Fire every minute self.timeout = 1000 * 60 while True: # Wait for service stop signal, otherwise loop again ret_code = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) # If stop signal encountered, quit if ret_code == win32event.WAIT_OBJECT_0: servicemanager.LogInfoMsg("Service is stopping") break # Otherwise, run our scripts and log the results to the event log else: self.counter += 1 log_output = "VulnService - %d loops and counting\n\n" % self.counter log_output += self.vbs_task() + "\n\n" log_output += self.dos_task() servicemanager.LogInfoMsg(log_output)
def SvcDoRun(self): self.ReportServiceStatus(win32service.SERVICE_RUNNING) servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.my_logger.info("Service Is Starting") self.main()