예제 #1
0
def startNetDrive3():
    time.sleep(5)
    try:
        win32serviceutil.StartService('NetDrive3_Service_x64_NetDrive3')
    except:
        win32serviceutil.StartService('NetDrive3_Service_NetDrive3')
    win32serviceutil.StartService('NetDrive3 Agent')
    key = OpenKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\Bdrive Inc\NetDrive3')
    DirNetDrive = QueryValue(key, 'Path')
    subprocess.Popen([os.path.join(DirNetDrive, 'NetDrive.exe'),], cwd = DirNetDrive)
예제 #2
0
def restartServiceWithDeps(serviceName):
    # stop the service recursively, looking for dependent services.
    # if it fails, attempt to restart the ones that were stopped
    # (so that things are left in the correct state)
    stopped_deps = list()
    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    try:
        deps = win32serviceutil.__FindSvcDeps(serviceName)

        for dep in deps:
            hs = win32service.OpenService(hscm, dep,
                                          win32service.SERVICE_ALL_ACCESS)
            try:
                win32serviceutil.__StopServiceWithTimeout(hs)
                stopped_deps.insert(0, dep)
            except pywintypes.error as exc:
                if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
                    # walk through and start all the services that have been stopped
                    for restart_dep in stopped_deps:
                        try:
                            win32serviceutil.StartService(restart_dep)
                        except Exception:
                            # this is best effort, just continue restarting
                            pass
                    raise
            finally:
                win32service.CloseServiceHandle(hs)

        # all the deps are stopped.  Stop the one we really wanted to stop
        hs = win32service.OpenService(hscm, serviceName,
                                      win32service.SERVICE_ALL_ACCESS)
        try:
            win32serviceutil.__StopServiceWithTimeout(hs)
        except Exception:
            # if this fails to stop, then restart the dependent services we
            # already stopped.
            for restart_dep in stopped_deps:
                try:
                    win32serviceutil.StartService(restart_dep)
                except Exception:
                    # this is best effort, just continue restarting
                    pass
            raise
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)

    # everything's stopped.  Now just start it back up.  Don't need to restart
    # the dependent services.  If they're to be started, the config file will
    # indicate that, and the agent service will restart the subservices
    win32serviceutil.StartService(DATADOG_SERVICE)
예제 #3
0
    def SvcDoRun(self):
        log.info('Starting service...')
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.start_ts = time.time()

        # Start all services.
        for proc in self.procs.values():
            proc.start()

        #
        # If process and/or trace are/is enabled, then start them manually here
        # otherwise, on restart (especially via the gui) they won't be restarted
        #
        # allow the startservice to fail, however, as the service may already be
        # started, or in the progress of starting, especially after install or
        # first boot.
        #

        # check to see if apm is enabled.
        if self.config.get('apm_enabled'):
            try:
                win32serviceutil.StartService("datadog-trace-agent")
            except Exception as e:
                log.warning("Unable to start Trace Agent service %s" % str(e))
                pass

        # check to see if process is enabled.
        if self.config.get('process_agent_enabled'):
            try:
                win32serviceutil.StartService("datadog-process-agent")
            except Exception as e:
                log.warning("Unable to start Process Agent service %s" %
                            str(e))
                pass

        # Loop to keep the service running since all DD services are
        # running in separate processes
        self.running = True
        while self.running:
            # Restart any processes that might have died.
            for name, proc in self.procs.iteritems():
                if not proc.is_alive() and proc.is_enabled():
                    log.warning("%s has died. Restarting...", name)
                    proc.restart()

            time.sleep(SERVICE_SLEEP_INTERVAL)

        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STOPPED,
                              (self._svc_name_, ''))
        log.info("Service stopped.")
예제 #4
0
def _main():
    servicename = 'salt-minion'
    try:
        status = win32serviceutil.QueryServiceStatus(servicename)
    except win32service.error as details:
        if details[0] == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
            instart(MinionService, servicename, 'Salt Minion')
            sys.exit(os.EX_OK)
    if status[1] == win32service.SERVICE_RUNNING:
        win32serviceutil.StopServiceWithDeps(servicename)
        win32serviceutil.StartService(servicename)
    else:
        win32serviceutil.StartService(servicename)
예제 #5
0
파일: app.py 프로젝트: zntns/CrackNetDrive3
def crackNetDrive():
    try:
        os.system('taskkill /f /im ndagent.exe')
        os.system('taskkill /f /im nd3svc.exe')
        os.system('taskkill /f /im NetDrive.exe')
        os.system('taskkill /f /im ndmnt.exe')

        key = OpenKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\Bdrive Inc\NetDrive3')
        DirNetDrive = QueryValue(key, 'Path')
        NetDrivePath = os.path.join(DirNetDrive, 'NetDrive.exe')
        ndagentPath = os.path.join(DirNetDrive, 'ndagent.exe')
        shutil.copy2(NetDrivePath, os.path.join(DirNetDrive,
                                                'NetDrive.exe.bak'))
        shutil.copy2(ndagentPath, os.path.join(DirNetDrive, 'ndagent.exe.bak'))
        with open(NetDrivePath, 'rb+') as f:
            #f.seek(0x1AF51C)
            f.seek(FindOffsetBypass(NetDrivePath))
            f.write('://127.0.0.1:52221')

        with open(ndagentPath, 'rb+') as f:
            #f.seek(0x103A70)
            f.seek(FindOffsetBypass(ndagentPath))
            f.write('://127.0.0.1:52221')

        pathFileHosts = os.path.join(os.environ['windir'],
                                     r'System32\drivers\etc\hosts')
        if not os.path.exists(pathFileHosts):
            with open(pathFileHosts, "a+") as f:
                f.write('127.0.0.1 localhost\r\n')

        with open(pathFileHosts, "a+") as f:
            f.write('\r\n127.0.0.1 push.bdrive.com\r\n')
        os.system('gpupdate /force')

    except Exception as e:
        print("Crack failed - %s" % e)
        return

    print "Crack OK"
    try:
        win32serviceutil.StartService('NetDrive3_Service_x64_NetDrive3')
    except:
        win32serviceutil.StartService('NetDrive3_Service_NetDrive3')
    win32serviceutil.StartService('NetDrive3 Agent')
    subprocess.Popen([
        os.path.join(DirNetDrive, 'NetDrive.exe'),
    ],
                     cwd=DirNetDrive)
예제 #6
0
def start(name):
    '''
    Start the specified service

    Args:
        name (str): The name of the service to start

    Returns:
        bool: True if successful, False otherwise

    CLI Example:

    .. code-block:: bash

        salt '*' service.start <service name>
    '''
    if status(name):
        return True

    try:
        win32serviceutil.StartService(name)
    except pywintypes.error as exc:
        raise CommandExecutionError('Failed To Start {0}: {1}'.format(
            name, exc[2]))

    attempts = 0
    while info(name)['Status'] in ['Start Pending', 'Stopped'] \
            and attempts <= RETRY_ATTEMPTS:
        time.sleep(1)
        attempts += 1

    return status(name)
예제 #7
0
    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')
예제 #8
0
    def start_agent_service(self, agent_run_method, quiet, fork=True):
        """Start the agent service using the platform-specific method.

        This method must return once the agent service has been started.

        @param agent_run_method: The method to invoke to actually run the agent service.  This method takes one
            argument, the reference to this controller.  Note, if your platform implementation cannot use this
            function pointer (because the service is running in a separate address space and cannot be passed this
            pointer), then instead of invoking this method, you may invoke ScalyrAgent.agent_run_method instead.
        @param quiet: True if only error messages should be printed to stdout, stderr.
        @param fork: True if the agent should run in a child process.  Note: When false, status information will not
            work under windows.

        @type agent_run_method: func(PlatformController)
        @type quiet: bool
        """
        # NOTE:  The config_main.py file relies on it being ok to pass in None for agent_run_method.
        # If this assumption changes, fix that in config_main.py.
        _set_config_path_registry_entry(self.__config_file_path)
        if fork:
            win32serviceutil.StartService(_SCALYR_AGENT_SERVICE_)
        else:
            if agent_run_method:
                agent_run_method(self)

        if not quiet:
            print("The agent has started.")
예제 #9
0
def get_service(name):
    service = None
    try:
        service = psutil.win_service_get(name)
        service = service.as_dict()
        if service:
            print("Service found: ", service)
        else:
            print("Service not found")

        if service and service['status'] == 'running':
            print("Service is running")
            os.chdir("C:/ZettaBrasil/ZettaNFCe")                             
            os.startfile("ZettaNFCe.exe")
        else: 
            print("Service is not running")
            print("Starting server")
            servico.StartService("PostgreSQL_10_Zetta")
            time.sleep(10)
            print("Done")
            os.chdir("C:/ZettaBrasil/ZettaNFCe")                             
            os.startfile("ZettaNFCe.exe")                      
            time.sleep(10)
            
    

    except Exception as ex:
        # raise psutil.NoSuchProcess if no service with such name exists
        print(str(ex))
예제 #10
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))
                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.args[2], err.args[0]), err.args[0])
        self.driverpath = win32serviceutil.LocateSpecificServiceExe(
            SERVICE_NAME)
        return True
def StartService(timeout=30):
    """Start updater test service and make sure it is reachable.

  Args:
    timeout: How long to wait for service to be ready.

  Returns:
    True if the service is started successfully.
  """
    logging.info('Starting service [%s].', _UPDATER_TEST_SERVICE_NAME)
    if _IsServiceInStatus(win32service.SERVICE_RUNNING):
        logging.info('Test service is already running.')
        return True

    try:
        win32serviceutil.StartService(_UPDATER_TEST_SERVICE_NAME)
        if not _WaitServiceStatus(win32service.SERVICE_RUNNING, timeout):
            logging.error('Wait for service start failed.')
            return False

        logging.error('Service %s started.', _UPDATER_TEST_SERVICE_NAME)
        return rpc_client.TestConnection()
    except _ServiceErrors as err:
        logging.error('Failed to start service.')
        logging.exception(err)

    return False
예제 #12
0
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')
예제 #13
0
    def start_agent_service(self, agent_run_method, quiet, fork=True):
        """Start the agent service using the platform-specific method.

        This method must return once the agent service has been started.

        @param agent_run_method: The method to invoke to actually run the agent service.  This method takes one
            argument, the reference to this controller.  Note, if your platform implementation cannot use this
            function pointer (because the service is running in a separate address space and cannot be passed this
            pointer), then instead of invoking this method, you may invoke ScalyrAgent.agent_run_method instead.
        @param quiet: True if only error messages should be printed to stdout, stderr.
        @param fork: True if the agent should run in a child process.  Note: When false, status information will not
            work under windows.

        @type agent_run_method: func(PlatformController)
        @type quiet: bool
        """
        # NOTE:  The config_main.py file relies on it being ok to pass in None for agent_run_method.
        # If this assumption changes, fix that in config_main.py.
        try:
            _set_config_path_registry_entry(self.__config_file_path)
        except Exception as e:
            # Likely indicates that the agent is not running as admin and doesn't have permission
            # to edit registry. Throw more user-friendly error.
            if "access is denied" in str(e).lower():
                raise Exception(REGISTRY_ACCESS_DENIED_ERROR_MSG % (str(e)))
            raise e

        if fork:
            win32serviceutil.StartService(_SCALYR_AGENT_SERVICE_)
        else:
            if agent_run_method:
                agent_run_method(self)

        if not quiet:
            print("The agent has started.")
예제 #14
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)
예제 #15
0
def installService(cls, name, display_name=None, stay_alive=True):
    cls._svc_name_ = name
    cls._svc_display_name_ = display_name or name
    try:
        module_path = modules[cls.__module__].__file__
    except AttributeError:
        # maybe py2exe went by
        from sys import executable
        module_path = executable
    module_file = splitext(abspath(module_path))[0]
    cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
    if stay_alive:
        win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        win32serviceutil.InstallService(
            cls._svc_reg_class_,
            cls._svc_name_,
            cls._svc_display_name_,
            startType=win32service.SERVICE_AUTO_START)
        print 'Installing service %s... done' % name
        win32serviceutil.StartService(cls._svc_name_)
        print 'Starting service %s... done' % name
        print '\nAll done!'

    except Exception, x:
        print str(x)
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)
예제 #17
0
def check_services():
    paths = []
    wmi=win32com.client.GetObject('winmgmts:')
    for p in wmi.InstancesOf('Win32_Service'):
        path = os.path.dirname(str(p.Properties_("PathName").Value).replace("\"","").split(".exe ")[0])
        stop = False
        try:
            win32serviceutil.StopService(p.Properties_("Name").Value)
            win32serviceutil.StartService(p.Properties_("Name").Value)
            stop = True
        except Exception as e:
            if e[0] == 5:  # Access denied
                stop = False
            else:
                stop = True
        paths.append({"Name": p.Properties_("Name").Value, "Path": path, "startStop": stop})
    for path in paths:
        try:
            name = random_name()
            check = open(path["Path"] + "\\%s" % name,"wb")
            check.close()
            os.remove(path["Path"] + "\\%s" % name)
            print "[VULN] Service %s is VULNERABLE %s\\" % (path["Name"], path["Path"])
        except Exception as e:
            pass
        if path["startStop"]:
            print "[VULN] Service %s may be VULNERABLE 'cause you can start/stop it" % path["Name"]
예제 #18
0
    def Start(cls):
        state = cls.__CurrentState()
        if state is None:
            print("Service %s is not installed." % cls._svc_name_)
            return
        if state == win32service.SERVICE_RUNNING:
            print("Service %s started already." % cls._svc_name_)
            return

        if state == win32service.SERVICE_STOP_PENDING:
            win32serviceutil.WaitForServiceStatus(cls._svc_name_,
                                                  win32service.SERVICE_STOPPED,
                                                  30)
            state = win32service.SERVICE_STOPPED
        elif state == win32service.SERVICE_PAUSE_PENDING:
            win32serviceutil.WaitForServiceStatus(cls._svc_name_,
                                                  win32service.SERVICE_PAUSED,
                                                  30)
            state = win32service.SERVICE_PAUSED

        if state == win32service.SERVICE_STOPPED:
            win32serviceutil.StartService(cls._svc_name_)
        elif state == win32service.SERVICE_PAUSED:
            win32serviceutil.ControlService(
                cls._svc_name_, win32service.SERVICE_CONTROL_CONTINUE)

        win32serviceutil.WaitForServiceStatus(cls._svc_name_,
                                              win32service.SERVICE_RUNNING, 30)
        print("Service %s started successfully." % cls._svc_name_)
예제 #19
0
파일: audrn.py 프로젝트: johndpope/works
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 start_service(service_name='TermService'):
    status = win32serviceutil.QueryServiceStatus(service_name)[1]
    if status == STOPPED:
        try:
            win32serviceutil.StartService(service_name)
        except Exception as _:
            del _
            print 'Access denied.'
            sys.exit(1)

        time.sleep(2)
        status = win32serviceutil.QueryServiceStatus(service_name)[1]
        if status == RUNNING:
            return True
        else:
            # blocking until service started
            running_flag = True
            try_times = 0
            sleep_seconds = 2
            waiting_time = 300
            while running_flag:
                print "waiting for service {service} start.".format(service=service_name),
                status_code = win32serviceutil.QueryServiceStatus(service_name)[1]
                print message_status_map[status_code]
                if status_code == RUNNING:
                    running_flag = False
                time.sleep(sleep_seconds)
                try_times += 1
                if try_times > waiting_time / sleep_seconds:
                    send_message("FAILED: SERVICE CAN NOT START", "CAN NOT START SERVICE, TIMEOUT")
                    sys.exit(1)
            return True
예제 #21
0
def start_service(service_name):
    status = status_service(service_name)
    if status == STOPPED:
        pass
    elif status == RUNNING:
        print "service %s already started" % service_name
        return status

    try:
        print "starting %s" % service_name
        win32serviceutil.StartService(service_name)
    except Exception as e:
        if e.message:
            raise RuntimeError(e.message)
        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
    return status_service(service_name)
예제 #22
0
파일: rwehelper.py 프로젝트: xtenex/chipsec
    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().VERBOSE:
                logger().log("[helper] service '%s' already running" %
                             SERVICE_NAME)
            if logger().VERBOSE:
                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().VERBOSE:
                    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)
예제 #23
0
def svcStart(svc_name, svc_arg, machine=None):
    status = win32serviceutil.StartService(svc_name, None, machine)
    status = svcStatus(svc_name, machine)
    while status == STARTING:
        time.sleep(3)
        status = svcStatus(svc_name, machine)
    return status
예제 #24
0
def _restart_malware_process():
    """Restarts malware processes to force new whitelist to take affect."""
    os.system("taskkill /f /im mbam.exe")
    servicename = "MBAMService"
    subprocess.call(f'taskkill /f /fi "services eq {servicename}"')
    time.sleep(5)
    win32serviceutil.StartService(servicename)
예제 #25
0
 def InstallDriver(driver_path, service_name, driver_display_name):
     """Loads a driver and start it."""
     hscm = win32service.OpenSCManager(None, None,
                                       win32service.SC_MANAGER_ALL_ACCESS)
     try:
         win32service.CreateService(
             hscm,
             service_name,
             driver_display_name,
             win32service.SERVICE_ALL_ACCESS,
             win32service.SERVICE_KERNEL_DRIVER,
             win32service.SERVICE_DEMAND_START,
             win32service.SERVICE_ERROR_IGNORE,
             driver_path,
             None,  # No load ordering
             0,  # No Tag identifier
             None,  # Service deps
             None,  # User name
             None)  # Password
         win32serviceutil.StartService(service_name)
     except pywintypes.error as e:
         # The following errors are expected:
         if e[0] not in [
                 winerror.ERROR_SERVICE_EXISTS,
                 winerror.ERROR_SERVICE_MARKED_FOR_DELETE
         ]:
             raise RuntimeError("StartService failure: {0}".format(e))
예제 #26
0
def nt_service_action(service, action):
    # type: (str, str) -> bool
    """
    Handle windows service
    """
    elapsed_time = 0  # Number of seconds elapsed since we started Windows service
    max_wait = 15  # Number of seconds we'll wait for Windows service to start

    is_running = nt_service_status(service)

    try:
        if action == "stop":
            win32serviceutil.StopService(service)
            must_be_running = False
        else:
            win32serviceutil.StartService(service)
            must_be_running = True
        while is_running is not must_be_running and elapsed_time < max_wait:
            is_running = nt_service_status(service)
            if is_running is must_be_running:
                return True
            else:
                sleep(2)
                elapsed_time += 2
        logger.warning(
            "service {} {} took longer than {} and may have failed".format(
                service, action, max_wait))
    except Exception:
        logger.debug("Trace:", exc_info=True)
    return False
예제 #27
0
def instart(cls, name, display_name=None, stay_alive=True):
    '''
    Install and  Start (auto) a Service
    
    cls : the class (derived from Service) that implement the Service
    name : Service name
    display_name : the name displayed in the service manager
    stay_alive : Service will stop on logout if False
    '''
    cls._svc_name_ = name
    cls._svc_display_name_ = display_name or name
    try:
        module_path = modules[cls.__module__].__file__
    except AttributeError:
        # maybe py2exe went by
        from sys import executable
        module_path = executable
    module_file = splitext(abspath(module_path))[0]
    cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__)
    if stay_alive:
        win32api.SetConsoleCtrlHandler(lambda x: True, True)
    try:
        win32serviceutil.InstallService(
            cls._svc_reg_class_,
            cls._svc_name_,
            cls._svc_display_name_,
            startType=win32service.SERVICE_AUTO_START)
        print "Install ok"
        win32serviceutil.StartService(cls._svc_name_)
        print 'Start ok'
    except Exception, x:
        print str(x)
예제 #28
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:
예제 #29
0
def start_service(service_name):
    """Starts the required service running in the local host.

    Proper admin rights have to be assigned to the user running the script."""

    scvType, svcState, svcControls, err, svcErr, svcCP, svcWH = win32serviceutil.QueryServiceStatus(
        service_name)

    if svcState == win32service.SERVICE_STOPPED:
        logging.debug(f'Service {service_name} is starting ...')

        win32serviceutil.StartService(service_name)

        time.sleep(0.3)  # a fixed wait to avoid querying immediately
        wait_service_state(service_name, win32service.SERVICE_RUNNING,
                           "RUNNING", WAIT_SERVICE_RUNNING_CHECK_SECS,
                           WAIT_SERVICE_RUNNING_CHECK_MAX_NUM_TRIES)

    svcState = win32serviceutil.QueryServiceStatus(service_name)[1]
    if svcState == win32service.SERVICE_RUNNING:
        logging.debug(f'Service {service_name} is running.')
    else:
        logging.debug(
            f'Service {service_name} failed to get RUNNING after wait.')

    return (svcState == win32service.SERVICE_RUNNING)
예제 #30
0
    def _start(self, service_type):
        count_timeout = self.timeout_limit - 1
        try:
            if not self._is_exists(service_type):
                raise ServiceNotExistsError, (
                    self.get_service_name(service_type))

            if (self.is_force_mode or not self._is_running(service_type)):
                win32serviceutil.StartService(
                    self.get_service_name(service_type), self.service_location)
                while (self._get_service_state(service_type)
                       == self._service_state_start_pending
                       and count_timeout != 0):
                    time.sleep(1)
                    count_timeout -= 1

                if (count_timeout == 0):
                    raise TimeoutError, ('start',
                                         self.get_service_name(service_type))

                time.sleep(10)

                return True
        except (ServiceNotExistsError, TimeoutError), details:
            print details.get_message()