Exemple #1
0
 def Service_Query():
     ml_service_query = win32serviceutil.QueryServiceStatus('MysticLight2_Service')
     print(ml_service_query)
     if ml_service_query[2] == 0:
         return("Stopped")
     else:
         return("Running")
Exemple #2
0
def status_service(service_name):
    try:
        result = win32serviceutil.QueryServiceStatus(service_name)[1]
        if result == START_PENDING:
            print("service %s is %s, please wait" %
                  (service_name, status_code[result]))
            time.sleep(2)
            return RUNNING
        elif result == STOP_PENDING:
            print("service %s is %s, please wait" %
                  (service_name, status_code[result]))
            time.sleep(2)
            return STOPPED
        else:
            return result if result is not None else 0
    except Exception as e:
        if e:
            raise RuntimeError(str(e))
        elif e.args:
            # print e.args
            args = list()
            for arg in e.args:
                if is_iterable(arg):
                    args.append(unicode(eval(repr(arg)), 'gbk'))
                else:
                    args.append(arg)
            print("Error:", args[-1], tuple(args))
            raise RuntimeError
        else:
            raise RuntimeError(
                "Uncaught exception, maybe it is a 'Access Denied'"
            )  # will not reach here
Exemple #3
0
 def service_info(self, action, machine, service):
     #Interacts with the Window's service controller
     #The netconnection must be completed first
     #If netconnection is not done first, a Permission denied may return from SC controller
     if action == 'stop':
         win32serviceutil.StopService(service, machine)
         print '%s stopped successfully' % service
     elif action == 'start':
         win32serviceutil.StartService(service, None, machine)
         print '%s started successfully' % service
     elif action == 'restart':
         win32serviceutil.RestartService(service, machine)
         print '%s restarted successfully' % service
     elif action == 'status':
         #print win32serviceutil.QueryServiceStatus(service, machine)
         retStatus = win32serviceutil.QueryServiceStatus(service,
                                                         machine)[1]
         if retStatus == self.RUNNING:  # scvType, svcState, svcControls, err, svcErr, svcCP, svcWH
             print "%s on %s is running" % (service, machine)
             return self.RUNNING
         elif retStatus == self.STARTING:
             print '%s on %s is STARTING' % (service, machine)
             return self.STARTING
         elif retStatus == self.STOPPING:
             print '%s on %s is STOPPING' % (service, machine)
             return self.STOPPING
         elif retStatus == self.STOPPED:
             print '%s on %s is STOPPED***************' % (service, machine)
             return self.STOPPED
         else:
             print "Failed to get status for %s on %s" % (service, machine)
Exemple #4
0
    def delete(self, start_driver):
        if not start_driver: return True
        if self.use_existing_service: return True

        if win32serviceutil.QueryServiceStatus(
                SERVICE_NAME)[1] != win32service.SERVICE_STOPPED:
            if logger().DEBUG:
                logger().warn(
                    "cannot delete service '{}' (not stopped)".format(
                        SERVICE_NAME))
            return False

        if logger().DEBUG:
            logger().log(
                "[helper] deleting service '{}'...".format(SERVICE_NAME))
        try:
            win32serviceutil.RemoveService(SERVICE_NAME)
            if logger().DEBUG:
                logger().log(
                    "[helper] service '{}' deleted".format(SERVICE_NAME))
        except win32service.error as err:
            if logger().DEBUG:
                logger().warn("RemoveService failed: {} ({:d})".format(
                    err[2], err[0]))
            return False

        return True
    def Imap(self, request, context):
        print("Running IMAP script")
        if win32serviceutil.QueryServiceStatus("IMAP4A")[1] != 4:
            win32serviceutil.StartService("IMAP4A")

        sleep(3)
        return helloworld_pb2.HelloReply(message='IMAP script finished')
Exemple #6
0
    def start(self, start_driver, driver_exists=False):
        # we are in native API mode so not starting the service/driver
        if not start_driver: return True

        self.use_existing_service = (win32serviceutil.QueryServiceStatus(
            SERVICE_NAME)[1] == win32service.SERVICE_RUNNING)

        if self.use_existing_service:
            self.driver_loaded = True
            if logger().DEBUG:
                logger().log("[helper] service '{}' already running".format(
                    SERVICE_NAME))
            if logger().DEBUG:
                logger().log(
                    "[helper] trying to connect to existing '{}' service...".
                    format(SERVICE_NAME))
        else:
            #if self.use_existing_service:
            #    _handle_error( "connecting to existing '{}' service failed (service is not running)".format(SERVICE_NAME) )
            try:
                win32serviceutil.StartService(SERVICE_NAME)
                win32serviceutil.WaitForServiceStatus(
                    SERVICE_NAME, win32service.SERVICE_RUNNING, 1)
                self.driver_loaded = True
                if logger().DEBUG:
                    logger().log(
                        "[helper] service '{}' started".format(SERVICE_NAME))
            except pywintypes.error as err:
                _handle_error(
                    "service '{}' didn't start: {} ({:d})".format(
                        SERVICE_NAME, err[2], err[0]), err[0])

        return True
Exemple #7
0
def instart(cls, name, display_name=None, stay_alive=True):
    from os.path import splitext, abspath
    from sys import modules

    cls.__svc_name_ = name
    cls.__svc_display_name_ = display_name
    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__)
    if stay_alive: win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        try:
            print "[+] TestModule Started : %s" % (name)
            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:
            try:
                win32serviceutil.StartService(cls._svc_name_)
            except Exception, e:
                print "[!] %s : %s" % (e.__class__, str(e))
            else:
Exemple #8
0
    def checkRPFServiceIsRunning(self):
        """Check if the RPF service is running (required to use Ethernet NIOs)"""

        if not sys.platform.startswith("win"):
            return (0, None)

        import pywintypes
        import win32service
        import win32serviceutil

        try:
            if win32serviceutil.QueryServiceStatus(
                    "npf", None)[1] != win32service.SERVICE_RUNNING:
                return (
                    2,
                    "The NPF service is not running: open cmd.exe as an Administrator and type 'sc config npf start= auto && net start npf'"
                )
        except pywintypes.error as e:
            if e[0] == 1060:
                return (
                    2,
                    "The NPF service is not installed, please install Winpcap and reboot"
                )
            else:
                return (
                    2,
                    "Could not check if the NPF service is running: {}".format(
                        e[2]))
Exemple #9
0
def service_manager_status():
    try:
        return WIN_STATUS_TO_AGENT[
            win32serviceutil.QueryServiceStatus(DATADOG_SERVICE)[1]
        ]
    except Exception:
        return AGENT_UNKNOWN
Exemple #10
0
class CopyToSystemDir(installer.Installer):
    """Copy the distribution from the temp directory to the target."""

    pre = [CheckForWow64]

    def StopPreviousService(self):
        """Wait until the service can be stopped."""
        service = config.CONFIG["Nanny.service_name"]

        # QueryServiceStatus returns: scvType, svcState, svcControls, err,
        # svcErr, svcCP, svcWH
        try:
            status = win32serviceutil.QueryServiceStatus(service)[1]
        except pywintypes.error, e:
            logging.info(
                "Unable to query status of service: %s with error: %s",
                service, e)
            return

        for _ in range(20):
            if status == win32service.SERVICE_STOPPED:
                break
            elif status != win32service.SERVICE_STOP_PENDING:
                logging.info("Attempting to stop service %s", service)
                try:
                    win32serviceutil.StopService(service)
                except pywintypes.error, e:
                    logging.info("Unable to stop service: %s with error: %s",
                                 service, e)
            time.sleep(1)
            status = win32serviceutil.QueryServiceStatus(service)[1]
Exemple #11
0
 def setUp(self):
     try:
         win32serviceutil.QueryServiceStatus(service_name)
     except win32service.error, details:
         if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
             self.was_installed = False
         raise
Exemple #12
0
def delete_updates():
    """Returns commands for deleting Windows Updates files"""
    windir = bleachbit.expandvars('$windir')
    dirs = glob.glob(os.path.join(windir, '$NtUninstallKB*'))
    dirs += [bleachbit.expandvars('$windir\\SoftwareDistribution\\Download')]
    dirs += [bleachbit.expandvars('$windir\\ie7updates')]
    dirs += [bleachbit.expandvars('$windir\\ie8updates')]
    if not dirs:
        # if nothing to delete, then also do not restart service
        return

    import win32serviceutil
    wu_running = win32serviceutil.QueryServiceStatus('wuauserv')[1] == 4

    args = ['net', 'stop', 'wuauserv']

    def wu_service():
        General.run_external(args)
        return 0
    if wu_running:
        yield Command.Function(None, wu_service, " ".join(args))

    for path1 in dirs:
        for path2 in FileUtilities.children_in_directory(path1, True):
            yield Command.Delete(path2)
        if os.path.exists(path1):
            yield Command.Delete(path1)

    args = ['net', 'start', 'wuauserv']
    if wu_running:
        yield Command.Function(None, wu_service, " ".join(args))
Exemple #13
0
    def start(self, start_driver, driver_exists=False):
        # we are in native API mode so not starting the service/driver
        if not start_driver: return True

        self.use_existing_service = (win32serviceutil.QueryServiceStatus(
            SERVICE_NAME)[1] == win32service.SERVICE_RUNNING)

        if self.use_existing_service:
            self.driver_loaded = True
            if logger().DEBUG:
                logger().log("[helper] service '%s' already running" %
                             SERVICE_NAME)
            if logger().DEBUG:
                logger().log(
                    "[helper] trying to connect to existing '%s' service..." %
                    SERVICE_NAME)
        else:
            #if self.use_existing_service:
            #    _handle_error( "connecting to existing '%s' service failed (service is not running)" % SERVICE_NAME )
            try:
                win32serviceutil.StartService(SERVICE_NAME)
                win32serviceutil.WaitForServiceStatus(
                    SERVICE_NAME, win32service.SERVICE_RUNNING, 1)
                self.driver_loaded = True
                if logger().DEBUG:
                    logger().log("[helper] service '%s' started" %
                                 SERVICE_NAME)
            except pywintypes.error, (hr, fn, msg):
                _handle_error(
                    "service '%s' didn't start: %s (%d)" %
                    (SERVICE_NAME, msg, hr), hr)
Exemple #14
0
    def _checkWindowsService(self, service_name):

        try:
            import pywintypes
            import win32service
            import win32serviceutil
        except ImportError as e:
            log.error(
                "Could not check if the {} service is running: {}".format(
                    service_name, e))
            return

        try:
            if win32serviceutil.QueryServiceStatus(
                    service_name, None)[1] != win32service.SERVICE_RUNNING:
                return False
        except pywintypes.error as e:
            if e.winerror == 1060:  # service is not installed
                return False
            else:
                log.error(
                    "Could not check if the {} service is running: {}".format(
                        service_name, e.strerror))

        return True
Exemple #15
0
def StopService(service_name, service_binary_name=None):
    """Stop a Windows service with the given name.

  Args:
    service_name: string The name of the service to be stopped.
    service_binary_name: string If given, also kill this binary as a best effort
        fallback solution.
  """
    logging.info("Stopping Windows service %s; Binary name: %s", service_name,
                 service_binary_name)

    # QueryServiceStatus returns: scvType, svcState, svcControls, err,
    # svcErr, svcCP, svcWH
    try:
        status = win32serviceutil.QueryServiceStatus(service_name)[1]
    except pywintypes.error as e:
        logging.info("Unable to query status of service: %s with error: %s",
                     service_name, e)
        return

    for _ in range(20):
        if status == win32service.SERVICE_STOPPED:
            break
        elif status != win32service.SERVICE_STOP_PENDING:
            logging.info("Attempting to stop service %s", service_name)
            try:
                win32serviceutil.StopService(service_name)
            except pywintypes.error as e:
                logging.info("Unable to stop service: %s with error: %s",
                             service_name, e)
        time.sleep(1)
        status = win32serviceutil.QueryServiceStatus(service_name)[1]

    if status != win32service.SERVICE_STOPPED and service_binary_name is not None:
        # Taskkill will fail on systems predating Windows XP, this is a best
        # effort fallback solution.
        output = subprocess.check_output(
            ["taskkill", "/im",
             "%s*" % service_binary_name, "/f"],
            shell=True,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE)

        logging.debug("%s", output)

        # Sleep a bit to ensure that process really quits.
        time.sleep(2)
Exemple #16
0
def is_running(userName=getpass.getuser()):
    "Test if the chalmers sevice is running for 'userName'"
    svc_name = get_service_name(userName)
    try:
        status = win32serviceutil.QueryServiceStatus(svc_name)
    except win32api.error:
        return False
    return status[1] == win32service.SERVICE_RUNNING
Exemple #17
0
def is_installed(userName=getpass.getuser()):
    "Test if the chalmers sevice is installed for 'userName'"
    svc_name = get_service_name(userName)
    try:
        win32serviceutil.QueryServiceStatus(svc_name)
        return True
    except win32api.error:
        return False
def query_status(service_name):
    '''Query service status.'''
    try:
        raw_status = win32serviceutil.QueryServiceStatus(service_name)[1]
        return StatusCode(raw_status)
    except pywintypes.error:
        LOGGER.warning('Failed to query status of service [%s]')
        return StatusCode.SERVICE_UNKNOWN
 def essbase_service(self, machine):
     #Uses the SC Query to obtain Essbase running state and return a 1 or 0
     service = "EssbaseService"
     if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4:
         print "Essbase is running!!!!!!!!!!!!!!!!"
         return 1
     else:
         return 0
Exemple #20
0
	def _waitForStarted(self):
		for each in range(100):
			svcType, svcState, svcControls, err, svcErr, svcCP, svcWH = \
					 win32serviceutil.QueryServiceStatus(ServiceName)
			if svcState & win32service.SERVICE_RUNNING:
				break
			else:
				time.sleep(0.10)
Exemple #21
0
 def IsDriverInstalled(self):
     try:
         win32serviceutil.QueryServiceStatus(self.name)
     except BaseException as e:
         if e.args[0] == 1060:  #not installed
             return False
         else:
             raise  #other error
     return True
Exemple #22
0
def service_state(name):
    try:
        import win32service, win32serviceutil
        if win32serviceutil.QueryServiceStatus(name)[1] == 4:
            return "%s is running" % (name)
        else:
            return "%s is stopped" % (name)
    except:
        return "failed"
def service_control(service, action):
    try:
        if action == 'stop':
            win32serviceutil.StopService(service)
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
        elif action == 'start':
            win32serviceutil.StartService(service)
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
        elif action == 'restart':
            win32serviceutil.RestartService(service)
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
        elif action == 'status':
            return EnumStatusService.getStatus(
                win32serviceutil.QueryServiceStatus(service)[1])
    except:
        return 'failed'
Exemple #24
0
def nt_service_status(service):
    # type: (str) -> bool
    """
    #  win32serviceutil.QueryServiceStatus(service) returns a list. If second entry = 4, service is running
    # TODO: handle other service states than 4
    """
    service_status = win32serviceutil.QueryServiceStatus(service)
    if service_status[1] == 4:
        return True
    return False
Exemple #25
0
def check_is_service_installed(svcName):
    import win32serviceutil

    is_service_installed = False
    try:
        win32serviceutil.QueryServiceStatus(svcName)
        is_service_installed = True
    except:
        is_service_installed = False
    return is_service_installed
Exemple #26
0
def wait_for_service(name, timeout=200):
    start = time.time()
    while True:
        status = win32serviceutil.QueryServiceStatus(name)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        if time.time() - start > timeout:
            raise TimeoutError("Timeout waiting for service")  # pylint: disable=undefined-variable

        time.sleep(.3)
def is_local_mysql_service_running():
    MYSQL_WIN32_SERVICE_NAME = 'MySQL56'
    import win32service
    import win32serviceutil
    if win32serviceutil.QueryServiceStatus(MYSQL_WIN32_SERVICE_NAME)[1] == (
            win32service.SERVICE_RUNNING
            or win32service.SERVICE_START_PENDING):
        return True
    else:
        return False
Exemple #28
0
    def isServiceRunning(self, serviceName):
        """
        Check if service is running

        @return: True if service is running
        @rtype: boolean
        """
        isRunning = win32serviceutil.QueryServiceStatus(serviceName)[1] == win32service.SERVICE_RUNNING
        self.logger.info('Service %s isRunning = %s' % (serviceName, isRunning))

        return isRunning
Exemple #29
0
    def main(self):
        # poc = psutil.process_iter()
        # 服务状态
        # UNKNOWN = 0
        # STOPPED = 1
        # START_PENDING = 2
        # STOP_PENDING = 3
        # RUNNING = 4
        # 检查服务的状态
        result = win32serviceutil.QueryServiceStatus(ServiceName)[1]
        #检测服务当前状态
        # for process in poc:
        #
        #     ProList.append(str(process.name()))
        #     # print(ProList)
        # # 把所有任务管理器中的进程名添加到列表

        # if ProcessName in ProList:
        #  # 判断进程名是否在列表中,如果是True,则所监控的服务正在 运行状态,
        #     # 打印服务正常运行
        #     # print("服务正常运行中...")
        #     pass
        # 判断当前服务处于什么状态
        if result == 4 or result == 2:
            #打印服务正常运行
            print("服务正常运行中...")

        else:
            # 如果服务状态不是已启动或正在启动,即监控的服务挂了,则在log文件下记录日志
            # 日志文件名是以年月日为文件名

            # f = open('.\\log\\' + time.strftime("%Y%m%d", time.localtime()) + '-exception.txt', 'w')
            with open('buglog.txt', 'a') as f:
                # print('Server is not running,Begining to Restart Server...')
                # 打印服务状态
                f.write('\n' + '服务没有启动,开始重启服务...' + '\n')
                f.write(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()) + '\n')
            # 写入时间和服务状态到日志文件中
            try:
                print("试图重启")
                # os.startfile(ProgramPath) #启动服务
                
                win32serviceutil.StartService(ServiceName)#启动服务
                print("重启成功")
                print("服务正常工作中...")
                # 调用服务重启
                with open('buglog.txt', 'a') as f:
                    f.write('重启服务成功...' + '\n')
                    f.write(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()))
            except :
                with open('buglog.txt', 'a') as f:
                    f.write('服务重启失败!.' + '\n')
                    f.write(time.strftime('%Y-%m-%d %H:%M:%S --%A--%c', time.localtime()))
                print("重启失败")
Exemple #30
0
 def status(self):
     """Return running status of Freezer Service
     by querying win32serviceutil.QueryServiceStatus()
     possible running status:
         1 == stop
         4 == running
     """
     if win32serviceutil.QueryServiceStatus(self.service_name)[1] == 4:
         print("{0} is running normally".format(self.service_name))
     else:
         print("{0} is *NOT* running".format(self.service_name))