Exemple #1
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?")
Exemple #2
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
    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)
 def Delete(self):
     serviceHandle = None
     try:
         serviceHandle = ServiceEntity.__getServiceHandle(self.ServiceName, self.__serviceConfigManagerHandle)
         win32service.DeleteService(serviceHandle)
     finally:
         if serviceHandle:
             win32service.CloseServiceHandle(serviceHandle)
Exemple #5
0
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)
Exemple #6
0
 def delete( self ):
     if (self.hs is not None):
         if logger().VERBOSE:
             logger().log( "[helper] deleting service (handle = 0x%08x).." % self.hs )
         win32service.DeleteService( self.hs )
         win32service.CloseServiceHandle( self.hs )
         self.hs = None
     return True
Exemple #7
0
    def delete(self):
        log.info("Trying to delete the winpmem service...")

        try:
            win32service.DeleteService(self.service)
            win32service.CloseServiceHandle(self.service)
            win32service.CloseServiceHandle(self.manager)
        except Exception as e:
            raise DetectorError("Unable to delete the service: {0}".format(e))
Exemple #8
0
 def delete_service(self, name):
     """
     Stops and delete a service
     """
     self.stop_service(name)
     hsvc = self.get_service(name)
     del self.__managed_services[name]
     win32service.DeleteService(hsvc)
     win32service.CloseServiceHandle(hsvc)
Exemple #9
0
def delete(name, timeout=90):
    """
    Delete the named service

    Args:

        name (str): The name of the service to delete

        timeout (int):
            The time in seconds to wait for the service to be deleted before
            returning. This is necessary because a service must be stopped
            before it can be deleted. Default is 90 seconds

            .. versionadded:: 2017.7.9,2018.3.4

    Returns:
        bool: ``True`` if successful, otherwise ``False``. Also returns ``True``
            if the service is not present

    CLI Example:

    .. code-block:: bash

        salt '*' service.delete <service name>
    """
    handle_scm = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(
            handle_scm, name, win32service.SERVICE_ALL_ACCESS
        )
    except pywintypes.error as exc:
        win32service.CloseServiceHandle(handle_scm)
        if exc.winerror != 1060:
            raise CommandExecutionError(
                "Failed to open {}. {}".format(name, exc.strerror)
            )
        log.debug('Service "{}" is not present'.format(name))
        return True

    try:
        win32service.DeleteService(handle_svc)
    except pywintypes.error as exc:
        raise CommandExecutionError(
            "Failed to delete {}. {}".format(name, exc.strerror)
        )
    finally:
        log.debug("Cleaning up")
        win32service.CloseServiceHandle(handle_scm)
        win32service.CloseServiceHandle(handle_svc)

    end_time = time.time() + int(timeout)
    while name in get_all() and time.time() < end_time:
        time.sleep(1)

    return name not in get_all()
Exemple #10
0
    def remove_service(self):
        self.session.logging.debug("Removing service %s", self.name)
        # Make sure the handle is closed.
        self.session.physical_address_space.close()

        try:
            win32service.ControlService(self.hSvc,
                                        win32service.SERVICE_CONTROL_STOP)
        except win32service.error:
            pass
        win32service.DeleteService(self.hSvc)
        win32service.CloseServiceHandle(self.hSvc)
Exemple #11
0
def delete_services(svc_id):
    for sv_name, sv_desc, sv_status in list_services():
        if sv_name.find(svc_id) != -1:
            try:
                print("delete service %s" % sv_name)
                
                svc_mgr = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
                svc_handle = win32service.OpenService(svc_mgr, sv_name, win32service.SERVICE_ALL_ACCESS)
                win32service.DeleteService(svc_handle)
                
            except:
                print("failed to delete service %s" % sv_name)  
Exemple #12
0
 def remove(self):
     self.stop()
     try:
         svc_mgr = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
         svc_handle = win32service.OpenService(svc_mgr, self.cls._svc_name_, win32service.SERVICE_ALL_ACCESS)
         win32service.DeleteService(svc_handle)
         return True
     except Exception as e:
         # the service is not installed
         if e[0] in [1060]:
             return False
         else:
             raise
Exemple #13
0
    def delete(self):
        if self.debug:
            print "Trying to delete the winpmem service..."

        try:
            win32service.DeleteService(self.service)
        except:
            if self.debug:
                print "Unable to DeleteService"
        try:
            win32service.CloseServiceHandle(self.service)
        except Exception as e:
            if self.debug:
                print "Unable to CloseServiceHandle: {0}, {1}".format(self.service, e)
        try:
            win32service.CloseServiceHandle(self.manager)
        except Exception as e:
            if self.debug:
                print "Unable to delete the service: {0}".format(e)
Exemple #14
0
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
Exemple #15
0
    def removeService(self, serviceName):
        """
        Remove Service
        Stops the service then starts to remove it
        @param serviceName: name of the service to remove
        """
        if self.isServiceRunning(serviceName):
            self.stopService(serviceName)

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

        serviceHandler = win32service.OpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)

        win32service.DeleteService(serviceHandler)

        win32service.CloseServiceHandle(serviceHandler)

        if not self.isServiceInstalled(serviceName):
            self.logger.info('Service %s removed Successfully' % serviceName)

            return True
Exemple #16
0
  def action_uninstall(self):
    hSCM = safe_open_scmanager()

    try:
      try:
        hSvc = win32serviceutil.SmartOpenService(hSCM, self.resource.service_name,
                                                 win32service.SERVICE_ALL_ACCESS)
      except win32api.error, details:
        if details.winerror == winerror.ERROR_SERVICE_DOES_NOT_EXIST:
          # Nothing to do
          return
        else:
          raise Fail("Error removing service {0}: {1}".format(self.resource.service_name, details.winerror))

      try:
        win32service.DeleteService(hSvc)
      except win32api.error:
        # Error mostly means the service is running and its removal is delayed until the next opportunity
        pass
      finally:
        win32service.CloseServiceHandle(hSvc)
Exemple #17
0
def delete(name):
    '''
    Delete the named service

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

    Returns:
        bool: True if successful, False otherwise

    CLI Example:

    .. code-block:: bash

        salt '*' service.delete <service name>
    '''
    handle_scm = win32service.OpenSCManager(None, None,
                                            win32service.SC_MANAGER_CONNECT)

    try:
        handle_svc = win32service.OpenService(handle_scm, name,
                                              win32service.SERVICE_ALL_ACCESS)
    except pywintypes.error as exc:
        raise CommandExecutionError('Failed To Open {0}: {1}'.format(
            name, exc[2]))

    win32service.DeleteService(handle_svc)

    win32service.CloseServiceHandle(handle_scm)
    win32service.CloseServiceHandle(handle_svc)

    attempts = 0
    while name in get_all() and attempts <= RETRY_ATTEMPTS:
        time.sleep(1)
        attempts += 1

    return name not in get_all()
Exemple #18
0
        def UninstallService(self, name):
            '''
            Uninstalls the NT service with the given name.
            '''
            # grab a handle to the manager
            try:
                mgr = win32service.OpenSCManager(
                    None, None, win32service.SC_MANAGER_ALL_ACCESS)
            except win32service.error as err:
                msg = "Failed to open service manager: %s" % err[2]
                mainlog.critical(msg)
                raise _EarlyServerExit

            # get a handle to the service
            try:
                svc = win32service.OpenService(mgr, name,
                                               win32service.SERVICE_ALL_ACCESS)
            except win32service.error as err:
                msg = "Failed to open service: %s" % err[2]
                mainlog.critical(msg)
                raise _EarlyServerExit

            # stop the service if needed
            state = win32service.QueryServiceStatus(svc)
            if state.dwCurrentState != win32service.SERVICE_STOPPED:
                try:
                    win32service.ControlService(
                        svc, win32service.SERVICE_CONTROL_STOP)
                except win32service.error as err:
                    msg = "Failed to stop service: %s" % err[2]
                    mainlog.error(msg)

            # delete the service
            try:
                win32service.DeleteService(svc)
            except win32service.error as err:
                msg = "Failed to remove service: %s" % err[2]
Exemple #19
0
        return

    try:
        fd = win32file.CreateFile(
            "\\\\.\\" + FLAGS.name,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
            win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

        try:
            t = time.time()
            image = Image(fd)
            print "Imaging to %s" % FLAGS.filename
            image.DumpWithRead(FLAGS.filename)
            print "\nCompleted in %s seconds" % (time.time() - t)
        finally:
            win32file.CloseHandle(fd)
    finally:
        try:
            win32service.ControlService(hSvc,
                                        win32service.SERVICE_CONTROL_STOP)
        except win32service.error:
            pass
        win32service.DeleteService(hSvc)
        win32service.CloseServiceHandle(hSvc)


if __name__ == "__main__":
    (FLAGS, args) = parser.parse_args()
    main()
Exemple #20
0
    def startasync(self, args, config):
        """
        First checks for a valid installation, then checks the grid,
        then registers the action: "node HOST start"
        """

        self.check_access(config=config)
        self.checkice()
        self.check_node(args)
        if self._isWindows():
            self.checkwindows(args)

        if 0 == self.status(args, node_only=True):
            self.ctx.die(876, "Server already running")

        self._initDir()
        # Do a check to see if we've started before.
        self._regdata()
        self.check([])

        user = args.user
        pasw = args.password
        descript = self._descript(args)

        if self._isWindows():
            svc_name = "OMERO.%s" % args.node
            output = self._query_service(svc_name)

            # Now check if the server exists
            if 0 <= output.find("DOESNOTEXIST"):
                binpath = """icegridnode.exe "%s" --deploy "%s" --service\
                %s""" % (self._icecfg(), descript, svc_name)

                # By default: "NT Authority\Local System"
                if not user:
                    try:
                        user = config.as_map()["omero.windows.user"]
                    except KeyError:
                        user = None
                if user is not None and len(user) > 0:
                    if not "\\" in user:
                        computername = win32api.GetComputerName()
                        user = "******".join([computername, user])
                    try:
                        # See #9967, code based on http://mail.python.org/\
                        # pipermail/python-win32/2010-October/010791.html
                        self.ctx.out("Granting SeServiceLogonRight to service"
                                     " user \"%s\"" % user)
                        policy_handle = win32security.LsaOpenPolicy(
                            None, win32security.POLICY_ALL_ACCESS)
                        sid_obj, domain, tmp = \
                            win32security.LookupAccountName(None, user)
                        win32security.LsaAddAccountRights(
                            policy_handle, sid_obj, ('SeServiceLogonRight', ))
                        win32security.LsaClose(policy_handle)
                    except pywintypes.error, details:
                        self.ctx.die(
                            200, "Error during service user set up:"
                            " (%s) %s" % (details[0], details[2]))
                    if not pasw:
                        try:
                            pasw = config.as_map()["omero.windows.pass"]
                        except KeyError:
                            pasw = self._ask_for_password(
                                " for service user \"%s\"" % user)
                else:
                    pasw = None

                hscm = win32service.OpenSCManager(
                    None, None, win32service.SC_MANAGER_ALL_ACCESS)
                try:
                    self.ctx.out("Installing %s Windows service." % svc_name)
                    hs = win32service.CreateService(
                        hscm, svc_name, svc_name,
                        win32service.SERVICE_ALL_ACCESS,
                        win32service.SERVICE_WIN32_OWN_PROCESS,
                        win32service.SERVICE_AUTO_START,
                        win32service.SERVICE_ERROR_NORMAL, binpath, None, 0,
                        None, user, pasw)
                    self.ctx.out("Successfully installed %s Windows service." %
                                 svc_name)
                    win32service.CloseServiceHandle(hs)
                finally:
                    win32service.CloseServiceHandle(hscm)

            # Then check if the server is already running
            if 0 <= output.find("RUNNING"):
                self.ctx.die(
                    201, "%s is already running. Use stop first" % svc_name)

            # Finally, try to start the service - delete if startup fails
            hscm = win32service.OpenSCManager(
                None, None, win32service.SC_MANAGER_ALL_ACCESS)
            try:
                try:
                    hs = win32service.OpenService(
                        hscm, svc_name, win32service.SC_MANAGER_ALL_ACCESS)
                    win32service.StartService(hs, None)
                    self.ctx.out("Starting %s Windows service." % svc_name)
                except pywintypes.error, details:
                    self.ctx.out("%s service startup failed: (%s) %s" %
                                 (svc_name, details[0], details[2]))
                    win32service.DeleteService(hs)
                    self.ctx.die(202, "%s service deleted." % svc_name)
            finally:
                win32service.CloseServiceHandle(hs)
                win32service.CloseServiceHandle(hscm)
Exemple #21
0
def main():
    """Load the driver and image the memory."""
    # Check the driver is somewhere
    if not FLAGS.driver or not os.access(FLAGS.driver, os.R_OK):
        print("You must specify a valid driver file.")
        sys.exit(-1)

    # Must have absolute path here.
    driver = os.path.join(os.getcwd(), FLAGS.driver)
    hScm = win32service.OpenSCManager(None, None,
                                      win32service.SC_MANAGER_CREATE_SERVICE)

    try:
        hSvc = win32service.CreateService(hScm, FLAGS.name, FLAGS.name,
                                          win32service.SERVICE_ALL_ACCESS,
                                          win32service.SERVICE_KERNEL_DRIVER,
                                          win32service.SERVICE_DEMAND_START,
                                          win32service.SERVICE_ERROR_IGNORE,
                                          driver, None, 0, None, None, None)
    except win32service.error as e:
        print(e)
        hSvc = win32service.OpenService(hScm, FLAGS.name,
                                        win32service.SERVICE_ALL_ACCESS)

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

    if FLAGS.unload:
        print("unloaded winpmem driver.")
        return

    try:
        win32service.StartService(hSvc, [])
    except win32service.error as e:
        print("%s: will try to continue" % e)

    if FLAGS.load:
        fd = win32file.CreateFile(
            "\\\\.\\" + FLAGS.name,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
            win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

        print(r"Loaded the winpmem driver. You can now attach "
              r"volatility to \\.\pmem")
        image = Image(fd)

        return

    try:
        fd = win32file.CreateFile(
            "\\\\.\\" + FLAGS.name,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None,
            win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)

        try:
            t = time.time()
            image = Image(fd)
            print("Imaging to %s" % FLAGS.filename)
            image.DumpWithRead(FLAGS.filename)
            print("\nCompleted in %s seconds" % (time.time() - t))
        finally:
            win32file.CloseHandle(fd)
    finally:
        try:
            win32service.ControlService(hSvc,
                                        win32service.SERVICE_CONTROL_STOP)
        except win32service.error:
            pass
        win32service.DeleteService(hSvc)
        win32service.CloseServiceHandle(hSvc)