Exemplo n.º 1
0
    async def start(self):
        status_info = win32service.QueryServiceStatus(self.handle)

        if status_info[1] == win32service.SERVICE_RUNNING:
            return True
        try:
            if self.handle:
                win32service.StartService(self.handle, None)
        except Exception as e:
            raise PermissionError("Ошибка запуска сервиса")
        status_info = win32service.QueryServiceStatus(self.handle)

        if status_info[1] == win32service.SERVICE_RUNNING:
            return True
        elif status_info[1] == win32service.SERVICE_START_PENDING:
            start_time = datetime.now()
            while True:
                if (datetime.now() - start_time).seconds > self.delay_time:
                    raise TimeoutError("Таймаут запуска сервиса")

                time.sleep(self.wait_time)
                if (win32service.QueryServiceStatus(
                        self.handle)[1] == win32service.SERVICE_RUNNING):
                    return True
        else:
            raise PermissionError("Ошибка запуска сервиса")
Exemplo n.º 2
0
    def start( self ):

        (type, state, ca, exitcode, svc_exitcode, checkpoint, waithint) = win32service.QueryServiceStatus( self.hs )
        if logger().VERBOSE: logger().log( "[helper] starting chipsec service: handle = 0x%x, type = 0x%x, state = 0x%x" % (self.hs, type, state) )

        if win32service.SERVICE_RUNNING == state:
            if logger().VERBOSE: logger().log( "[helper] chipsec service already running" )
        else:
            try:
                win32service.StartService( self.hs, None );
                state = win32service.QueryServiceStatus( self.hs )[1]
                while win32service.SERVICE_START_PENDING == state:
                    time.sleep( 1 )
                    state = win32service.QueryServiceStatus( self.hs )[1]
                if win32service.SERVICE_RUNNING == state:
                    if logger().VERBOSE: logger().log( "[helper] chipsec service started (SERVICE_RUNNING)" )
            except win32service.error, (hr, fn, msg):
                if logger().VERBOSE: logger().log_bad(traceback.format_exc())
                if (winerror.ERROR_ALREADY_EXISTS == hr or winerror.ERROR_SERVICE_ALREADY_RUNNING == hr):
                    if logger().VERBOSE: logger().log( "[helper] chipsec service already exists: %s (%d)" % (msg, hr) )
                else:
                    win32service.CloseServiceHandle( self.hs )
                    self.hs = None
                    string  = "StartService failed: %s (%d)" % (msg, hr)
                    logger().error( string )
                    raise OsHelperError(string,hr)
Exemplo n.º 3
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.º 4
0
    def start(self):
        """开启服务"""
        try:
            if self.handle:
                win32service.StartService(self.handle, None)
        except Exception as e:
            self.log(e)
        status_info = win32service.QueryServiceStatus(self.handle)

        if status_info[1] == win32service.SERVICE_RUNNING:
            return '启动服务%s成功'.encode('gbk') % self.name
        elif status_info[1] == win32service.SERVICE_START_PENDING:
            # 如果服务正在启动中则延迟返回启动信息,直到启动成功,或返回启动时间过长信息
            start_time = datetime.datetime.now()
            while True:
                if (datetime.datetime.now() -
                        start_time).seconds > self.delay_time:
                    return '启动服务%s时间太长'.encode('gbk') % self.name

                time.sleep(self.wait_time)
                if win32service.QueryServiceStatus(
                        self.handle)[1] == win32service.SERVICE_RUNNING:
                    return '启动服务%s成功'.encode('gbk') % self.name
        else:
            return '启动服务%s失败'.encode('gbk') % self.name
Exemplo n.º 5
0
    def start(self):
        """Start service"""
        try:
            if self.handle:
                win32service.StartService(self.handle, None)
        except Exception as e:
            logging.info(e)
        status_info = win32service.QueryServiceStatus(self.handle)

        if status_info[1] == win32service.SERVICE_RUNNING:
            logging.info('Start %s successfully.', self.name)
            return 'Start %s successfully.' % (self.name)
        elif status_info[1] == win32service.SERVICE_START_PENDING:
            start_time = datetime.datetime.now()
            while True:
                if (datetime.datetime.now() -
                        start_time).seconds > self.delay_time:
                    logging.info('Start %s too much time.', self.name)
                    return 'Start %s too much time.' % (self.name)

                time.sleep(self.wait_time)
                if win32service.QueryServiceStatus(
                        self.handle)[1] == win32service.SERVICE_RUNNING:
                    logging.info('Start %s successfully.', self.name)
                    return 'Start %s successfully.' % (self.name)
        else:
            logging.info('Start %s fail.', self.name)
            return 'Start %s fail.' % (self.name)
Exemplo n.º 6
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.º 7
0
 def start(self):
     """开启服务"""
     try:
         if self.handle:
             win32service.StartService(self.handle, None)
     except Exception, e:
         self.log(e)
Exemplo n.º 8
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.º 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 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)
Exemplo n.º 11
0
 	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()
Exemplo n.º 12
0
 def start(self):
     """ Start the service. """
     hService = winsvc.OpenService(self.scm_handle, self.ServiceName,
                                   winsvc.SERVICE_START)
     try:
         winsvc.StartService(hService, None)
     except pywintypes.error, e:
         self.last_error = e.strerror
Exemplo n.º 13
0
 def start(self, name):
     try:
         handle = win32service.OpenService(self.scm, name,
                                           win32service.SERVICE_ALL_ACCESS)
         if handle:
             win32service.StartService(handle, None)
             win32service.CloseServiceHandle(handle)
     except Exception as e:
         logging.error(e)
Exemplo n.º 14
0
def start_service(*svcs):
    scm_h = Wsvc.OpenSCManager(None, None, Wsvc.SC_MANAGER_ENUMERATE_SERVICE)
    for svc in svcs:
        svc_h = Wsvc.OpenService(
            scm_h, svc, Wsvc.SERVICE_QUERY_STATUS | Wsvc.SERVICE_START)
        status = Wsvc.QueryServiceStatusEx(svc_h)
        if status["CurrentState"] == Wsvc.SERVICE_STOPPED:
            Wsvc.StartService(svc_h, None)
        Wsvc.CloseServiceHandle(svc_h)
    Wsvc.CloseServiceHandle(scm_h)
Exemplo n.º 15
0
 def start_service(self, name):
     """
     Starts a service
     """
     try:
         hsvc = self.get_service(name)
         win32service.StartService(hsvc, [])
         return True
     except win32service.error:
         return False
Exemplo n.º 16
0
def StartService(service):
    try:
        win32service.StartService(service, None)
        status = win32service.QueryServiceStatus(service)[1]
        while (status == win32service.SERVICE_START_PENDING):
            time.sleep(1)
            status = win32service.QueryServiceStatus(service)[1]
        return status == win32service.SERVICE_RUNNING
    except:
        return False
Exemplo n.º 17
0
def StartService(serviceName, args = None, machine = None):
    hscm = win32service.OpenSCManager(machine,None,win32service.SC_MANAGER_ALL_ACCESS)
    try:

        hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS)
        try:
            win32service.StartService(hs, args)
        finally:
            win32service.CloseServiceHandle(hs)
    finally:
        win32service.CloseServiceHandle(hscm)
Exemplo n.º 18
0
 def Start(self):
     if self.started:
         cx_Logging.Info("Service %s already started.", self.name)
     else:
         cx_Logging.Info("Starting service %s", self.name)
         win32service.StartService(self.handle, None)
         while True:
             if self.state != win32service.SERVICE_START_PENDING:
                 break
             cx_Logging.Info("    waiting for service to start....")
             time.sleep(2)
Exemplo n.º 19
0
def start_service(h_svc, logger):
    """Starts the winpmem service"""
    # Make sure the service is stopped.
    try:
        win32service.ControlService(h_svc, win32service.SERVICE_CONTROL_STOP)
    except win32service.error:
        pass

    try:
        win32service.StartService(h_svc, [])
    except win32service.error, e:
        logger.error(str(e) + ": will try to continue")
Exemplo n.º 20
0
 def Start(self, serviceName):
     """Start the service."""
     print "Starting service", serviceName
     handle = win32service.OpenService(self.__handle, serviceName,
                                       SC_MANAGER_ALL_ACCESS)
     win32service.StartService(handle, None)
     while True:
         state = self.__GetState(handle)
         if state != SERVICE_START_PENDING:
             break
         print "    waiting for service to start...."
         time.sleep(2)
     win32service.CloseServiceHandle(handle)
Exemplo n.º 21
0
    def start(self):
        log.info("Trying to start the winpmem service...")

        try:
            win32service.StartService(self.service, [])
        except Exception as e:
            # If the service is already loaded we can continue.
            # This generally shouldn't happen, but in case it does we can just
            # try to use the running instance and unload it when we're done.
            if hasattr(e, 'winerror') and int(e.winerror) == 1056:
                log.info("The service appears to be already loaded")
            # If the problem is different, we need to terminate.
            else:
                raise DetectorError("Unable to start service: {0}".format(e))

        self.wait_status()
Exemplo n.º 22
0
def StartService(serviceName):
    retval = False
    manager = None
    service = None
    try:
        manager = win32service.OpenSCManager('localhost', 'ServicesActive',
                                             win32service.SC_MANAGER_CONNECT)
        service = win32service.OpenService(
            manager, serviceName,
            win32service.SERVICE_START | win32service.SERVICE_QUERY_STATUS)
        status = win32service.QueryServiceStatus(service)
        if status[1] == win32service.SERVICE_RUNNING or status[
                1] == win32service.SERVICE_START_PENDING:
            print(('Service %s is already started (%s)' %
                   (serviceName, GetCurrentStateStr(state)[0])))
        else:
            print(('Starting service %s' % serviceName))
            if win32service.StartService(service, None):
                started = False
                slept = 0
                while not started and slept < 5:
                    status = win32service.QueryServiceStatus(service)
                    if status[1] == win32service.SERVICE_RUNNING:
                        started = True
                    else:
                        win32api.Sleep(1000)
                        slept += 1
        retval = True
    except Exception as inst:
        if len(inst.args) == 3:
            number = inst.args[0]
            function = inst.args[1]
            message = inst.args[2]
            print(('ERROR starting service: %#08x (%s): %s' %
                   (number, function, message)))
        else:
            print(('ERROR starting service: %s' % inst))
    finally:
        if service:
            win32service.CloseServiceHandle(service)
        if manager:
            win32service.CloseServiceHandle(manager)
    return retval
    def Start(self):
        status = self.GetServiceStatus()
        if status['CurrentState'].Win32Value() == CurrentStateType.RUNNING:
            return status

        serviceHandle = None
        try:
            serviceHandle = ServiceEntity.__getServiceHandle(self.ServiceName, self.__serviceConfigManagerHandle)
            win32service.StartService(serviceHandle, {})
            start = time.time()
            status = self.GetServiceStatus()
            while status['CurrentState'].Win32Value() != CurrentStateType.RUNNING:
                if time.time() - start > self._TIMEOUT:
                    raise TimeoutException()
                time.sleep(.5)
                status = self.GetServiceStatus()
            return status
        finally:
            win32service.CloseServiceHandle(serviceHandle)
Exemplo n.º 24
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, e:
        print("%s: will try to continue" % e)
Exemplo n.º 25
0
 def start(self):
     win32service.StartService(self.handle, None)
Exemplo n.º 26
0
 def start(self):
     ws.StartService(self.handle, None)
Exemplo n.º 27
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)
Exemplo n.º 28
0
        None,
        None)
except:
    print "Cannot create service!"
    sys.exit()

key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE,
    "System\\CurrentControlSet\\Services\\%s\\Parameters" % ServiceName)
try:
    win32api.RegSetValueEx(key,
        "ServiceDll",
        0,
        win32con.REG_EXPAND_SZ,
        ImagePath);
finally:
    win32api.RegCloseKey(key)

key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE,
    "Software\\Microsoft\\Windows NT\\CurrentVersion\\SvcHost")
try:
    win32api.RegSetValueEx(key,
        ServiceName,
        0,
        win32con.REG_MULTI_SZ,
        [ServiceName, '']);
finally:
    win32api.RegCloseKey(key)

win32service.StartService(hs, ServiceArgs)
win32service.CloseServiceHandle(hs)
win32service.CloseServiceHandle(hscm)
Exemplo n.º 29
0
        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 r"unloaded winpmem driver."
        return

    try:
        win32service.StartService(hSvc, [])
    except win32service.error, 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)
Exemplo n.º 30
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)