def start( self ): (type, state, ca, exitcode, svc_exitcode, checkpoint, waithint) = win32service.QueryServiceStatus( self.hs ) if logger().VERBOSE: logger().log( "[helper] starting chipsec service: handle = 0x%x, type = 0x%x, state = 0x%x" % (self.hs, type, state) ) if win32service.SERVICE_RUNNING == state: if logger().VERBOSE: logger().log( "[helper] chipsec service already running" ) else: try: win32service.StartService( self.hs, None ); state = win32service.QueryServiceStatus( self.hs )[1] while win32service.SERVICE_START_PENDING == state: time.sleep( 1 ) state = win32service.QueryServiceStatus( self.hs )[1] if win32service.SERVICE_RUNNING == state: if logger().VERBOSE: logger().log( "[helper] chipsec service started (SERVICE_RUNNING)" ) except win32service.error, (hr, fn, msg): if logger().VERBOSE: logger().log_bad(traceback.format_exc()) if (winerror.ERROR_ALREADY_EXISTS == hr or winerror.ERROR_SERVICE_ALREADY_RUNNING == hr): if logger().VERBOSE: logger().log( "[helper] chipsec service already exists: %s (%d)" % (msg, hr) ) else: win32service.CloseServiceHandle( self.hs ) self.hs = None string = "StartService failed: %s (%d)" % (msg, hr) logger().error( string ) raise OsHelperError(string,hr)
def start(self): """开启服务""" try: if self.handle: win32service.StartService(self.handle, None) except Exception as 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
async def start(self): status_info = win32service.QueryServiceStatus(self.handle) if status_info[1] == win32service.SERVICE_RUNNING: return True try: if self.handle: win32service.StartService(self.handle, None) except Exception as e: raise PermissionError("Ошибка запуска сервиса") status_info = win32service.QueryServiceStatus(self.handle) if status_info[1] == win32service.SERVICE_RUNNING: return True elif status_info[1] == win32service.SERVICE_START_PENDING: start_time = datetime.now() while True: if (datetime.now() - start_time).seconds > self.delay_time: raise TimeoutError("Таймаут запуска сервиса") time.sleep(self.wait_time) if (win32service.QueryServiceStatus( self.handle)[1] == win32service.SERVICE_RUNNING): return True else: raise PermissionError("Ошибка запуска сервиса")
def start(self): """Start service""" try: if self.handle: win32service.StartService(self.handle, None) except Exception as e: logging.info(e) status_info = win32service.QueryServiceStatus(self.handle) if status_info[1] == win32service.SERVICE_RUNNING: logging.info('Start %s successfully.', self.name) return 'Start %s successfully.' % (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: logging.info('Start %s too much time.', self.name) return 'Start %s too much time.' % (self.name) time.sleep(self.wait_time) if win32service.QueryServiceStatus( self.handle)[1] == win32service.SERVICE_RUNNING: logging.info('Start %s successfully.', self.name) return 'Start %s successfully.' % (self.name) else: logging.info('Start %s fail.', self.name) return 'Start %s fail.' % (self.name)
def fetchstatus(self, fstatus, timeout=None): self.fstatus = fstatus.upper() if timeout is not None: timeout = int(timeout) timeout *= 2 def to(timeout): time.sleep(.5) if timeout is not None: if timeout > 1: timeout -= 1 return timeout else: return "TO" if self.fstatus == "STOPPED": while 1: self.stat = win32service.QueryServiceStatus(self.handle) if self.stat[1] == win32service.SERVICE_STOPPED: self.fstate = "STOPPED" break else: timeout = to(timeout) if timeout == "TO": return "TIMEDOUT" break elif self.fstatus == "STOPPING": while 1: self.stat = win32service.QueryServiceStatus(self.handle) if self.stat[1] == win32service.SERVICE_STOP_PENDING: self.fstate = "STOPPING" break else: timeout = to(timeout) if timeout == "TO": return "TIMEDOUT" break elif self.fstatus == "RUNNING": while 1: self.stat = win32service.QueryServiceStatus(self.handle) if self.stat[1] == win32service.SERVICE_RUNNING: self.fstate = "RUNNING" break else: timeout = to(timeout) if timeout == "TO": return "TIMEDOUT" break elif self.fstatus == "STARTING": while 1: self.stat = win32service.QueryServiceStatus(self.handle) if self.stat[1] == win32service.SERVICE_START_PENDING: self.fstate = "STARTING" break else: timeout = to(timeout) if timeout == "TO": return "TIMEDOUT" break
def StartService(service): try: win32service.StartService(service, None) status = win32service.QueryServiceStatus(service)[1] while (status == win32service.SERVICE_START_PENDING): time.sleep(1) status = win32service.QueryServiceStatus(service)[1] return status == win32service.SERVICE_RUNNING except: return False
def sc(serviceName): # 获取“服务管理器”的句柄 scHandle = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) # do something ... print 'got SCM handle : %(scHandle)s' % locals() # 获取某个服务的句柄 serviceHandle = win32service.OpenService(scHandle, serviceName, win32service.SC_MANAGER_ALL_ACCESS) # 利用句柄查询该服务的状态信息 status = win32service.QueryServiceStatus(serviceHandle) PrintServiceStatus(status) # 也可以直接通过服务的名称来查询状态 status = win32serviceutil.QueryServiceStatus(serviceName) # 停止该服务 if isServiceRunning(serviceName): status = win32service.ControlService(serviceHandle, win32service.SERVICE_CONTROL_STOP) PrintServiceStatus(status) # 启动该服务 if not isServiceRunning(serviceName): win32serviceutil.StartService(serviceName) PrintServiceStatus(win32serviceutil.QueryServiceStatus(serviceName)) # 释放所取得的所有句柄 win32service.CloseServiceHandle(serviceHandle) win32service.CloseServiceHandle(scHandle)
def checkService(svcName): import win32service, time hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) try: hs = win32service.OpenService(hscm, svcName, win32service.SERVICE_ALL_ACCESS) except: logfile.write('can not open %s at %s \n' % (svcName, time.ctime())) return False if hs: status = win32service.QueryServiceStatus(hs) status = getServiceStatus(status) if status == 'running': return True if status == 'stopped' or status == 'stopping': logfile.write('%s stopped at %s\n' % (svcName, time.ctime())) try: win32service.StartService(hs, None) warningfile.write('%s started at %s\n' % (svcName, time.ctime())) return True except: warningfile.write('trying to start %s failed at %s\n' % (svcName, time.ctime())) else: logfile.write('controlling %s => all failed at %s\n' % (svcName, time.ctime()))
def checkHlyctlSvc(): hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) print hscm try: hlyhs = win32service.OpenService(hscm, "hlyctlsvc", win32service.SERVICE_ALL_ACCESS) except: f1.write('can not open hlysvc\n') print 'can not open hlysvc' return 'cannot open' if hlyhs: hlystatus = win32service.QueryServiceStatus(hlyhs) hlystatus = getServiceStatus(hlystatus) if hlystatus == 'stopping': time.sleep(1.0) if hlystatus =='stopped': print 'hly stopped' f2.write('hly stopped \n') try: win32serviceutil.StartService("hlyctlsvc", None, None) print 'hly started' f2.write('hly started \n') time.sleep(5.0) except: print 'hly start failed' time.sleep(10.0) f1.write('hly start failed\n') else : print 'rev running' f3.write('rev running\n')
def checkRevSvc(): hscm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS) print hscm try: revhs = win32service.OpenService(hscm, "revsvc", win32service.SERVICE_ALL_ACCESS) except: f1.write('not found revsvc\n') print 'not found revsvc' return 'not found' if revhs: revstatus = win32service.QueryServiceStatus(revhs) revstatus = getServiceStatus(revstatus) if revstatus == 'stopping': time.sleep(1.0) if revstatus == 'stopped': print 'rev stopped' f2.write('rev stopped \n') try: win32serviceutil.StartService("revsvc", None, None) print 'rev started' f2.write('rev started \n') time.sleep(5.0) except: print 'rev start failed' time.sleep(10.0) f1.write('rev start failed\n') else: print 'rev running' f3.write('rev running\n')
def stop(self): """Stop service""" try: status_info = win32service.ControlService( self.handle, win32service.SERVICE_CONTROL_STOP) except Exception as e: logging.info(e) if status_info[1] == win32service.SERVICE_STOPPED: logging.info('Stop %s successfully.', self.name) return 'Stop %s successfully.' % (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: logging.info('Stop %s too much time.', self.name) return 'Stop %s too much time.' % (self.name) time.sleep(self.wait_time) if win32service.QueryServiceStatus( self.handle)[1] == win32service.SERVICE_STOPPED: logging.info('Stop %s successfully.', self.name) return 'Stop %s successfully.' % (self.name) else: logging.info('Stop %s fail.', self.name) return 'Stop %s fail.' % (self.name)
def is_stop(self): flag = False if self.handle: ret = win32service.QueryServiceStatus(self.handle) flag = ret[1] != win32service.SERVICE_RUNNING return flag
def infotype(self): self.stat = ws.QueryServiceStatus(self.handle) if self.stat[0] and ws.SERVICE_WIN32_OWN_PROCESS: print "The %s service runs in its own process." % self.lserv if self.stat[0] and ws.SERVICE_WIN32_SHARE_PROCESS: print "The %s service shares a process with other services." % self.lserv if self.stat[0] and ws.SERVICE_INTERACTIVE_PROCESS: print "The %s service can interact with the desktop." % self.lserv
def infoctrl(self): self.stat = win32service.QueryServiceStatus(self.handle) if self.stat[2] and win32service.SERVICE_ACCEPT_PAUSE_CONTINUE: print("The %s service can be paused." % self.lserv) if self.stat[2] and win32service.SERVICE_ACCEPT_STOP: print("The %s service can be stopped." % self.lserv) if self.stat[2] and win32service.SERVICE_ACCEPT_SHUTDOWN: print("The %s service can be shutdown." % self.lserv)
def StopService(serviceName): retval = False manager = None service = None try: manager = win32service.OpenSCManager('localhost', 'ServicesActive', win32service.SC_MANAGER_CONNECT) service = win32service.OpenService( manager, serviceName, win32service.SERVICE_STOP | win32service.SERVICE_QUERY_STATUS) status = win32service.QueryServiceStatus(service) if status[1] == win32service.SERVICE_STOP_PENDING or status[ 1] == win32service.SERVICE_STOPPED: print(('Service %s is already stopped (%s)' % (serviceName, GetCurrentStateStr(state)[0]))) else: print(('Stopping service %s' % serviceName)) if win32service.ControlService(service, win32service.SERVICE_CONTROL_STOP): win32api.Sleep(1000) stopped = False slept = 0 while not stopped and slept < 5: status = win32service.QueryServiceStatus(service) if status[1] == win32service.SERVICE_STOPPED: stopped = True else: win32api.Sleep(500) slept += 1 retval = True except Exception as inst: if len(inst.args) == 3: number = inst.args[0] function = inst.args[1] message = inst.args[2] print(('ERROR stopping service: %#08x (%s): %s' % (number, function, message))) else: print(('ERROR stopping service: %s' % inst)) finally: if service: win32service.CloseServiceHandle(service) if manager: win32service.CloseServiceHandle(manager) return retval
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)
def is_stop(self): """Check service whether stop""" flag = False try: if self.handle: ret = win32service.QueryServiceStatus(self.handle) flag = ret[1] != win32service.SERVICE_RUNNING except Exception as e: logging.info(e) return flag
def stop( self ): state = 0 if (self.hs is not None): if logger().VERBOSE: logger().log( "[helper] stopping service (handle = 0x%08x).." % self.hs ) try: state = win32service.ControlService( self.hs, win32service.SERVICE_CONTROL_STOP ) #state = win32serviceutil.StopService( name, machine )[1] except win32service.error, (hr, fn, msg): logger().error( "StopService failed: %s (%d)" % (msg, hr) ) state = win32service.QueryServiceStatus( self.hs )[1]
def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. 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 restart(self): """重启服务""" try: self.handle = win32service.OpenService(self.scm, self.name, win32service.SC_MANAGER_ALL_ACCESS) except Exception as e: self.log(e) if not self.is_stop(): self.stop() self.start() return win32service.QueryServiceStatus(self.handle)
def status(self): 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"
def isStop(self, name): flag = False try: handle = win32service.OpenService( self.scm, name, win32service.SC_MANAGER_ALL_ACCESS) if handle: ret = win32service.QueryServiceStatus(handle) flag = ret[1] != win32service.SERVICE_RUNNING win32service.CloseServiceHandle(handle) except Exception, e: logging.error(e)
def get_status(self): if not self.status: try: s = win32service.QueryServiceStatus(self.get_sh_query_status()) self.status = s[1] if self.status == 1: self.status = "STOPPED" elif self.status == 4: self.status = "STARTED" except: pass return self.status
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)
def QueryServiceStatus(serviceName, machine=None): hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_CONNECT) try: hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_QUERY_STATUS) try: status = win32service.QueryServiceStatus(hs) finally: win32service.CloseServiceHandle(hs) finally: win32service.CloseServiceHandle(hscm) return status
def __StopServiceWithTimeout(hs, waitSecs = 30): try: status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP) except pywintypes.error as exc: if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise for i in range(waitSecs): status = win32service.QueryServiceStatus(hs) if status[1] == win32service.SERVICE_STOPPED: break win32api.Sleep(1000) else: raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
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 status(self): """Get the state of service""" 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 as e: logging.info(e)
def OnInitDialog(self): cfg = win32service.QueryServiceConfig(self.service) self.GetDlgItem(self.IDC_BOOT + cfg[1]).SetCheck(1) status = win32service.QueryServiceStatus(self.service) if ((status[0] & win32service.SERVICE_KERNEL_DRIVER) or (status[0] & win32service.SERVICE_FILE_SYSTEM_DRIVER)): # driver self.GetDlgItem(self.IDC_LABEL).SetWindowText('Device:') else: # service self.GetDlgItem(self.IDC_LABEL).SetWindowText('Service:') self.GetDlgItem(self.IDC_BOOT).EnableWindow(0) self.GetDlgItem(self.IDC_SYSTEM).EnableWindow(0) self.GetDlgItem(self.IDC_DEVICE).SetWindowText(str(self.name)) return dialog.Dialog.OnInitDialog(self)
def stop(self): """停止服务""" try: status_info = win32service.ControlService(self.handle, win32service.SERVICE_CONTROL_STOP) except Exception as e: return e if status_info[1] == win32service.SERVICE_STOPPED: return '停止服务%s成功!'% 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时间太长!'% self.name time.sleep(self.wait_time) if win32service.QueryServiceStatus(self.handle)[1] == win32service.SERVICE_STOPPED: return '停止服务%s成功!' % self.name else: return '停止服务%s失败!'% self.name