Exemplo n.º 1
0
def SmartOpenService(hscm, name, access):
    try:
        return win32service.OpenService(hscm, name, access)
    except win32api.error as details:
        if details.winerror not in [winerror.ERROR_SERVICE_DOES_NOT_EXIST,
                                    winerror.ERROR_INVALID_NAME]:
            raise
    name = win32service.GetServiceKeyName(hscm, name)
    return win32service.OpenService(hscm, name, access)
Exemplo n.º 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)
Exemplo n.º 3
0
def SmartOpenService(hscm, name, access):
    try:
        return win32service.OpenService(hscm, name, access)
    except win32api.error, details:
        if details[0] not in [
                winerror.ERROR_SERVICE_DOES_NOT_EXIST,
                winerror.ERROR_INVALID_NAME
        ]:
            raise
        name = _GetServiceShortName(name)
        if name is None:
            raise
        return win32service.OpenService(hscm, name, access)
Exemplo n.º 4
0
def stop_delete_service(service_name):
    '''
    Checks if the service is installed as running.
    If it is running, it will stop it.
    If it is stopped, then it will delete it.
    '''

    hscm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)

    try:
        win32service.OpenService(hscm, service_name,
                                 win32service.SERVICE_ALL_ACCESS)
        # Already installed
        status = win32serviceutil.QueryServiceStatus(service_name)
        if status[1] == 4:
            # Stop the service
            win32serviceutil.StopService(service_name)
        time.sleep(3)
        #delete the service
        win32serviceutil.RemoveService(service_name)
        time.sleep(3)
        return True

    except win32api.error, details:
        if details[0] != winerror.ERROR_SERVICE_DOES_NOT_EXIST:
            print service_name + "is not being installed properly but have other problem."
            return False
        else:
            # Service is not being installed and ready for fresh installtion
            return True
Exemplo n.º 5
0
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()))
Exemplo n.º 6
0
 def State(self, serviceName):
     """Return the state of the service."""
     handle = win32service.OpenService(self.__handle, serviceName,
                                       SC_MANAGER_ALL_ACCESS)
     state = self.__GetState(handle)
     win32service.CloseServiceHandle(handle)
     return state
Exemplo n.º 7
0
 def open(self):
     try:
         self.service = win32service.OpenService(
             self.manager, self.service_name,
             win32service.SERVICE_ALL_ACCESS)
     except Exception as e:
         log.debug("Unable to OpenService: {0}".format(e))
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)
Exemplo n.º 9
0
        def ctl(self, command, raise_exc=True):
            # sending start signal via service control will not fail if
            # a service can accept start command but cannot change its state into 'Running'
            # we should instead poll a service state until we succeed or timeout
            if command.lower() == 'start':
                RUNNING = 4
                TIMEOUT = 3

                GENERIC_READ = win32con.GENERIC_READ
                SC_MANAGER_ALL_ACCESS = win32service.SC_MANAGER_ALL_ACCESS

                __handle = win32service.OpenSCManager(None, None, GENERIC_READ)
                handle = win32service.OpenService(__handle, self.name,
                                                  SC_MANAGER_ALL_ACCESS)
                try:
                    win32service.StartService(handle, None)
                except Exception, e:
                    raise InitdError(
                        'Could not complete StartService command.\n, {0}'.
                        format(e))
                elapsed = 0
                while elapsed < TIMEOUT and win32service.QueryServiceStatusEx(
                        handle)['CurrentState'] != RUNNING:
                    time.sleep(0.1)
                    elapsed += 0.1

                if win32service.QueryServiceStatusEx(
                        handle)['CurrentState'] == RUNNING:
                    return

                raise exceptions.Timeout(
                    "{0} service failed to change its state"
                    " into 'Running' after {1}-second timeout.".format(
                        self.name, TIMEOUT))
Exemplo n.º 10
0
 def change_sercice_configuration(self, hnd, s):
     try:
         svcH = win32service.OpenService(hnd, s.name,
                                         win32service.SERVICE_CHANGE_CONFIG)
         return True
     except:
         return False
Exemplo n.º 11
0
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')
Exemplo n.º 12
0
	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)
Exemplo n.º 13
0
 def stopasync(self, args, config):
     """
     Returns true if the server was already stopped
     """
     self.check_node(args)
     if 0 != self.status(args, node_only=True):
         self.ctx.err("Server not running")
         return True
     elif self._isWindows():
         svc_name = "OMERO.%s" % args.node
         output = self._query_service(svc_name)
         if 0 <= output.find("DOESNOTEXIST"):
             self.ctx.die(
                 203, "%s does not exist. Use 'start' first." % svc_name)
         hscm = win32service.OpenSCManager(
             None, None, win32service.SC_MANAGER_ALL_ACCESS)
         try:
             hs = win32service.OpenService(
                 hscm, svc_name, win32service.SC_MANAGER_ALL_ACCESS)
             win32service.ControlService(hs,
                                         win32service.SERVICE_CONTROL_STOP)
             win32service.DeleteService(hs)
             self.ctx.out("%s service deleted." % svc_name)
         finally:
             win32service.CloseServiceHandle(hs)
             win32service.CloseServiceHandle(hscm)
     else:
         command = self._cmd("-e", "node shutdown %s" % self._node())
         try:
             self.ctx.call(command)
         except NonZeroReturnCode, nzrc:
             self.ctx.rv = nzrc.rv
             self.ctx.out("Was the server already stopped?")
Exemplo n.º 14
0
    def __start_driver(self):
        hService = None
        bResult = True

        hService = win32service.OpenService(self.hSCManager, "WINIO",
                                            win32service.SERVICE_ALL_ACCESS)
        win32service.StartService(hService, None)
Exemplo n.º 15
0
 def __init__(self, service, machinename=None, dbname=None):
     self.userv = service
     self.scmhandle = ws.OpenSCManager(machinename, dbname, ws.SC_MANAGER_ALL_ACCESS)
     self.sserv, self.lserv = self.getname()
     if (self.sserv or self.lserv) == None: sys.exit()
     self.handle = ws.OpenService(self.scmhandle, self.sserv, ws.SERVICE_ALL_ACCESS)
     self.sccss = "SYSTEM\\CurrentControlSet\\Services\\"
Exemplo n.º 16
0
 def get_sh_read_control(self):
     if not self.sh_read_control:
         try:
             self.sh_read_control = win32service.OpenService(self.get_scm(), self.get_name(), win32con.READ_CONTROL)
         except:
             pass
     return self.sh_read_control
Exemplo n.º 17
0
 def action_start(self):
     self._service_handle = self._service_handle if hasattr(self, "_service_handle") else \
       win32service.OpenService(_schSCManager, self.resource.service_name, win32service.SERVICE_ALL_ACCESS)
     if not self.status():
         self.enable()
         win32service.StartService(self._service_handle, None)
         self.wait_status(win32service.SERVICE_RUNNING)
Exemplo n.º 18
0
    def __init__(self, name):
        """
        name: 服务的名称
        """
        self.name = name

        # 启动或停止服务时等待操作成功等待时间
        self.wait_time = 0.5
        # 启动或停止服务时最大等待时间,超过时返回超时提示
        self.delay_time = 10
        self.scm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_ALL_ACCESS)

        if self.is_exists():
            try:
                self.handle = win32service.OpenService(
                    self.scm, self.name, win32service.SC_MANAGER_ALL_ACCESS)
            except Exception as e:
                self.log(e)
        else:
            print(f'服务 {self.name} 没有安装')
            try:
                win32serviceutil.HandleCommandLine(PythonService, 'install')

            except Exception as e:
                print(e)
Exemplo n.º 19
0
    def get_services(self, services_loaded):
        scm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_ENUMERATE_SERVICE)
        svcs = win32service.EnumServicesStatus(scm)

        for svc in svcs:
            try:
                sh_query_config = win32service.OpenService(
                    scm, svc[0], win32service.SERVICE_QUERY_CONFIG)
                service_info = win32service.QueryServiceConfig(sh_query_config)
                short_name = svc[0]
                full_path = service_info[3]
                sv = self.check_if_service_already_loaded(
                    short_name, full_path, services_loaded)

                if sv:
                    sv.permissions = self.get_service_permissions(sv)

                if not sv:
                    sk = Service()
                    sk.name = short_name
                    sk.display_name = svc[1]
                    sk.full_path = full_path
                    sk.paths = get_path_info(full_path)
                    sk.permissions = self.get_service_permissions(sv)
                    services_loaded.append(sk)
            except:
                pass

        return services_loaded
Exemplo n.º 20
0
def stopService():
    """Stop the running service and wait for its process to die.
	"""
    scm = win32service.OpenSCManager(None, None,
                                     win32service.SC_MANAGER_ALL_ACCESS)
    try:
        serv = win32service.OpenService(scm, NVDAService._svc_name_,
                                        win32service.SERVICE_ALL_ACCESS)
        try:
            pid = win32service.QueryServiceStatusEx(serv)["ProcessId"]

            # Stop the service.
            win32service.ControlService(serv,
                                        win32service.SERVICE_CONTROL_STOP)

            # Wait for the process to exit.
            proc = AutoHANDLE(
                windll.kernel32.OpenProcess(SYNCHRONIZE, False, pid))
            if not proc:
                return
            windll.kernel32.WaitForSingleObject(proc, INFINITE)

        finally:
            win32service.CloseServiceHandle(serv)
    finally:
        win32service.CloseServiceHandle(scm)
Exemplo n.º 21
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')
Exemplo n.º 22
0
    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)
Exemplo n.º 23
0
 def action_stop(self):
     self._service_handle = self._service_handle if hasattr(self, "_service_handle") else \
       win32service.OpenService(_schSCManager, self.resource.service_name, win32service.SERVICE_ALL_ACCESS)
     if self.status():
         win32service.ControlService(self._service_handle,
                                     win32service.SERVICE_CONTROL_STOP)
         self.wait_status(win32service.SERVICE_STOPPED)
Exemplo n.º 24
0
 	def OnStartupCmd(self, id, code):
		service = self.GetSelService()
		if not service:
			return
		s = win32service.OpenService(self.scm, service[1], win32service.SERVICE_ALL_ACCESS)
		if StartupDlg(service[0], s).DoModal() == win32con.IDOK:
			self.ReloadData()
    def __init__(self, name):
        """
        name: 服务的名称
        """
        self.name = name

        #启动或停止服务时等待操作成功等待时间
        self.wait_time = 0.5
        #启动或停止服务时最大等待时间,超过时返回超时提示
        self.delay_time = 10
        self.scm = win32service.OpenSCManager(
            None,
            None,
            win32service.SC_MANAGER_ALL_ACCESS
        )

        if self.is_exists():
            try:
                self.handle = win32service.OpenService(
                    self.scm,
                    self.name,
                    win32service.SC_MANAGER_ALL_ACCESS
                )
            except Exception as e:
                self.log(e)
        else:
            print('服务 %s 没有安装'.encode('gbk') % self.name)
Exemplo n.º 26
0
 def service_stop(self, hnd, s):
     try:
         svcH = win32service.OpenService(hnd, s.name,
                                         win32service.SERVICE_STOP)
         return True
     except:
         return False
Exemplo n.º 27
0
    def uninstall_driver(self):
        hService = None
        pServiceConfig = None
        # dwBytesNeeded = 0
        # cbBufSize = 0

        try:
            self.__stop_driver()

            hService = win32service.OpenService(
                self.hSCManager, 'WINIO', win32service.SERVICE_ALL_ACCESS)

            # If QueryServiceConfig() can not return a correct config, it will
            # throw exception!
            pServiceConfig = win32service.QueryServiceConfig(hService)

            # If service is set to load automatically, don't delete it!
            # dwStartType
            if (pServiceConfig[1] == win32service.SERVICE_DEMAND_START):
                win32service.DeleteService(hService)

        except pywintypes.error as e:
            if e.winerror == EC_SERVICE_NOT_INSTALLED:
                return

            raise
Exemplo n.º 28
0
    def create(self):
        if not self.driver or not os.path.exists(self.driver):
            if self.debug:
                print "The driver does not exist at path: {0}".format(self.driver)
            return
        if self.debug:
            print "Trying to create service", self.service_name, self.driver

        try:
            if not self.service:
                self.service = win32service.CreateService(
                    self.manager,
                    self.service_name,
                    self.service_name,
                    win32service.SERVICE_ALL_ACCESS,
                    win32service.SERVICE_KERNEL_DRIVER,
                    win32service.SERVICE_DEMAND_START,
                    win32service.SERVICE_ERROR_IGNORE,
                    self.driver,
                    None, 0, None, None, None)
        except win32service.error as e:
            if self.debug:
                print "Unable to create service: {0}".format(e)
            self.service = win32service.OpenService(self.manager, self.service_name,
                                        win32service.SERVICE_ALL_ACCESS)
        try:
            win32service.ControlService(self.service, win32service.SERVICE_CONTROL_STOP)
        except win32service.error:
            pass
Exemplo n.º 29
0
    def svcStop(self, svc_name, machine=None):
        accessSCM = win32con.GENERIC_READ
        hscm = win32service.OpenSCManager(None, None, accessSCM)
        try:
            shandle = win32service.OpenService(hscm, svc_name, accessSCM)
            try:
                dependent_services = win32service.EnumDependentServices(
                    shandle, win32service.SERVICE_ACTIVE)
                for (service_name, display_name,
                     service_status) in dependent_services:
                    if (service_status[1] == RUNNING):
                        self.logger.info(
                            "Stopping {} service because it is dependency of {}"
                            .format(service_name, svc_name))
                        self.svcStop(service_name)
            finally:
                win32service.CloseServiceHandle(shandle)
        finally:
            win32service.CloseServiceHandle(hscm)

        status = win32serviceutil.StopService(svc_name, machine)[1]
        i = 0
        while status == STOPPING:
            time.sleep(1)
            status = self.svcStatus(svc_name, machine)
            i = i + 1
            if i > 60:
                self.logger.info("Timeout stopping %s service" % svc_name)
                raise TimeoutError
        return status
Exemplo n.º 30
0
    def load_driver(self):
        """Load the driver if possible."""
        # Check the driver is somewhere accessible.
        if self.driver is None:
            # Valid values
            # http://superuser.com/questions/305901/possible-values-of-processor-architecture
            machine = platform.machine()
            if machine == "AMD64":
                driver = "winpmem_x64.sys"
            elif machine == "x86":
                driver = "winpmem_x86.sys"
            else:
                raise plugin.PluginError("Unsupported architecture")

            self.driver = rekall.get_resource("WinPmem/%s" % driver)

            # Try the local directory
            if self.driver is None:
                self.driver = os.path.join(os.getcwd(), "WinPmem", driver)

        self.session.logging.debug("Loading driver from %s", self.driver)

        if not os.access(self.driver, os.R_OK):
            raise plugin.PluginError("Driver file %s is not accessible." %
                                     self.driver)

        # Must have absolute path here.
        self.hScm = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_CREATE_SERVICE)

        try:
            self.hSvc = win32service.CreateService(
                self.hScm, self.name, self.name,
                win32service.SERVICE_ALL_ACCESS,
                win32service.SERVICE_KERNEL_DRIVER,
                win32service.SERVICE_DEMAND_START,
                win32service.SERVICE_ERROR_IGNORE, self.driver, None, 0, None,
                None, None)

            self.session.logging.debug("Created service %s", self.name)
            # Remember to cleanup afterwards.
            self.we_started_service = True

        except win32service.error as e:
            # Service is already there, try to open it instead.
            self.hSvc = win32service.OpenService(
                self.hScm, self.name, win32service.SERVICE_ALL_ACCESS)

        # Make sure the service is stopped.
        try:
            win32service.ControlService(self.hSvc,
                                        win32service.SERVICE_CONTROL_STOP)
        except win32service.error:
            pass

        try:
            win32service.StartService(self.hSvc, [])
        except win32service.error, e:
            self.session.logging.debug("%s: will try to continue", e)