def StopDependentServices(self): # Pass a zero-length buffer to get the required buffer size. dwBytesNeeded = DWORD() dwCount = DWORD() if EnumDependentServices( self.schService, SERVICE_ACTIVE, None, 0, byref(dwBytesNeeded), byref(dwCount) ): # If the Enum call succeeds, then there are no dependent # services, so do nothing. return True if GetLastError() != ERROR_MORE_DATA: return False # Unexpected error # Allocate a buffer for the dependencies. lpDependencies = cast( HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, dwBytesNeeded ), LPENUM_SERVICE_STATUS ) if not lpDependencies: return False for i in range(dwCount): #ess = *(lpDependencies + i) # Open the service. hDepService = OpenService( self.schSCManager, ess.lpServiceName, SERVICE_STOP | SERVICE_QUERY_STATUS ) if not hDepService: return False try: # Send a stop code. if not ControlService( hDepService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS) &ssp ): return False # Wait for the service to stop. while ssStatus.dwCurrentState != SERVICE_STOPPED: Sleep(ssStatus.dwWaitHint) ssStatus = self.GetStatus() if ssStatus.dwCurrentState == SERVICE_STOPPED: break if GetTickCount() - dwStartTime > dwTimeout: return False finally: # Always release the service handle. CloseServiceHandle(hDepService) return True
def GetUncPathOf(filePath): buf = create_string_buffer(1024) dwBufSize = DWORD(1024) err = WNetGetUniversalName(filePath, UNIVERSAL_NAME_INFO_LEVEL, buf, byref(dwBufSize)) if err == 0: return cast(buf, POINTER(UNIVERSAL_NAME_INFO)).contents.lpUniversalName elif err == ERROR_NOT_CONNECTED: pass else: print "GetUncPathOf Error:", err, FormatError(err) return filePath
def GetStatus(self): dwBytesNeeded = DWORD() result = QueryServiceStatusEx( self.schService, # handle to service SC_STATUS_PROCESS_INFO, # information level cast(byref(self.ssStatus), LPBYTE), # address of structure sizeof(self.ssStatus), # size of structure byref(dwBytesNeeded) # size needed if buffer is too small ) if not result: raise WinError() return self.ssStatus
def GetClipboardText(): if not SafeOpenClipboard(): return text = u"" try: hClipMem = GetClipboardData(CF_UNICODETEXT) if hClipMem: text = cast(GlobalLock(hClipMem), c_wchar_p).value GlobalUnlock(hClipMem) else: hClipMem = GetClipboardData(CF_TEXT) if hClipMem: text = cast(GlobalLock(hClipMem), c_char_p).value GlobalUnlock(hClipMem) text = text.decode(eg.systemEncoding) finally: CloseClipboard() # replace CR+LF with \n text = text.replace("\r\n", "\n") return text
def Stop(self): """ Stops the service. """ self.GetServiceHandle() # Make sure the service is not already stopped. ssStatus = self.GetStatus() if ssStatus.dwCurrentState == SERVICE_STOPPED: return # If a stop is pending, wait for it. dwStartTime = GetTickCount() dwTimeout = 30000 while ssStatus.dwCurrentState == SERVICE_STOP_PENDING: # Do not wait longer than the wait hint. A good interval is # one-tenth of the wait hint but not less than 1 second # and not more than 10 seconds. Sleep(min(max(1000, ssStatus.dwWaitHint / 10), 10000)) ssStatus = self.GetStatus() if ssStatus.dwCurrentState == SERVICE_STOPPED: return if GetTickCount() - dwStartTime > dwTimeout: raise TimeOutError() # If the service is running, dependencies must be stopped first. #self.StopDependentServices() # Send a stop code to the service. if not ControlService( self.schService, SERVICE_CONTROL_STOP, cast(byref(ssStatus), LPSERVICE_STATUS) ): raise WinError() # Wait for the service to stop. while ssStatus.dwCurrentState != SERVICE_STOPPED: Sleep(ssStatus.dwWaitHint) ssStatus = self.GetStatus() if ssStatus.dwCurrentState == SERVICE_STOPPED: break if GetTickCount() - dwStartTime > dwTimeout: raise TimeOutError()
def GetComPorts(availableOnly=True): """ Scans the registry for serial ports and return a list of (port, desc, hwid) tuples. If availableOnly is true only return currently existing ports. """ result = [] stringBuffer = create_unicode_buffer(256) flags = DIGCF_DEVICEINTERFACE if availableOnly: flags |= DIGCF_PRESENT hdi = SetupDiGetClassDevs(byref(GUID_CLASS_COMPORT), None, 0, flags) if hdi == INVALID_HANDLE_VALUE: raise WinError() dwRequiredSize = DWORD() dwIndex = 0 while True: did = SP_DEVICE_INTERFACE_DATA() did.cbSize = sizeof(did) if not SetupDiEnumDeviceInterfaces( hdi, None, byref(GUID_CLASS_COMPORT), dwIndex, byref(did) ): err = GetLastError() if err != ERROR_NO_MORE_ITEMS: raise WinError(err) break # get the size if not SetupDiGetDeviceInterfaceDetail( hdi, byref(did), None, 0, byref(dwRequiredSize), None ): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) # allocate buffer class _SP_DEVICE_INTERFACE_DETAIL_DATA(Structure): _fields_ = [ ('cbSize', DWORD), ('DevicePath', TCHAR*(dwRequiredSize.value - sizeof(DWORD))), ] idd = _SP_DEVICE_INTERFACE_DETAIL_DATA() idd.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) devinfo = SP_DEVINFO_DATA() devinfo.cbSize = sizeof(devinfo) if not SetupDiGetDeviceInterfaceDetail( hdi, byref(did), cast(byref(idd), PSP_DEVICE_INTERFACE_DETAIL_DATA), dwRequiredSize, None, byref(devinfo) ): raise WinError() # hardware ID if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_HARDWAREID, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer)-1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) szHardwareID = stringBuffer.value # friendly name if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_FRIENDLYNAME, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer)-1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) szFriendlyName = stringBuffer.value portName = re.search(r"\((.*)\)", szFriendlyName).group(1) result.append((portName, szFriendlyName, szHardwareID)) dwIndex += 1 SetupDiDestroyDeviceInfoList(hdi) return result
def IsAdmin(): """ Find out if the user (the owner of the current process) is a member of the administrators group on the local computer (not on the domain!). """ # First we must open a handle to the access token for this thread. hThread = HANDLE() if not OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, 0, byref(hThread)): err = GetLastError() if err == ERROR_NO_TOKEN: # If the thread does not have an access token, we'll examine the # access token associated with the process. if not OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, byref(hThread)): raise WinError() else: raise WinError(err) # Then we must query the size of the group information associated with # the token. Note that we expect a FALSE result from GetTokenInformation # because we've given it a NULL buffer. On exit cbTokenGroups will tell # the size of the group information. cbTokenGroups = DWORD() if GetTokenInformation(hThread, TokenGroups, None, 0, byref(cbTokenGroups)): raise WinError() # Here we verify that GetTokenInformation failed for lack of a large # enough buffer. err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) # Now we allocate a buffer for the group information. ptg = create_string_buffer(cbTokenGroups.value) # Now we ask for the group information again. # This may fail if an administrator has added this account to an additional # group between our first call to GetTokenInformation and this one. if not GetTokenInformation(hThread, TokenGroups, ptg, cbTokenGroups, byref(cbTokenGroups)): raise WinError() # Now we must create a System Identifier for the Admin group. systemSidAuthority = SID_IDENTIFIER_AUTHORITY() systemSidAuthority.Value[5] = SECURITY_NT_AUTHORITY psidAdmin = PSID() if not AllocateAndInitializeSid( byref(systemSidAuthority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, byref(psidAdmin)): raise WinError() # Finally we'll iterate through the list of groups for this access # token looking for a match against the SID we created above. ptg = cast(ptg, POINTER(TOKEN_GROUPS)) groups = cast(ptg.contents.Groups, POINTER(SID_AND_ATTRIBUTES)) isAdmin = False for i in range(ptg.contents.GroupCount): if EqualSid(groups[i].Sid, psidAdmin.value): isAdmin = True break # Before we exit we must explicitly deallocate the SID we created. FreeSid(psidAdmin) return isAdmin
def GetComPorts(availableOnly=True): """ This generator scans the device registry for com ports and yields port, desc, hwid. If availableOnly is true only return currently existing ports. """ stringBuffer = ctypes.create_unicode_buffer(256) flags = DIGCF_DEVICEINTERFACE if availableOnly: flags |= DIGCF_PRESENT hdi = SetupDiGetClassDevs(byref(GUID_CLASS_COMPORT), None, NULL, flags) #~ for i in range(256): for dwIndex in range(256): did = SP_DEVICE_INTERFACE_DATA() did.cbSize = sizeof(did) if not SetupDiEnumDeviceInterfaces( hdi, None, byref(GUID_CLASS_COMPORT), dwIndex, byref(did) ): if ctypes.GetLastError() != ERROR_NO_MORE_ITEMS: raise ctypes.WinError() break dwNeeded = DWORD() # get the size if not SetupDiGetDeviceInterfaceDetail( hdi, byref(did), None, 0, byref(dwNeeded), None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() # allocate buffer class _SP_DEVICE_INTERFACE_DETAIL_DATA(ctypes.Structure): _fields_ = [ ('cbSize', DWORD), ('DevicePath', TCHAR*(dwNeeded.value - sizeof(DWORD))), ] idd = _SP_DEVICE_INTERFACE_DETAIL_DATA() idd.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) devinfo = SP_DEVINFO_DATA() devinfo.cbSize = sizeof(devinfo) if not SetupDiGetDeviceInterfaceDetail( hdi, byref(did), cast(byref(idd), PSP_DEVICE_INTERFACE_DETAIL_DATA), dwNeeded, None, byref(devinfo) ): raise ctypes.WinError() #print idd.DevicePath, sizeof(idd) # hardware ID if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_HARDWAREID, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() szHardwareID = stringBuffer.value # friendly name #szFriendlyName = ctypes.create_string_buffer('\0' * 250) if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_FRIENDLYNAME, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer) - 1, None ): # Ignore ERROR_INSUFFICIENT_BUFFER if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise ctypes.WinError() szFriendlyName = stringBuffer.value portName = re.search(r"\((.*)\)", szFriendlyName).group(1) yield portName, szFriendlyName, szHardwareID SetupDiDestroyDeviceInfoList(hdi)
def GetComPorts(availableOnly=True): """ Scans the registry for serial ports and return a list of (port, desc, hwid) tuples. If availableOnly is true only return currently existing ports. """ result = [] stringBuffer = create_unicode_buffer(256) flags = DIGCF_DEVICEINTERFACE if availableOnly: flags |= DIGCF_PRESENT hdi = SetupDiGetClassDevs(byref(GUID_CLASS_COMPORT), None, 0, flags) if hdi == INVALID_HANDLE_VALUE: raise WinError() dwRequiredSize = DWORD() dwIndex = 0 while True: did = SP_DEVICE_INTERFACE_DATA() did.cbSize = sizeof(did) if not SetupDiEnumDeviceInterfaces( hdi, None, byref(GUID_CLASS_COMPORT), dwIndex, byref(did)): err = GetLastError() if err != ERROR_NO_MORE_ITEMS: raise WinError(err) break # get the size if not SetupDiGetDeviceInterfaceDetail(hdi, byref(did), None, 0, byref(dwRequiredSize), None): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) # allocate buffer class _SP_DEVICE_INTERFACE_DETAIL_DATA(Structure): _fields_ = [ ('cbSize', DWORD), ('DevicePath', TCHAR * (dwRequiredSize.value - sizeof(DWORD))), ] idd = _SP_DEVICE_INTERFACE_DETAIL_DATA() idd.cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA) devinfo = SP_DEVINFO_DATA() devinfo.cbSize = sizeof(devinfo) if not SetupDiGetDeviceInterfaceDetail( hdi, byref(did), cast(byref(idd), PSP_DEVICE_INTERFACE_DETAIL_DATA), dwRequiredSize, None, byref(devinfo)): raise WinError() # hardware ID if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_HARDWAREID, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer) - 1, None): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) szHardwareID = stringBuffer.value # friendly name if not SetupDiGetDeviceRegistryProperty( hdi, byref(devinfo), SPDRP_FRIENDLYNAME, None, cast(stringBuffer, PBYTE), sizeof(stringBuffer) - 1, None): # Ignore ERROR_INSUFFICIENT_BUFFER err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) szFriendlyName = stringBuffer.value portName = re.search(r"\((.*)\)", szFriendlyName).group(1) result.append((portName, szFriendlyName, szHardwareID)) dwIndex += 1 SetupDiDestroyDeviceInfoList(hdi) return result
def IsAdmin(): """ Find out if the user (the owner of the current process) is a member of the administrators group on the local computer (not on the domain!). """ # First we must open a handle to the access token for this thread. hThread = HANDLE() if not OpenThreadToken( GetCurrentThread(), TOKEN_QUERY, 0 , byref(hThread) ): err = GetLastError() if err == ERROR_NO_TOKEN: # If the thread does not have an access token, we'll examine the # access token associated with the process. if not OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, byref(hThread) ): raise WinError() else: raise WinError(err) # Then we must query the size of the group information associated with # the token. Note that we expect a FALSE result from GetTokenInformation # because we've given it a NULL buffer. On exit cbTokenGroups will tell # the size of the group information. cbTokenGroups = DWORD() if GetTokenInformation( hThread, TokenGroups, None, 0, byref(cbTokenGroups) ): raise WinError() # Here we verify that GetTokenInformation failed for lack of a large # enough buffer. err = GetLastError() if err != ERROR_INSUFFICIENT_BUFFER: raise WinError(err) # Now we allocate a buffer for the group information. ptg = create_string_buffer(cbTokenGroups.value) # Now we ask for the group information again. # This may fail if an administrator has added this account to an additional # group between our first call to GetTokenInformation and this one. if not GetTokenInformation( hThread, TokenGroups, ptg, cbTokenGroups, byref(cbTokenGroups) ): raise WinError() # Now we must create a System Identifier for the Admin group. systemSidAuthority = SID_IDENTIFIER_AUTHORITY() systemSidAuthority.Value[5] = SECURITY_NT_AUTHORITY psidAdmin = PSID() if not AllocateAndInitializeSid( byref(systemSidAuthority), 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, byref(psidAdmin) ): raise WinError() # Finally we'll iterate through the list of groups for this access # token looking for a match against the SID we created above. ptg = cast(ptg, POINTER(TOKEN_GROUPS)) groups = cast(ptg.contents.Groups, POINTER(SID_AND_ATTRIBUTES)) isAdmin = False for i in range(ptg.contents.GroupCount): if EqualSid(groups[i].Sid, psidAdmin.value): isAdmin = True break # Before we exit we must explicitly deallocate the SID we created. FreeSid(psidAdmin) return isAdmin