Python win32service.CloseServiceHandle() Examples

The following are 20 code examples of win32service.CloseServiceHandle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32service , or try the search function .
Example #1
Source File: ControlService.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def OnStartCmd(self, id, code):
		service = self.GetSelService()
		if not service:
			return
		s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
		win32service.StartService(s, None)
		win32service.CloseServiceHandle(s)
		self.ReloadData() 
Example #2
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def Stop(self):
        """
        This will be called to stop the thread.
        """
        if self.file:
            writeOvlap = win32file.OVERLAPPED()
            writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
            msg = "q".encode("ascii")
            win32file.WriteFile(self.file, msg, writeOvlap)
            win32file.CloseHandle(self.file)
            self.file = None
        self.keepRunning = False

        if self.service:
            win32service.CloseServiceHandle(self.service)

        #eg.PrintNotice("MCE_Vista: stopping thread") 
Example #3
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,plugin):
        """
        This initializes the class, and saves the plugin reference for use in the new thread.
        """
        self.plugin = plugin
        self.file = None
        self.connecting = False
        self.receiving = False
        self.sentMessageOnce = True
        self.receivingTimeout = None

        try:
            scmanager = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT)
            self.service = win32service.OpenService(scmanager, MCE_SERVICE_NAME, win32service.SERVICE_START | win32service.SERVICE_QUERY_STATUS)
            win32service.CloseServiceHandle(scmanager)
        except:
            self.service = None 
Example #4
Source File: windows.py    From cloudbase-init with Apache License 2.0 6 votes vote down vote up
def create_service(self, service_name, display_name, path, start_mode,
                       username=None, password=None):
        LOG.debug('Creating service %s', service_name)
        start_type = self._get_win32_start_type(start_mode)

        with WindowsUtils._get_service_control_manager(
                scm_access=win32service.SC_MANAGER_CREATE_SERVICE) as hscm:
            hs = win32service.CreateService(
                hscm, service_name, display_name,
                win32service.SERVICE_ALL_ACCESS,
                win32service.SERVICE_WIN32_OWN_PROCESS,
                start_type,
                win32service.SERVICE_ERROR_NORMAL,
                path, None, False, None,
                username, password)
            win32service.CloseServiceHandle(hs) 
Example #5
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def StopServiceWithDeps(serviceName, machine = None, waitSecs = 30):
    # Stop a service recursively looking for dependant services
    hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:
        deps = __FindSvcDeps(serviceName)
        for dep in deps:
            hs = win32service.OpenService(hscm, dep, win32service.SERVICE_ALL_ACCESS)
            try:
                __StopServiceWithTimeout(hs, waitSecs)
            finally:
                win32service.CloseServiceHandle(hs)
        # Now my service!
        hs = win32service.OpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:
            __StopServiceWithTimeout(hs, waitSecs)
        finally:
            win32service.CloseServiceHandle(hs)

    finally:
        win32service.CloseServiceHandle(hscm) 
Example #6
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def RemoveService(serviceName):
    try:
        import perfmon
        perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
    except (ImportError, win32api.error):
        pass

    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:
        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        win32service.DeleteService(hs)
        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)

    import win32evtlogutil
    try:
        win32evtlogutil.RemoveSourceFromRegistry(serviceName)
    except win32api.error:
        pass 
Example #7
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def ControlService(serviceName, code, machine = None):
    hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:

        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:
            status = win32service.ControlService(hs, code)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    return status 
Example #8
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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 
Example #9
Source File: ControlService.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __del__(self):
		win32service.CloseServiceHandle(self.service) 
Example #10
Source File: ControlService.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def __del__(self):
		win32service.CloseServiceHandle(self.scm) 
Example #11
Source File: ControlService.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def ReloadData(self):
		service = self.GetSelService()
		self.listCtrl.SetRedraw(0)
		self.listCtrl.ResetContent()
		svcs = win32service.EnumServicesStatus(self.scm)
		i = 0
		self.data = []
		for svc in svcs:
			try:
				status = ('Unknown', 'Stopped', 'Starting', 'Stopping', 'Running',
					'Continuing', 'Pausing', 'Paused')[svc[2][1]]
			except:
				status = 'Unknown'
			s = win32service.OpenService(self.scm, svc[0], win32service.SERVICE_ALL_ACCESS)
			cfg = win32service.QueryServiceConfig(s)
			try:
				startup = ('Boot', 'System', 'Automatic', 'Manual', 'Disabled')[cfg[1]]
			except:
				startup = 'Unknown'
			win32service.CloseServiceHandle(s)

			# svc[2][2] control buttons
			pos = self.listCtrl.AddString(str(svc[1]) + '\t' + status + '\t' + startup)
			self.listCtrl.SetItemData(pos, i)
			self.data.append(tuple(svc[2]) + (svc[1], svc[0], ))
			i = i + 1

			if service and service[1] == svc[0]:
				self.listCtrl.SetCurSel(pos)
		self.OnListEvent(self.IDC_LIST, win32con.LBN_SELCHANGE)
		self.listCtrl.SetRedraw(1) 
Example #12
Source File: ControlService.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def OnPauseCmd(self, id, code):
		service = self.GetSelService()
		if not service:
			return
		s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
		win32service.ControlService(s, win32service.SERVICE_CONTROL_PAUSE)
		win32service.CloseServiceHandle(s)
		self.ReloadData() 
Example #13
Source File: ControlService.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def OnContinueCmd(self, id, code):
		service = self.GetSelService()
		if not service:
			return
		s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
		win32service.ControlService(s, win32service.SERVICE_CONTROL_CONTINUE)
		win32service.CloseServiceHandle(s)
		self.ReloadData() 
Example #14
Source File: windows.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def _get_service_control_manager(
            scm_access=win32service.SC_MANAGER_CONNECT):
        hscm = win32service.OpenSCManager(None, None, scm_access)
        try:
            yield hscm
        finally:
            win32service.CloseServiceHandle(hscm) 
Example #15
Source File: windows.py    From cloudbase-init with Apache License 2.0 5 votes vote down vote up
def _get_service_handle(service_name,
                            service_access=win32service.SERVICE_QUERY_CONFIG,
                            scm_access=win32service.SC_MANAGER_CONNECT):
        with WindowsUtils._get_service_control_manager(scm_access) as hscm:
            hs = win32service.OpenService(hscm, service_name, service_access)
            try:
                yield hs
            finally:
                win32service.CloseServiceHandle(hs) 
Example #16
Source File: utils.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def stop_and_delete_driver_service(h_svc):
    """Stops the winpmem service and delete it"""
    try:
        win32service.ControlService(h_svc, win32service.SERVICE_CONTROL_STOP)
    except win32service.error:
        pass
    win32service.DeleteService(h_svc)
    win32service.CloseServiceHandle(h_svc) 
Example #17
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def InstallService(pythonClassString, serviceName, displayName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
    # Handle the default arguments.
    if startType is None:
        startType = win32service.SERVICE_DEMAND_START
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    if errorControl is None:
        errorControl = win32service.SERVICE_ERROR_NORMAL

    exeName = '"%s"' % LocatePythonServiceExe(exeName) # None here means use default PythonService.exe
    commandLine = _GetCommandLine(exeName, exeArgs)
    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:
        hs = win32service.CreateService(hscm,
                                serviceName,
                                displayName,
                                win32service.SERVICE_ALL_ACCESS,         # desired access
                    serviceType,        # service type
                    startType,
                    errorControl,       # error control type
                    commandLine,
                    None,
                    0,
                    serviceDeps,
                    userName,
                    password)
        if description is not None:
            try:
                win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
            except NotImplementedError:
                pass    ## ChangeServiceConfig2 and description do not exist on NT
        win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll) 
Example #18
Source File: live_windows.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def remove_service(self, also_close_as=True):
        self.session.logging.debug("Removing service %s",
                                   self.plugin_args.service_name)

        # Make sure the handle is closed.
        if also_close_as:
            self.session.physical_address_space.close()

        # Stop the service if it's running.
        if not self.hSvc:
            try:
                self.hSvc = win32service.OpenService(
                    self.hScm, self.plugin_args.service_name,
                    win32service.SERVICE_ALL_ACCESS)
            except win32service.error:
                self.session.logging.debug("%s service does not exist.",
                                           self.plugin_args.service_name)

        if self.hSvc:
            self.session.logging.debug("Stopping service: %s",
                                       self.plugin_args.service_name)
            try:
                win32service.ControlService(
                    self.hSvc, win32service.SERVICE_CONTROL_STOP)
            except win32service.error as e:
                self.session.logging.debug("Error stopping service: %s", e)

            self.session.logging.debug("Deleting service: %s",
                                       self.plugin_args.service_name)
            try:
                win32service.DeleteService(self.hSvc)
            except win32service.error as e:
                self.session.logging.debug("Error deleting service: %s", e)

            win32service.CloseServiceHandle(self.hSvc) 
Example #19
Source File: win32serviceutil.py    From ironpython2 with Apache License 2.0 4 votes vote down vote up
def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, displayName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
    # Before doing anything, remove any perfmon counters.
    try:
        import perfmon
        perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
    except (ImportError, win32api.error):
        pass

    # The EXE location may have changed
    exeName = '"%s"' % LocatePythonServiceExe(exeName)

    # Handle the default arguments.
    if startType is None: startType = win32service.SERVICE_NO_CHANGE
    if errorControl is None: errorControl = win32service.SERVICE_NO_CHANGE

    hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
    serviceType = win32service.SERVICE_WIN32_OWN_PROCESS
    if bRunInteractive:
        serviceType = serviceType | win32service.SERVICE_INTERACTIVE_PROCESS
    commandLine = _GetCommandLine(exeName, exeArgs)
    try:
        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:

            win32service.ChangeServiceConfig(hs,
                serviceType,  # service type
                startType,
                errorControl,       # error control type
                commandLine,
                None,
                0,
                serviceDeps,
                userName,
                password,
                displayName)
            if description is not None:
                try:
                    win32service.ChangeServiceConfig2(hs,win32service.SERVICE_CONFIG_DESCRIPTION,description)
                except NotImplementedError:
                    pass    ## ChangeServiceConfig2 and description do not exist on NT

        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
    InstallPythonClassString(pythonClassString, serviceName)
    # If I have performance monitor info to install, do that.
    if perfMonIni is not None:
        InstallPerfmonForService(serviceName, perfMonIni, perfMonDll) 
Example #20
Source File: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 4 votes vote down vote up
def is_agent_running(self, fail_if_running=False, fail_if_not_running=False):
        """Returns true if the agent service is running, as determined by this platform implementation.

        This will optionally raise an Exception with an appropriate error message if the agent is running or not
        runnning.

        @param fail_if_running:  True if the method should raise an Exception with a platform-specific error message
            explaining how it determined the agent is running.
        @param fail_if_not_running: True if the method should raise an Exception with a platform-specific error message
            explaining how it determined the agent is not running.

        @type fail_if_running: bool
        @type fail_if_not_running: bool

        @return: True if the agent process is already running.
        @rtype: bool

        @raise AgentAlreadyRunning
        @raise AgentNotRunning
        """

        hscm = None
        hs = None

        try:
            hscm = win32service.OpenSCManager(
                None, None, win32service.SC_MANAGER_CONNECT
            )
            hs = win32serviceutil.SmartOpenService(
                hscm, _SCALYR_AGENT_SERVICE_, win32service.SERVICE_QUERY_STATUS
            )
            status = win32service.QueryServiceStatusEx(hs)

            state = status["CurrentState"]

            is_running = state in (
                win32service.SERVICE_RUNNING,
                win32service.SERVICE_START_PENDING,
            )
            if fail_if_running and is_running:
                pid = status["ProcessId"]
                raise AgentAlreadyRunning(
                    "The operating system reports the Scalyr Agent Service is running with "
                    "pid=%d" % pid
                )
            if fail_if_not_running and not is_running:
                raise AgentNotRunning(
                    "The operating system reports the Scalyr Agent Service is not running"
                )

            return state in (
                win32service.SERVICE_RUNNING,
                win32service.SERVICE_START_PENDING,
            )

        finally:
            if hs is not None:
                win32service.CloseServiceHandle(hs)
            if hscm is not None:
                win32service.CloseServiceHandle(hscm)