def window__get_thread_window_handles(thread_process_id):
"""
:param thread_process_id: thread process ID, as from window__get_thread_process_id
:return: hwnd for all top-level windows with this thread process id.
"""
ret = []
def callback(hwnd, lparam):
ret.append(hwnd)
return True
enum_win_proc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int))
windll.user32.EnumThreadWindows(wintypes.DWORD(thread_process_id), enum_win_proc(callback), None)
return ret
python类DWORD的实例源码
def _wait_for_handles(handles, timeout=-1):
"""
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
"""
arrtype = HANDLE * len(handles)
handle_array = arrtype(*handles)
ret = windll.kernel32.WaitForMultipleObjects(
len(handle_array), handle_array, BOOL(False), DWORD(timeout))
if ret == WAIT_TIMEOUT:
return None
else:
h = handle_array[ret]
return h
def getvolumeinfo(path):
"""
Return information for the volume containing the given path. This is going
to be a pair containing (file system, file system flags).
"""
# Add 1 for a trailing backslash if necessary, and 1 for the terminating
# null character.
volpath = ctypes.create_unicode_buffer(len(path) + 2)
rv = GetVolumePathName(path, volpath, len(volpath))
if rv == 0:
raise WinError()
fsnamebuf = ctypes.create_unicode_buffer(MAX_PATH + 1)
fsflags = DWORD(0)
rv = GetVolumeInformation(volpath, None, 0, None, None, byref(fsflags),
fsnamebuf, len(fsnamebuf))
if rv == 0:
raise WinError()
return (fsnamebuf.value, fsflags.value)
def WlanOpenHandle():
"""
The WlanOpenHandle function opens a connection to the server.
DWORD WINAPI WlanOpenHandle(
_In_ DWORD dwClientVersion,
_Reserved_ PVOID pReserved,
_Out_ PDWORD pdwNegotiatedVersion,
_Out_ PHANDLE phClientHandle
);
"""
func_ref = wlanapi.WlanOpenHandle
func_ref.argtypes = [DWORD, c_void_p, POINTER(DWORD), POINTER(HANDLE)]
func_ref.restype = DWORD
negotiated_version = DWORD()
client_handle = HANDLE()
result = func_ref(2, None, byref(negotiated_version), byref(client_handle))
if result != ERROR_SUCCESS:
raise Exception("WlanOpenHandle failed.")
return client_handle
def WlanCloseHandle(hClientHandle):
"""
The WlanCloseHandle function closes a connection to the server.
DWORD WINAPI WlanCloseHandle(
_In_ HANDLE hClientHandle,
_Reserved_ PVOID pReserved
);
"""
func_ref = wlanapi.WlanCloseHandle
func_ref.argtypes = [HANDLE, c_void_p]
func_ref.restype = DWORD
result = func_ref(hClientHandle, None)
if result != ERROR_SUCCESS:
raise Exception("WlanCloseHandle failed.")
return result
def WlanEnumInterfaces(hClientHandle):
"""
The WlanEnumInterfaces function enumerates all of the wireless LAN
interfaces currently enabled on the local computer.
DWORD WINAPI WlanEnumInterfaces(
_In_ HANDLE hClientHandle,
_Reserved_ PVOID pReserved,
_Out_ PWLAN_INTERFACE_INFO_LIST *ppInterfaceList
);
"""
func_ref = wlanapi.WlanEnumInterfaces
func_ref.argtypes = [HANDLE,
c_void_p,
POINTER(POINTER(WLAN_INTERFACE_INFO_LIST))]
func_ref.restype = DWORD
wlan_ifaces = pointer(WLAN_INTERFACE_INFO_LIST())
result = func_ref(hClientHandle, None, byref(wlan_ifaces))
if result != ERROR_SUCCESS:
raise Exception("WlanEnumInterfaces failed.")
return wlan_ifaces
def WlanDeleteProfile(hClientHandle, pInterfaceGuid, profileName):
"""
DWORD WINAPI WlanDeleteProfile(
_In_ HANDLE hClientHandle,
_In_ const GUID *pInterfaceGuid,
_In_ LPCWSTR strProfileName,
_Reserved_ PVOID pReserved
);
"""
func_ref = wlanapi.WlanDeleteProfile
func_ref.argtypes = [HANDLE,
POINTER(GUID),
LPCWSTR,
c_void_p]
func_ref.restype = DWORD
result = func_ref(hClientHandle,
byref(pInterfaceGuid),
profileName,
None)
if result != ERROR_SUCCESS:
raise Exception("WlanDeleteProfile failed. error %d" % result, result)
return result
def WlanConnect(hClientHandle, pInterfaceGuid, pConnectionParameters):
"""
The WlanConnect function attempts to connect to a specific network.
DWORD WINAPI WlanConnect(
_In_ HANDLE hClientHandle,
_In_ const GUID *pInterfaceGuid,
_In_ const PWLAN_CONNECTION_PARAMETERS pConnectionParameters,
_Reserved_ PVOID pReserved
);
"""
func_ref = wlanapi.WlanConnect
func_ref.argtypes = [HANDLE,
POINTER(GUID),
POINTER(WLAN_CONNECTION_PARAMETERS),
c_void_p]
func_ref.restype = DWORD
result = func_ref(hClientHandle,
pointer(pInterfaceGuid),
pointer(pConnectionParameters),
None)
if result != ERROR_SUCCESS:
raise Exception("".join(["WlanConnect failed with error ", str(result)]))
return result
def process__get_exit_code(thread_pid):
"""
:param thread_pid:
:return: None if the process hasn't exited, or the int exit code.
"""
hproc = windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, False, thread_pid)
try:
exit_code = wintypes.DWORD()
if GetExitCodeProcess(hproc, byref(exit_code)) != 0:
if exit_code == STILL_ACTIVE:
return None
return int(exit_code)
raise WinError()
finally:
windll.kernel32.CloseHandle(hproc)
def areAdminRightsElevated():
'''
Tells you whether current script already has Administrative rights.
'''
pid = GetCurrentProcess()
processToken = HANDLE()
if not OpenProcessToken(pid, TOKEN_READ, ctypes.byref(processToken)):
raise ctypes.WinError()
try:
elevated, elevatedSize = DWORD(), DWORD()
if not GetTokenInformation(processToken, TokenElevation, ctypes.byref(elevated),
ctypes.sizeof(elevated), ctypes.byref(elevatedSize)):
raise ctypes.WinError()
return bool(elevated)
finally:
CloseHandle(processToken)
def areAdminRightsElevated():
'''
Tells you whether current script already has Administrative rights.
'''
pid = GetCurrentProcess()
processToken = HANDLE()
if not OpenProcessToken(pid, TOKEN_READ, ctypes.byref(processToken)):
raise ctypes.WinError()
try:
elevated, elevatedSize = DWORD(), DWORD()
if not GetTokenInformation(processToken, TokenElevation, ctypes.byref(elevated),
ctypes.sizeof(elevated), ctypes.byref(elevatedSize)):
raise ctypes.WinError()
return bool(elevated)
finally:
CloseHandle(processToken)
def _wait_for_handles(handles, timeout=-1):
"""
Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx
"""
arrtype = HANDLE * len(handles)
handle_array = arrtype(*handles)
ret = windll.kernel32.WaitForMultipleObjects(
len(handle_array), handle_array, BOOL(False), DWORD(timeout))
if ret == WAIT_TIMEOUT:
return None
else:
h = handle_array[ret]
return h
def CreateFile(path, access=GENERIC_READ | GENERIC_WRITE, mode=0, security_attributes=NULL, creation=OPEN_EXISTING, flags=FILE_ATTRIBUTE_NORMAL, template_file = NULL):
"""See: CreateFile function
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
"""
CreateFile_Fn = windll.kernel32.CreateFileA
CreateFile_Fn.argtypes = [
wintypes.LPCSTR, # _In_ LPCTSTR lpFileName
wintypes.DWORD, # _In_ DWORD dwDesiredAccess
wintypes.DWORD, # _In_ DWORD dwShareMode
LPSECURITY_ATTRIBUTES, # _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
wintypes.DWORD, # _In_ DWORD dwCreationDisposition
wintypes.DWORD, # _In_ DWORD dwFlagsAndAttributes
wintypes.HANDLE] # _In_opt_ HANDLE hTemplateFile
CreateFile_Fn.restype = wintypes.HANDLE
handle = wintypes.HANDLE(CreateFile_Fn(path,
access,
mode,
security_attributes,
creation,
flags,
template_file))
return handle
def WriteFile(file, buffer, number_of_bytes_to_write, number_of_bytes_written, overlapped):
"""See: WriteFile function
https://msdn.microsoft.com/en-us/library/windows/desktop/aa365747(v=vs.85).aspx
"""
WriteFile_Fn = windll.kernel32.WriteFile
WriteFile_Fn.argtypes = [
wintypes.HANDLE, # _In_ HANDLE hFile,
wintypes.LPCVOID, # _In_ LPCVOID lpBuffer,
wintypes.DWORD, # _In_ DWORD nNumberOfBytesToWrite,
LPDWORD, # _Out_opt_ LPDWORD lpNumberOfBytesWritten,
LPOVERLAPPED # _Inout_opt_ LPOVERLAPPED lpOverlapped
]
WriteFile_Fn.restype = wintypes.BOOL
ret = wintypes.BOOL(WriteFile_Fn(
file,
buffer,
number_of_bytes_to_write,
number_of_bytes_written,
overlapped
))
return ret
def open_device(self, access=GENERIC_READ | GENERIC_WRITE, mode=0, creation=OPEN_EXISTING, flags=FILE_ATTRIBUTE_NORMAL):
"""See: CreateFile function
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
"""
CreateFile_Fn = windll.kernel32.CreateFileA
CreateFile_Fn.argtypes = [
wintypes.LPCSTR, # _In_ LPCTSTR lpFileName
wintypes.DWORD, # _In_ DWORD dwDesiredAccess
wintypes.DWORD, # _In_ DWORD dwShareMode
LPSECURITY_ATTRIBUTES, # _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes
wintypes.DWORD, # _In_ DWORD dwCreationDisposition
wintypes.DWORD, # _In_ DWORD dwFlagsAndAttributes
wintypes.HANDLE] # _In_opt_ HANDLE hTemplateFile
CreateFile_Fn.restype = wintypes.HANDLE
self.handle = wintypes.HANDLE(CreateFile_Fn('\\\\.\\' + self.name,
access,
mode,
NULL,
creation,
flags,
NULL))
def open_service(service_manager_handle, service_name, desired_access):
""" See: OpenService function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms684330(v=vs.85).aspx
"""
OpenService_Fn = windll.Advapi32.OpenServiceA #SC_HANDLE WINAPI OpenService(
OpenService_Fn.argtypes = [ #
wintypes.HANDLE, # _In_ SC_HANDLE hSCManager,
LPCTSTR, # _In_ LPCTSTR lpServiceName,
wintypes.DWORD # _In_ DWORD dwDesiredAccess
]
OpenService_Fn.restype = wintypes.SC_HANDLE
handle = OpenService_Fn(
service_manager_handle,
service_name,
desired_access
)
return handle
def control_service(service_handle, control, service_status):
"""See: ControlService function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682108(v=vs.85).aspx
"""
ControlService_Fn = windll.Advapi32.ControlService #BOOL WINAPI ControlService(
ControlService_Fn.argtypes = [ #
wintypes.SC_HANDLE, # _In_ SC_HANDLE hService,
wintypes.DWORD, # _In_ DWORD dwControl,
wintypes.LPCVOID # _Out_ LPSERVICE_STATUS lpServiceStatus
]
ControlService_Fn.restype = wintypes.BOOL
bool = ControlService_Fn(
service_handle,
control,
service_status
)
return bool
def open_sc_manager(machine_name, database_name, desired_access):
"""See: OpenSCManager function
https://msdn.microsoft.com/en-us/library/windows/desktop/ms684323(v=vs.85).aspx
"""
OpenSCManager_Fn = windll.Advapi32.OpenSCManagerA #SC_HANDLE WINAPI OpenSCManager(
OpenSCManager_Fn.argtypes = [ #
LPCTSTR, # _In_opt_ LPCTSTR lpMachineName,
LPCTSTR, # _In_opt_ LPCTSTR lpDatabaseName,
wintypes.DWORD # _In_ DWORD dwDesiredAccess
]
OpenSCManager_Fn.restype = wintypes.SC_HANDLE
handle = OpenSCManager_Fn(
machine_name,
database_name,
desired_access
)
return handle
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start):
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
handle = handles[stream_id]
attribute = wintypes.WORD(attr)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
return _FillConsoleOutputAttribute(
handle, attribute, length, start, byref(num_written))
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char.encode())
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start):
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
handle = handles[stream_id]
attribute = wintypes.WORD(attr)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
return _FillConsoleOutputAttribute(
handle, attribute, length, start, byref(num_written))
def readlink(path):
# Make sure the path exists and is actually a junction
if not isjunction(path):
raise Exception("%s does not exist or is not a junction" % path)
hlink = CreateFile(path, fs.GENERIC_READ, fs.FILE_SHARE_READ, None,
fs.OPEN_EXISTING,
fs.FILE_FLAG_OPEN_REPARSE_POINT | fs.FILE_FLAG_BACKUP_SEMANTICS,
None)
if hlink == fs.INVALID_HANDLE_VALUE:
raise WinError()
try:
(junctioninfo, infolen) = new_junction_reparse_buffer()
dummy = DWORD(0)
res = DeviceIoControl(
hlink,
FSCTL_GET_REPARSE_POINT,
None,
0,
byref(junctioninfo),
infolen,
byref(dummy),
None)
if res == 0:
raise WinError()
return unparsed_unconvert(junctioninfo.SubstituteNameBuffer)
finally:
CloseHandle(hlink)
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start):
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
handle = handles[stream_id]
attribute = wintypes.WORD(attr)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
return _FillConsoleOutputAttribute(
handle, attribute, length, start, byref(num_written))
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start):
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
handle = handles[stream_id]
attribute = wintypes.WORD(attr)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
return _FillConsoleOutputAttribute(
handle, attribute, length, start, byref(num_written))
def WriteFile(handle, data, ol = None):
c_written = DWORD()
success = ctypes.windll.kernel32.WriteFile(handle, ctypes.create_string_buffer(encode(data)), len(data), ctypes.byref(c_written), ol)
return ctypes.windll.kernel32.GetLastError(), c_written.value
def ReadFile(handle, desired_bytes, ol = None):
c_read = DWORD()
buffer = ctypes.create_string_buffer(desired_bytes+1)
success = ctypes.windll.kernel32.ReadFile(handle, buffer, desired_bytes, ctypes.byref(c_read), ol)
buffer[c_read.value] = null_byte
return ctypes.windll.kernel32.GetLastError(), decode(buffer.value)
def PeekNamedPipe(handle, desired_bytes):
c_avail = DWORD()
c_message = DWORD()
if desired_bytes > 0:
c_read = DWORD()
buffer = ctypes.create_string_buffer(desired_bytes+1)
success = ctypes.windll.kernel32.PeekNamedPipe(handle, buffer, desired_bytes, ctypes.byref(c_read), ctypes.byref(c_avail), ctypes.byref(c_message))
buffer[c_read.value] = null_byte
return decode(buffer.value), c_avail.value, c_message.value
else:
success = ctypes.windll.kernel32.PeekNamedPipe(handle, None, desired_bytes, None, ctypes.byref(c_avail), ctypes.byref(c_message))
return "", c_avail.value, c_message.value