Esempio n. 1
0
	def __copyDataToWinamp(self, data):
		if type(data) is str:
			dataToCopy = create_string_buffer(data)
		else:
			dataToCopy = data

		# allocate data in Winamp's address space
		lpAddress = windll.kernel32.VirtualAllocEx(self.__hProcess, None, sizeof(dataToCopy), win32con.MEM_COMMIT, win32con.PAGE_READWRITE)
		if not lpAddress:
			raise pywintypes.error(GetLastError(), "VirtualAllocEx")

		# write data to Winamp's memory
		rc = windll.kernel32.WriteProcessMemory(self.__hProcess, lpAddress, addressof(dataToCopy), sizeof(dataToCopy), None)
		if not rc:
			raise pywintypes.error(GetLastError(), "WriteProcessMemory")

		return lpAddress
Esempio n. 2
0
    def test_windows_pipe_error_encoding_issue(self, mock_logging):
        import pywintypes
        with pytest.raises(errors.ConnectionError):
            with handle_connection_errors(mock.Mock(api_version='1.22')):
                raise pywintypes.error(9999, 'WriteFile', 'I use weird characters \xe9')

        _, args, _ = mock_logging.error.mock_calls[0]
        assert 'Windows named pipe error: I use weird characters \xe9 (code: 9999)' == args[0]
Esempio n. 3
0
    def test_windows_pipe_error_misc(self, mock_logging):
        import pywintypes
        with pytest.raises(errors.ConnectionError):
            with handle_connection_errors(mock.Mock(api_version='1.22')):
                raise pywintypes.error(231, 'WriteFile', 'The pipe is busy.')

        _, args, _ = mock_logging.error.mock_calls[0]
        assert "Windows named pipe error: The pipe is busy. (code: 231)" == args[0]
Esempio n. 4
0
    def test_windows_pipe_error_no_data(self, mock_logging):
        import pywintypes
        with pytest.raises(errors.ConnectionError):
            with handle_connection_errors(mock.Mock(api_version='1.22')):
                raise pywintypes.error(232, 'WriteFile', 'The pipe is being closed.')

        _, args, _ = mock_logging.error.mock_calls[0]
        assert "The current Compose file version is not compatible with your engine version." in args[0]
Esempio n. 5
0
 def testStrangeArgsNone(self):
     try:
         raise pywintypes.error()
         self.fail("Expected exception")
     except pywintypes.error as exc:
         self.failUnlessEqual(exc.args, ())
         self.failUnlessEqual(exc.winerror, None)
         self.failUnlessEqual(exc.funcname, None)
         self.failUnlessEqual(exc.strerror, None)
Esempio n. 6
0
 def test_user_name_windows_route2(self, mock_get_user_name):
     "Get user name using GetUserName"
     # Creating instance of pywintypes.error so this patch needs to be
     # within the function body
     with patch.object(
             win32api, 'GetUserNameEx',
             side_effect=pywintypes.error()) as mock_get_user_name_ex:
         self.assertEqual(self.MOCK_USERNAME, user_name())
         mock_get_user_name_ex.assert_called_once_with(3)
         mock_get_user_name.assert_called_once_with()
Esempio n. 7
0
def RegEnumKey(*arg):
    "Enumerates subkeys of the specified open registry key. "
    key, index = arg
    if isinstance(key, HKEY):
        try:
            return CP.options(key.data)[index]
        except IndexError:
            raise pywintypes.error(259, 'pvApi_RegEnum_Key', 'IndexError')
    else:
        return Hook('RegEnumKey', *arg)
Esempio n. 8
0
 def testStrangeArgsNotEnough(self):
     try:
         raise pywintypes.error("foo")
         self.fail("Expected exception")
     except pywintypes.error as exc:
         assert exc.args[0] == "foo"
         # 'winerror' always args[0]
         self.failUnlessEqual(exc.winerror, "foo")
         self.failUnlessEqual(exc.funcname, None)
         self.failUnlessEqual(exc.strerror, None)
 def test_user_name_windows_route2(self, mock_get_user_name):
     "Get user name using GetUserName"
     # Creating instance of pywintypes.error so this patch needs to be
     # within the function body
     with patch.object(
         win32api, 'GetUserNameEx', side_effect=pywintypes.error()
     ) as mock_get_user_name_ex:
         self.assertEqual(self.MOCK_USERNAME, user_name())
         mock_get_user_name_ex.assert_called_once_with(3)
         mock_get_user_name.assert_called_once_with()
Esempio n. 10
0
 def testStrangeArgsTooMany(self):
     try:
         raise pywintypes.error("foo", "bar", "you", "never", "kn", 0)
         self.fail("Expected exception")
     except pywintypes.error as exc:
         self.failUnlessEqual(exc.args[0], "foo")
         self.failUnlessEqual(exc.args[-1], 0)
         self.failUnlessEqual(exc.winerror, "foo")
         self.failUnlessEqual(exc.funcname, "bar")
         self.failUnlessEqual(exc.strerror, "you")
Esempio n. 11
0
 def testStrangeArgsTooMany(self):
     try:
         raise pywintypes.error("foo", "bar", "you", "never", "kn", 0)
         self.fail("Expected exception")
     except pywintypes.error as exc:
         self.failUnlessEqual(exc.args[0], "foo")
         self.failUnlessEqual(exc.args[-1], 0)
         self.failUnlessEqual(exc.winerror, "foo")
         self.failUnlessEqual(exc.funcname, "bar")
         self.failUnlessEqual(exc.strerror, "you")
def WaitForServiceStatus(serviceName, status, waitSecs, machine=None):
    """Waits for the service to return the specified status.  You
    should have already requested the service to enter that state"""
    for i in range(waitSecs*4):
        now_status = QueryServiceStatus(serviceName, machine)[1]
        if now_status == status:
            break
        win32api.Sleep(250)
    else:
        raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "QueryServiceStatus", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
Esempio n. 13
0
    def test_windows_pipe_error_encoding_issue(self, mock_logging):
        import pywintypes
        with pytest.raises(errors.ConnectionError):
            with handle_connection_errors(mock.Mock(api_version='1.22')):
                raise pywintypes.error(9999, 'WriteFile',
                                       'I use weird characters \xe9')

        _, args, _ = mock_logging.error.mock_calls[0]
        assert 'Windows named pipe error: I use weird characters \xe9 (code: 9999)' == args[
            0]
def WaitForServiceStatus(serviceName, status, waitSecs, machine=None):
    """Waits for the service to return the specified status.  You
    should have already requested the service to enter that state"""
    for i in range(waitSecs*4):
        now_status = QueryServiceStatus(serviceName, machine)[1]
        if now_status == status:
            break
        win32api.Sleep(250)
    else:
        raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "QueryServiceStatus", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
Esempio n. 15
0
    def test_windows_pipe_error_no_data(self, mock_logging):
        import pywintypes
        with pytest.raises(errors.ConnectionError):
            with handle_connection_errors(mock.Mock(api_version='1.22')):
                raise pywintypes.error(232, 'WriteFile',
                                       'The pipe is being closed.')

        _, args, _ = mock_logging.error.mock_calls[0]
        assert "The current Compose file version is not compatible with your engine version." in args[
            0]
Esempio n. 16
0
 def test_stop_not_running(self):
     '''
     Test stopping a service that is already stopped
     '''
     mock_error = MagicMock(side_effect=pywintypes.error(
         1062, 'StopService', 'Service is not running'))
     mock_info = MagicMock(side_effect=[{'Status': 'Stopped'}])
     with patch.object(win32serviceutil, 'StopService', mock_error), \
             patch.object(win_service, '_status_wait', mock_info):
         self.assertTrue(win_service.stop('spongebob'))
Esempio n. 17
0
 def testStrangeArgsNotEnough(self):
     try:
         raise pywintypes.error("foo")
         self.fail("Expected exception")
     except pywintypes.error as exc:
         assert exc.args[0] == "foo"
         # 'winerror' always args[0]
         self.failUnlessEqual(exc.winerror, "foo")
         self.failUnlessEqual(exc.funcname, None)
         self.failUnlessEqual(exc.strerror, None)
Esempio n. 18
0
def run(args, cwd=None, as_admin=False, cmd_window=False):
    """ Run an arbitrary command. """
    if isinstance(args, str):
        args = [args]
    args = list(args)

    if cwd is None:
        cwd = os.getenv("USERPROFILE")

    if as_admin:
        subprocess.call(args, shell=True, cwd=cwd)
    else:
        # We have to do all this nonsense to spawn the process
        # as the logged in user, rather than as the administrator
        # that PyleWM is running as
        startup_info = STARTUPINFO()
        process_information = PROCESS_INFORMATION()

        shell_window = ctypes.windll.user32.GetShellWindow()
        thread_id, process_id = win32process.GetWindowThreadProcessId(
            shell_window)
        shell_handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                            False, process_id)
        shell_token = win32security.OpenProcessToken(shell_handle,
                                                     win32con.TOKEN_DUPLICATE)

        spawn_token = win32security.DuplicateTokenEx(
            shell_token, win32security.SecurityImpersonation,
            win32con.TOKEN_QUERY | win32con.TOKEN_ASSIGN_PRIMARY
            | win32con.TOKEN_DUPLICATE
            | win32con.TOKEN_ADJUST_DEFAULT | 0x0100,
            win32security.TokenPrimary, None)

        escaped_commandline = ""
        for arg in args:
            escaped_commandline += '"'
            escaped_commandline += arg
            escaped_commandline += '" '

        # Try to lookup where the exe is from PATH
        executable = args[0]
        if not os.path.isfile(executable):
            executable = shutil.which(executable)

        success = ctypes.windll.advapi32.CreateProcessWithTokenW(
            int(spawn_token), 0, executable, escaped_commandline,
            win32con.CREATE_NO_WINDOW
            if not cmd_window else win32con.CREATE_NEW_CONSOLE, None,
            os.getcwd(), ctypes.pointer(startup_info),
            ctypes.pointer(process_information))

        if not success:
            error = ctypes.get_last_error()
            raise pywintypes.error(error, 'CreateProcessWithTokenW',
                                   win32api.FormatMessageW(error))
Esempio n. 19
0
 def test_stop_not_running(self):
     """
     Test stopping a service that is already stopped
     """
     mock_error = MagicMock(side_effect=pywintypes.error(
         1062, "StopService", "Service is not running"))
     mock_info = MagicMock(side_effect=[{"Status": "Stopped"}])
     with patch.object(win32serviceutil, "StopService",
                       mock_error), patch.object(win_service,
                                                 "_status_wait", mock_info):
         self.assertTrue(win_service.stop("spongebob"))
Esempio n. 20
0
 def test_start_already_running(self):
     '''
     Test starting a service that is already running
     '''
     mock_false = MagicMock(return_value=False)
     mock_error = MagicMock(side_effect=pywintypes.error(
         1056, 'StartService', 'Service is running'))
     mock_info = MagicMock(side_effect=[{'Status': 'Running'}])
     with patch.object(win32serviceutil, 'StartService', mock_error), \
              patch.object(win_service, 'disabled', mock_false), \
              patch.object(win_service, '_status_wait', mock_info):
         self.assertTrue(win_service.start('spongebob'))
Esempio n. 21
0
def __StopServiceWithTimeout(hs, waitSecs = 30):
    try:
        status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP)
    except pywintypes.error as exc:
        if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE:
            raise
    for i in range(waitSecs):
        status = win32service.QueryServiceStatus(hs)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        win32api.Sleep(1000)
    else:
        raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
Esempio n. 22
0
def __StopServiceWithTimeout(hs, waitSecs = 30):
    try:
        status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP)
    except pywintypes.error as exc:
        if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE:
            raise
    for i in range(waitSecs):
        status = win32service.QueryServiceStatus(hs)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        win32api.Sleep(1000)
    else:
        raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
Esempio n. 23
0
 def test_get_counters_no_data_to_return(self, mock_query):
     mock_query.side_effect = pywintypes.error(-2147481643,
                                               "CollectQueryData",
                                               "No data to return.")
     counter_list = [
         ("Memory", None, "Available Bytes"),
         ("Paging File", "*", "% Usage"),
         ("Processor", "*", "% Processor Time"),
         ("Server", None, "Work Item Shortages"),
         ("Server Work Queues", "*", "Queue Length"),
         ("System", None, "Context Switches/sec"),
     ]
     results = win_pdh.get_counters(counter_list)
     assert results == {}
Esempio n. 24
0
def duplicate_shell_token():
    hWndShell = user32.GetShellWindow()
    if not hWndShell:
        raise pywintypes.error(winerror.ERROR_FILE_NOT_FOUND, 'GetShellWindow',
                               'no shell window')
    tid, pid = win32process.GetWindowThreadProcessId(hWndShell)
    hProcShell = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      False, pid)
    hTokenShell = win32security.OpenProcessToken(hProcShell,
                                                 win32con.TOKEN_DUPLICATE)
    return win32security.DuplicateTokenEx(
        hTokenShell, win32security.SecurityImpersonation,
        win32con.TOKEN_ASSIGN_PRIMARY | win32con.TOKEN_DUPLICATE
        | win32con.TOKEN_QUERY | win32con.TOKEN_ADJUST_DEFAULT
        | TOKEN_ADJUST_SESSIONID, win32security.TokenPrimary, None)
Esempio n. 25
0
 def test_start_already_running(self):
     """
     Test starting a service that is already running
     """
     mock_false = MagicMock(return_value=False)
     mock_error = MagicMock(side_effect=pywintypes.error(
         1056, "StartService", "Service is running"))
     mock_info = MagicMock(side_effect=[{"Status": "Running"}])
     with patch.object(win32serviceutil, "StartService",
                       mock_error), patch.object(win_service, "disabled",
                                                 mock_false), patch.object(
                                                     win_service,
                                                     "_status_wait",
                                                     mock_info):
         self.assertTrue(win_service.start("spongebob"))
Esempio n. 26
0
def joindom(dom, user, passwd):
	netapi32 = windll.LoadLibrary ("netapi32.dll")
	user = '******'%(dom, user)
	ret = netapi32.NetJoinDomain(None, dom , None, user, passwd ,int(0x00000001|0x00000002|0x00000020))
	if ret != 0:
	    dicterr = dict()
	    dicterr[1219]='Fermez les connexions existantes sur le serveur'
	    dicterr[1311]='Domaine introuvable'
	    dicterr[1326]='erreur d\'authentification' 
	    dicterr[2691]='Deja dans le domaine'
	    try:
	        msgerr = dicterr[ret]
	    except:
	        msgerr = ''
	    raise pywintypes.error(ret, 'NetJoinDomain', 'Impossible de joindre le domaine ' + dom +  '\n' + msgerr)
	return ret
Esempio n. 27
0
  def _iterate(self):
    events, timeout = self._context.query()

    events = list(events)
    if timeout == sys.maxint:
      timeout = INFINITE

    if events:
      rc = WaitForMultipleObjects(events, False, timeout)
      if rc == WAIT_FAILED:
        raise pywintypes.error(GetLastError(), "WaitForMultipleObjects")
      # else: # WAIT_TIMEOUT or WAIT_OBJECT_0+i
    else:
      Sleep(timeout)

    self._context.check_and_dispatch()
Esempio n. 28
0
    def test_must_return_false_if_ping_raises_pywintypes_error(self):
        with patch.dict("sys.modules", patched_modules()):
            import samcli.local.docker.manager as manager_module
            import samcli.local.docker.utils as docker_utils

            importlib.reload(manager_module)
            importlib.reload(docker_utils)
            manager = manager_module.ContainerManager(
                docker_client=self.docker_client_mock)
            import pywintypes  # pylint: disable=import-error

            self.ping_mock.side_effect = pywintypes.error("pywintypes.error")
            is_reachable = manager.is_docker_reachable
            self.assertFalse(is_reachable)

        # reload modules to ensure platform.system() is unpatched
        importlib.reload(manager_module)
Esempio n. 29
0
def GetProcessId(handle):
    """Get the process id, given the process handle.
    """

    from win32api import GetLastError, FormatMessage
    from pywintypes import error, HANDLE
    from ctypes import windll, c_uint
    
    handle = c_uint(handle)
    _GetProcessId = windll.kernel32.GetProcessId
    pid = _GetProcessId(handle)

    if not pid:
        err = GetLastError()
        errmsg = FormatMessage(err)
        raise error(err, "GetProcessId", errmsg)

    return pid
 def _set_windows_handler():
     try:
         handler_windows = logging.handlers.NTEventLogHandler(
             app, dllname=None, logtype='Application')
         handler_windows.setFormatter(formatter)
         _add_log_handler(handler_windows)
     except pywintypes.error, e:
         if 'RegSetValueEx' in str(e):
             e = ("Error A write error has occurred " + 
                  "attempting to write Event Viewer (Windows Application log) " + 
                  "entry to registry. " + 
                  "This can happen if the application using the verbose " + 
                  "logger is running as a user that does not have " + 
                  "permissions. Try running the application as a specific " + 
                  "user, as system, or as Administrator."  + str(e) )
             raise pywintypes.error(e)
         else:
             raise
Esempio n. 31
0
def CreateRemoteThread(hProcess, pfn, param):
    from win32api import GetLastError, FormatMessage
    from pywintypes import error, HANDLE
    from ctypes import windll, c_uint, c_void_p
    
    
    _CreateRemoteThread = windll.kernel32.CreateRemoteThread
    hProcess = c_uint(hProcess.handle) # XXX
    param = c_void_p(param)
    pfn = c_void_p(pfn) # XXX

    hThread = _CreateRemoteThread(hProcess, c_void_p(), c_uint(0),
                                  pfn, param, c_uint(0), c_void_p())

    if not hThread:
        err = GetLastError()
        errmsg = FormatMessage(err)
        raise error(err, "CreateRemoteThread", errmsg)

    return HANDLE(hThread)
Esempio n. 32
0
def test_critical_query(aggregator, dd_run_check, mock_performance_objects, mocker, caplog):
    import pywintypes

    mock_performance_objects({'Foo': (['baz'], {'Bar': [9000]})})
    mocker.patch('win32pdh.CollectQueryData', side_effect=pywintypes.error(None, None, 'foo failed'))
    check = get_check({'metrics': {'Foo': {'name': 'foo', 'counters': [{'Bar': 'bar'}]}}})
    dd_run_check(check)

    aggregator.assert_all_metrics_covered()

    expected_message = 'Error querying performance counters: foo failed'
    aggregator.assert_service_check(
        'test.windows.perf.health', ServiceCheck.CRITICAL, message=expected_message, tags=GLOBAL_TAGS
    )

    for _, level, message in caplog.record_tuples:
        if level == logging.ERROR and message == expected_message:
            break
    else:
        raise AssertionError('Expected ERROR log with message `{}`'.format(expected_message))
Esempio n. 33
0
def test_counters_refresh(aggregator, dd_run_check, mock_performance_objects, mocker, caplog):
    import pywintypes

    error_data = (None, None, 'foo failed')
    mock_performance_objects({'Foo': (['baz'], {'Bar': [9000]})})
    mocker.patch(
        'datadog_checks.base.checks.windows.perf_counters.counter.PerfObject.refresh',
        side_effect=pywintypes.error(*error_data),
    )
    check = get_check({'metrics': {'Foo': {'name': 'foo', 'counters': [{'Bar': 'bar'}]}}})
    dd_run_check(check)

    aggregator.assert_all_metrics_covered()
    aggregator.assert_service_check('test.windows.perf.health', ServiceCheck.OK, tags=GLOBAL_TAGS)

    expected_message = 'Error refreshing counters for performance object `Foo`: {}'.format(error_data)
    for _, level, message in caplog.record_tuples:
        if level == logging.ERROR and message == expected_message:
            break
    else:
        raise AssertionError('Expected ERROR log with message `{}`'.format(expected_message))
Esempio n. 34
0
def create_file(
    path,
    desired_access,
    share_mode,
    sddl,
    creation_disposition,
    flags_and_attributes,
    zero=0,
    raise_last_error=False,
):
    # Create security attributes
    assert zero == 0
    security_attributes = win32security.SECURITY_ATTRIBUTES()
    security_attributes.bInheritHandle = 0
    if sddl:
        security_attributes.SECURITY_DESCRIPTOR = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
            sddl, win32security.SDDL_REVISION_1,
        )

    # Windows API call
    handle = win32file.CreateFile(
        path,
        desired_access,
        share_mode,
        security_attributes,
        creation_disposition,
        flags_and_attributes,
        0,
    )

    # Close the handle
    # This is necessary since we use a single process
    # for running all the commands from a single test case
    assert handle != win32file.INVALID_HANDLE_VALUE
    win32file.CloseHandle(handle)

    # Used when the command is prepended with `-e`
    if raise_last_error:
        raise pywintypes.error(win32api.GetLastError(), "CreateFileW", None)
Esempio n. 35
0
def __StopServiceWithTimeout(hs, waitSecs=30):
    try:
        status = win32service.ControlService(hs,
                                             win32service.SERVICE_CONTROL_STOP)
    except pywintypes.error, exc:
        if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
            raise
    for i in range(waitSecs):
        status = win32service.QueryServiceStatus(hs)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        win32api.Sleep(1000)
    else:
        raise pywintypes.error(
            winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService",
            win32api.FormatMessage(
                winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])


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:
Esempio n. 36
0
 def test_fail__get_event_handler(self):
     with patch.object(win32evtlog, 'OpenEventLog', side_effect=pywintypes.error()) as open_event_log:
         open_event_log.called_once_with("System", None)
         self.assertRaises(FileNotFoundError, win_event_viewer._get_event_handler, "System")
Esempio n. 37
0
def SetEndOfFile(handle):
    res = win32file.SetEndOfFile(handle)

    if not res:
        raise pywintypes.error(win32api.GetLastError(), "SetEndOfFile")
Esempio n. 38
0
def SetEndOfFile(handle):
    res = win32file.SetEndOfFile(handle)

    if not res:
        raise pywintypes.error(win32api.GetLastError(), "SetEndOfFile")
Esempio n. 39
0
	def __freeDataInWinamp(self, addr):
		rc = windll.kernel32.VirtualFreeEx(self.__hProcess, addr, 0, win32con.MEM_RELEASE)
		if not rc:
			raise pywintypes.error(GetLastError(), "VirtualFreeEx")
Esempio n. 40
0
def WSAEnumNetworkEvents(fd, event):
  net_events = WSANETWORKEVENTS()
  rc = windll.ws2_32.WSAEnumNetworkEvents(fd, event.handle, byref(net_events))
  if rc == SOCKET_ERROR:
    raise pywintypes.error(WSAGetLastError(), "WSAEnumNetworkEvents")
  return net_events
Esempio n. 41
0
def _error(routine):
    # internal helper
    err = GetLastError()
    errmsg = FormatMessage(err)
    raise error(err, routine, errmsg)
    else:
        raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "QueryServiceStatus", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
    
def __StopServiceWithTimeout(hs, waitSecs = 30):
    try:
        status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP)
    except pywintypes.error, exc:
        if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE:
            raise
    for i in range(waitSecs):
        status = win32service.QueryServiceStatus(hs)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        win32api.Sleep(1000)
    else:
        raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])


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)