def install_drivers_windows(): print "installing drivers" servicemanager.LogInfoMsg("installing drivers") driver_path = os.environ['PROGRAMFILES'] + "\codebender/drivers/Windows/" if platform.machine() == "x86": driver_cmd = "dpinst-x86.exe /sw" else: driver_cmd = "dpinst-amd64.exe /sw" print "Installation Path: ", driver_path print "Installation cmd: ", driver_cmd logging.info("Installation Path:") logging.info(driver_path) logging.info("Installation CMD:") logging.info(driver_cmd) servicemanager.LogInfoMsg("installing drivers. path: " + driver_path + " & cmd: " + driver_cmd) proc = subprocess.Popen(driver_cmd, stdout=subprocess.PIPE, shell=True, cwd=driver_path) (out, err) = proc.communicate() print "program output:", out print "program error:", err servicemanager.LogInfoMsg("program output:" + str(out)) servicemanager.LogInfoMsg("program error:" + str(err)) print proc.returncode return proc.returncode
def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.timeout = 3000 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("aservice - STOPPED") break else: servicemanager.LogInfoMsg("aservice - is alive and well") #Ok, here's the real money shot right here. #[actual service code between rests] try: #file_path = "startfox.py" #execfile(file_path) #Execute the script winsound.Beep(400, 300) print 'iwifiwefi' except: pass
def main(self): # Здесь выполняем необходимые действия при старте службы servicemanager.LogInfoMsg("Hello! I'm a Dummy Service.") while True: # Здесь должен находиться основной код сервиса servicemanager.LogInfoMsg("I'm still here.") # Проверяем не поступила ли команда завершения работы службы rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) if rc == win32event.WAIT_OBJECT_0: # Здесь выполняем необходимые действия при остановке службы servicemanager.LogInfoMsg("Bye!") break # Здесь выполняем необходимые действия при приостановке службы if self._paused: servicemanager.LogInfoMsg("I'm paused... Keep waiting...") # Приостановка работы службы while self._paused: # Проверям не поступила ли команда возобновления работы службы rc = win32event.WaitForSingleObject(self.hWaitResume, self.resumeTimeout) if rc == win32event.WAIT_OBJECT_0: self._paused = False # Здесь выполняем необходимые действия при возобновлении работы службы servicemanager.LogInfoMsg("Yeah! Let's continue!") break
def main(self): # Actions which need run when service will start servicemanager.LogInfoMsg("Python service is started") while True: # MAIN SERVICE CODE servicemanager.LogInfoMsg("I'm still here.") # Проверяем не поступила ли команда завершения работы службы # Checking for 'end service' command rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) if rc == win32event.WAIT_OBJECT_0: # Actions which need run when service will stop servicemanager.LogInfoMsg("Service stopped !") break # Actions which need run when service will pause if self._paused: servicemanager.LogInfoMsg("Service on pause") # Pause service while self._paused: # Проверям не поступила ли команда возобновления работы службы # Checking for 'continue service' command rc = win32event.WaitForSingleObject(self.hWaitResume, self.resumeTimeout) if rc == win32event.WAIT_OBJECT_0: self._paused = False # Здесь выполняем необходимые действия при возобновлении работы службы # Actions which need run when service will continue servicemanager.LogInfoMsg("Service work is continued") break
def inactive_cleanup(exit_event): while True: exit_event.wait(60.0) if exit_event.is_set(): try: all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) for server, oid, ctime, xtime in all_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) except Exception as e: servicemanager.LogInfoMsg('\n\nException %s happen when stop opc gateway service' % e) finally: exit_event.clear() return else: try: all_sessions = OpenOPC.get_sessions(host=opc_gate_host, port=opc_gate_port) if len(all_sessions) > max_clients: stale_sessions = sorted(all_sessions, key=lambda s: s[3])[:-max_clients] else: stale_sessions = [s for s in all_sessions if time.time() - s[3] > (inactive_timeout * 60)] for server, oid, ctime, xtime in stale_sessions: OpenOPC.close_session(oid, host=opc_gate_host, port=opc_gate_port) time.sleep(1) except Exception as e: servicemanager.LogInfoMsg('\n\nException %s happen when cleanup timeout session' % e)
def SvcDoRun(self): servicemanager.LogInfoMsg('\n\nStarting service\nOPC_GATE_HOST=%s\nOPC_GATE_PORT=%d\nOPC_MAX_CLIENTS=%d\nOPC_INACTIVE_TIMEOUT=%d' % ('localhost' if opc_gate_host is None else opc_gate_host, opc_gate_port, max_clients, inactive_timeout)) exit_event = threading.Event() p = threading.Thread(target=inactive_cleanup, args=(exit_event,)) p.start() daemon = Pyro4.core.Daemon(host=opc_gate_host, port=opc_gate_port) uri = daemon.register(opc(), "opc") servicemanager.LogInfoMsg("\n\nStartup opc pyro daemon(%s)" % uri.asString()) stop_pending = False 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.sockets ins,outs,exs = select.select(socks,[],[],1) for s in socks: if s in ins: daemon.events(ins) break p.join() daemon.shutdown()
def main(db_name): import servicemanager pg_dump = PgDumpCli(db_name) servicemanager.LogInfoMsg("Starting %s backup sequence" % pg_dump.db_name) try: p = Popen(pg_dump(), stderr=PIPE, stdout=PIPE, env=pg_dump.env) out, err = p.communicate(timeout=TIMEOUT) if p.returncode: # error code returned servicemanager.LogWarningMsg( "There was an error during %s backup.\n" "pg_dump response is:\n %s" % (pg_dump.db_name, err.decode("cp866", errors='ignore'))) else: # successfull completion servicemanager.LogInfoMsg("%s backup sequence complete" % pg_dump.db_name) history_manager = BackupHistoryManager(db_name) history_manager() except OSError: # bad command servicemanager.LogErrorMsg("There was an error during %s backup.\n" "pg_dump.exe was not found at %s" % (pg_dump.db_name, pg_dump.pg_dump_dir)) except TimeoutExpired: p.kill() servicemanager.LogErrorMsg("There was an error during %s backup.\n" "Timeout expired" % pg_dump.db_name)
def main(): import sys import log from reboot import RebootServer,AbortReboot import servicemanager args = sys.argv[1:] if len(args) == 0: usage(sys.argv[0]) for arg in args: server = arg errmsg = pingserver(server) rcnt = log.getint('record','rebootcount') if errmsg: if rcnt < 3: rcnt += 1 log.set('record','rebootcount',rcnt) message = '%s is not responsive, This server is going to reboot in 30 seconds' % server servicemanager.LogInfoMsg(message) RebootServer(message) raw_input('Press any key to stop reboot...') AbortReboot() servicemanager.LogInfoMsg('Reboot is been cancelled.') else: message = '%s is not responsive, but rebootcount is over %d, not more reboot' % (server,rcnt) servicemanager.LogInfoMsg(message) else: log.set('record','rebootcount',0) message = '%s is alive.' % (server) #servicemanager.LogInfoMsg(message) print message
def main(self): home_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), '..')) # home_dir = 'c:\\Users\\IEUser' servicemanager.LogInfoMsg('HOME DIR: %s' % home_dir) conffile = os.path.join(home_dir, 'psistats.conf') if os.path.exists(conffile) == False: raise Exception("%s does not exist" % conffile) conf = config.load(conffile) fileConfig(conffile) logger = logging.getLogger('psistats2') logger.info('Starting psistats2') servicemanager.LogInfoMsg('Starting Manager thread') manager = Manager(conf, reportClass=PsistatsReport) manager.start() while True: if self.need_to_stop is True: break time.sleep(5) servicemanager.LogInfoMsg('Stopping Manager thread') manager.stop() servicemanager.LogInfoMsg('Done')
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): import servicemanager self._log.info("%s - Starting" % self._svc_name_) servicemanager.LogInfoMsg("%s - Starting" % self._svc_name_) try: # Config file name is hardcoded config_file = "config.cfg" # Try to find the configuration file looking up # from the script file # It's a messy kludge but I couldn't find better import os.path path = os.path.abspath(os.path.dirname(__file__)) last_path = path self._log.info("%s - Searching for config in (%s)" % (self._svc_name_, last_path)) while not os.access(path + "/" + config_file, os.R_OK): (path, _) = os.path.split(path) if path == last_path: last_path = None print "Not found aborting" break last_path = path self._log.info("%s - Searching for config in (%s)" % (self._svc_name_, last_path)) if last_path == None: self._log.error( "%s - Unable to locate configuration file (%s)" % (self._svc_name_, config_file)) servicemanager.LogErrorMsg( "%s - Unable to locate configuration file (%s)" % (self._svc_name_, config_file)) return # Change working directory os.chdir(last_path) # init python logging (Anything logged before that had been lost) logging.config.fileConfig(config_file) self._log.info("%s - Changing working directory to (%s)" % (self._svc_name_, last_path)) # Start self._log.info("%s - Starting Moniteur" % self._svc_name_) self.application = Moniteur(config_file) self.application.start() self._log.info("%s - Started" % self._svc_name_) servicemanager.LogInfoMsg("%s - Started" % self._svc_name_) while self.isAlive: time.sleep(5) self._log.info("%s - Stopping" % self._svc_name_) servicemanager.LogInfoMsg("%s - Stopping" % self._svc_name_) except: pass
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) if self.warden_server: servicemanager.LogInfoMsg("Warden shutting down...") self.warden_server._shutdown() servicemanager.LogInfoMsg("Warden shut down complete") win32event.SetEvent(self.hWaitStop)
def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) sm.LogInfoMsg("sent stop event") self.daemon.stop() win32event.SetEvent(self.hWaitStop) sm.LogInfoMsg("Statser - STOPPED") self.ReportServiceStatus(win32service.SERVICE_STOPPED)
def SvcDoRun(self): servicemanager.LogInfoMsg( 'Neutron Hyper-V Agent: Starting (C:\\Python27\\Scripts\\neutron-hyperv-agent.exe %s)' % sys.argv[1]) self.p = subprocess.Popen( ["C:\\Python27\\Scripts\\neutron-hyperv-agent.exe", sys.argv[1]]) self.p.wait() servicemanager.LogInfoMsg("Neutron Hyper-V Agent: Stopped")
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) self.timeout = 3 * 1000 * 60 * 60 # 3 hours wait time self.weekendTimeoutExtra = 0 logging.info("Starting SvcDoRun with timeout: {0} seconds".format( self.timeout * 0.001)) logging.info("msBloombergForecastService start modules") try: logging.info("Run Bloomberg Forecasts Model") self.forecasts = createBloombergForecastDB(dev=True) self.LaunchModelScript() except: self.sendErrorMail(str(traceback.format_exc())) logging.info("Connection failed with: {0}".format( traceback.format_exc())) servicemanager.LogErrorMsg(traceback.format_exc()) raise logging.info("msBloombergForecastService initiated: run SvcDoRun") while 1: rc = win32event.WaitForSingleObject( self.hWaitStop, self.timeout + self.weekendTimeoutExtra) if rc == win32event.WAIT_OBJECT_0: servicemanager.LogInfoMsg("msBloombergForecastService Stopped") break else: try: servicemanager.LogInfoMsg( "msBloombergForecastService: Getting started") logging.info( "Opening Forecasts Bloomberg within Service: ") now = datetime.datetime.now() if (now.isoweekday() <= 5): logging.info("Update dataset: Bloomberg Forecasts") self.LaunchModelScript() self.weekendTimeoutExtra = 0 else: logging.info( "Stop for the Weekend at {0:%A %Y-%m-%d %H:%M}". format(now)) self.weekendTimeoutExtra = 24 * 1000 * 60 * 60 # 24 hours logging.info( "Next check will be: {0:%Y-%m-%d %H:%M}".format( now + datetime.timedelta(seconds=( (self.timeout + self.weekendTimeoutExtra) * 0.001)))) except: self.sendErrorMail(str(traceback.format_exc())) logging.info("Connection failed with: {0}".format( traceback.format_exc())) servicemanager.LogErrorMsg(traceback.format_exc()) pass
def SvcDoRun(self): home = win32serviceutil.GetServiceCustomOption( WardenService._svc_name_, 'WARDEN_HOME', defaultValue=None) home = AutoConf.get_home(home) servicemanager.LogInfoMsg( "Warden starting up (home directory: %s) ..." % home) self.warden_server = WardenServer.WardenServer(home) self.warden_server._startup() servicemanager.LogInfoMsg("Warden start up complete") win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
def kill_proc_tree(pid, including_parent=True): parent = psutil.Process(pid) for child in parent.get_children(recursive=True): servicemanager.LogInfoMsg( "Neutron Hyper-V Agent: Stopping (Killing child: %s)" % child) child.kill() if including_parent: servicemanager.LogInfoMsg( "Neutron Hyper-V Agent: Stopping (Killing parent: %s)" % parent) parent.kill()
def SvcDoRun(self): import servicemanager from driver 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 __init__(self, args): try: win32serviceutil.ServiceFramework.__init__(self,args) servicemanager.LogInfoMsg("Logging to: " + log_location) print("Initialising...") servicemanager.LogInfoMsg("Initialising...") self.hWaitStop = win32event.CreateEvent(None,0,0,None) self.isAlive = True except Exception as e: print("Error: " + str(e)) servicemanager.LogErrorMsg("Error: " + str(e))
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) servicemanager.LogInfoMsg('ceajenkins before main') try: self.main() except: servicemanager.LogErrorMsg(traceback.format_exc()) sys.exit(-1) servicemanager.LogInfoMsg('normal exit')
def main(self): self.timeOut = 10 # milliseconds service = Service(CONFIG.mode, CONFIG.port, CONFIG.password, True) while True: rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeOut) if rc == win32event.WAIT_OBJECT_0: servicemanager.LogInfoMsg("ButrManager - STOPPED") break else: servicemanager.LogInfoMsg("ButrManager - RUNNING") service.run_once()
def SvcDoRun(self): """ Start the Windows service. """ servicemanager.LogInfoMsg("Starting %s..." % self._svc_name_) self.main() servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '') ) servicemanager.LogInfoMsg("%s started." % self._svc_name_)
def SvcDoRun(self): import servicemanager servicemanager.LogInfoMsg("OpenStack Compute: Starting") server = service.Service.create(binary='nova-compute', topic=CONF.compute_topic, db_allowed=False) service.serve(server) while self.isAlive: time.sleep(5) servicemanager.LogInfoMsg("OpenStack Compute: Stopped")
def checkForStop(self): self.timeout = 60000 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("LexinSmartDeamon - STOPPED") # TODO: Improve this. Windows consider it an error right now os._exit(0) else: servicemanager.LogInfoMsg("LexinSmartDeamon - is alive and well")
def release_client(self, obj): """Release a OpenOPC client instance in the Pyro server""" try: guid = obj.GUID() self._pyroDaemon.unregister(obj) except Exception as e: servicemanager.LogInfoMsg('\n\nException %s happen when unregister client %s from Pyro daemon' % (e, guid)) finally: del self._opc_objects[guid] del self._init_times[guid] del self._last_times[guid] servicemanager.LogInfoMsg('\n\nDestroy client %s' % guid)
def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.timeout = 1000 config = os.path.join(base_dir, "config.txt") servicemanager.LogInfoMsg('Starting with Config.txt from %s'%config) #logger.info('Read Config.txt from %s'%config) read_config(config) #logger.info('Start Http Server on Port %s'%PORT) servicemanager.LogInfoMsg('Start Http Server on Port %s'%PORT) start_http_server(int(PORT)) REGISTRY.register(CustomCollector()) self.ReportServiceStatus(win32service.SERVICE_RUNNING) self.main()
def SvcStop(self): """ Stop the Windows service. Kills the running task nicely and then forcefully if being nice didn't work. """ # Explored a number of options here. The simplest would have been to # run the webapp with in another process and then shut it down. # However this isn't compatible with virtualenv: # https://stackoverflow.com/questions/10124768/python-pywin32-windows-service-and-multiprocessing # http://bugs.python.org/issue5162 # TODO: Test this without virtualenv. Shouldn't use services with virtualenv. # os.kill is supported on Windows in Python 2.7 but requires we know the # pid which we don't have easy access to. # See Windows-specific info: https://docs.python.org/2/library/os.html#os.kill # Threading option: # https://stackoverflow.com/a/35576127/3642440 # taskkill allows us to use the service name so it seems the most # straightforward. # https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb491009(v=technet.10) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) servicemanager.LogInfoMsg("Stopping ShotgunJiraBridge...") try: os.system("taskkill /fi 'SERVICES eq %s'" % self._svc_name_) # Give the process some time to exit nicely time.sleep(0.1) # forcefully kill the process if it's still running but ignore errors try: os.system("taskkill /f /fi 'SERVICES eq %s'" % self._svc_name_) except OSError: pass except OSError as e: # Catch the error in case the process exited between our check and our # attempt to stop it. servicemanager.LogErrorMsg("Unable to shutdown %s: %s" % ( self._svc_name_, e )) else: self.ReportServiceStatus(win32service.SERVICE_STOPPED) servicemanager.LogInfoMsg("%s stopped." % 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): 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): # NOQA """Service main.""" self.ReportServiceStatus(win32service.SERVICE_RUNNING) servicemanager.LogInfoMsg("Service is starting.") rc = None log_header() while rc != win32event.WAIT_OBJECT_0: try: pass except Exception: for l in traceback.format_exc().splitlines(): logging.error(l) break rc = win32event.WaitForSingleObject(self.hWaitStop, 0) log_footer() servicemanager.LogInfoMsg("Service is finished.")