converting python 2 to python 3('PROCESS_ALL_ACCESS' is not defined) - python-3.x

Here is my code that isn't working.
I do not know how to define it?
('PROCESS_ALL_ACCESS' is not defined)
import sys
from ctypes import *
PAGE_READWRITE = 0x04
PROCESS_ALL_ACCES = ( 0x000F0000 | 0x00100000 | 0xFFF )
VIRTUAL_MEM = ( 0x1000 | 0x2000 )
kernel32 = windll.kernel32
pid = sys.argv[0]
dll_path = sys.argv[1:]
dll_len = len(dll_path)
# Get a handle to the process we are injecting into.
h_process = kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, int(pid) )
if not h_process:
print("[*] Couldn't acquire a handle to PID: %s") % pid
sys.exit(0)
# Allocate some space for the DLL path
arg_address = kernel32.VirtualAllocEx(h_process, 0, dll_len, VIRTUAL_MEM,
PAGE_READWRITE)
# Write the DLL path into the allocated space
written = c_int(0)
kernel32.WriteProcessMemory(h_process, arg_address, dll_path, dll_len,
byref(written))
# We need to resolve the address for LoadLibraryA
h_kernel32 = kernel32.GetModuleHandleA("kernel32.dll")
h_loadlib = kernel32.GetProcAddress(h_kernel32, "LoadLibraryA")
# Now we try to create the remote thread, with the entry point set
# to LoadLibraryA and a pointer to DLL path as its single parameter
thread_id = c_ulong(0)
if not kerel32.CreateRemoteThread(h_process,
None,
0,
h_loadlib,
arg_address,
0,
byref(thread_id)):
print("[*] Failed to inject the DLL. Exiting.")
sys.exit(0)
print("[*] Temote thread with ID 0x%08x created.") % thread_id.value
I Keep on getting this error 'PROCESS_ALL_ACCESS'
in alot of my code i'm converting from "Gray Hat Python"
File "C:\Python\Python36-32\dll_injector.py", line 14, in <module>
h_process = kernel32.OpenProcess( PROCESS_ALL_ACCESS, False, int(pid) )
NameError: name 'PROCESS_ALL_ACCESS' is not defined

I don't know if you're still trying to solve this, but you have a spelling error.
In your 5th line, you have this:
PROCESS_ALL_ACCES = ( 0x000F0000 | 0x00100000 | 0xFFF )
You're missing an S

Related

Python ctypes EnumThreadWindows failing with error 87 (ERROR_INVALID_PARAMETER)

I can't seem to get EnumThreadWindows to work. It keeps failing with error 87. Code:
error = ctypes.WinDLL('Kernel32').GetLastError
enum_func = ctypes.WINFUNCTYPE(wintypes.BOOL,
wintypes.HWND,
wintypes.LPARAM)
def callback(hwnd, lParam):
length = ctypes.WinDLL('User32').GetWindowTextLengthW(hwnd) + 1
buf = ctypes.create_unicode_buffer(length)
ctypes.WinDLL('User32').GetWindowTextW(hwnd, buf, length)
print(buf.value)
worker = enum_func(callback)
test = ctypes.WinDLL('User32').EnumThreadWindows(6000, worker, None)
print(error(test))
I've tried pid = wintypes.DWORD(6000), test = ctypes.WinDLL('User32').EnumThreadWindows(pid.value, worker, None) to no avail.
What am I doing wrong?
Here's working code. Make sure to pass a valid thread ID.
You might be interested in the fact that an LPARAM can be anything, including a python object, so if you pass a Python object it can be manipulated in the callback:
import ctypes
from ctypes import wintypes
from collections import namedtuple
Window = namedtuple('Window','hwnd title')
WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL,
wintypes.HWND,
ctypes.py_object) # to allow any Python object.
u32 = ctypes.WinDLL('user32',use_last_error=True) # to ensure GetLastError was captured
# Declaring arguments and return type helps catch errors and support 64-bit.
# HWND is 64-bit on 64-bit Python, and could get truncated if left to ctypes default
# of c_int (32-bit). This code works on Python 2.7 and 3.9.
u32.GetWindowTextLengthW.argtypes = wintypes.HWND,
u32.GetWindowTextLengthW.restype = ctypes.c_int
u32.GetWindowTextW.argtypes = wintypes.HWND,wintypes.LPWSTR,ctypes.c_int
u32.GetWindowTextW.restype = ctypes.c_int
u32.EnumThreadWindows.argtypes = wintypes.DWORD,WNDENUMPROC,ctypes.py_object # to pass Python object
u32.EnumThreadWindows.restype = wintypes.BOOL
#WNDENUMPROC # decorator makes this a ctypes-compatible function
def callback(hwnd, lParam):
length = u32.GetWindowTextLengthW(hwnd) + 1
buf = ctypes.create_unicode_buffer(length)
u32.GetWindowTextW(hwnd, buf, length)
lParam.append(Window(hwnd,buf.value)) # append data to the callback parameter
return True # return True to continue enumeration
result = [] # A python object
if u32.EnumThreadWindows(6332, callback, result): # 6332 was a thread in my explore.exe
for wnd in result: # list results when enumeration complete
print(wnd)
else:
print('error:',ctypes.get_last_error()) # print error of EnumThreadWindows.
# Python could use a Win32 function that fails in
# between the ctypes call and calling GetLastError
# directly.
Output:
Window(hwnd=65832, title='')
Window(hwnd=65838, title='')
Window(hwnd=131174, title='')
Window(hwnd=65682, title='')
Window(hwnd=65678, title='')
Window(hwnd=65826, title='Program Manager')
Window(hwnd=196928, title='MSCTFIME UI')
Window(hwnd=65680, title='Default IME')

XGetWindowProperty and ctypes

Question
I'm trying to find NET_WM_NAME property for each of the window/client that X11 reports. Problem is that there's nothing returned - number of items is 0 and returned data results in empty string. I've looked at multiple code examples through out github and examples written in C and C++ , specifically Why is XGetWindowProperty returning null? as well as Xlib XGetWindowProperty Zero items returned , however I cannot find where is the problem with my code. Seemingly everything is fine, order of parameters passed to XGetWindowProperty function is in accordance with documentation, and the function returns success status, but results are empty. Where is the problem with my code ?
Code
Below is the code I am working with. The issue is xgetwindowproperty function. The other parts below it work fine, and are provided only for completeness.
#! /usr/bin/env python3
import sys
from ctypes import *
def xgetwindowproperty(display,w):
actual_type_return = c_ulong()
actual_format_return = c_int()
nitems_return = c_ulong()
bytes_after_return = c_ulong()
prop_return = POINTER(c_ubyte)()
wm_name = Xlib.XInternAtom(display,'_NET_WM_NAME',False)
utf8atom = Xlib.XInternAtom(display,'UTF8_STRING',False)
print('_NET_WM_NAME',wm_name, 'UTF8_STRING',utf8atom)
# AnyPropertyType = c_long(0)
status = Xlib.XGetWindowProperty(
display,
w,
wm_name,
0,
65536,
False,
utf8atom,
byref(actual_type_return),
byref(actual_format_return),
byref(nitems_return),
byref(bytes_after_return),
byref(prop_return)
)
print(nitems_return.value) # returns 0
# empty string as result
print( 'Prop', ''.join([ chr(c) for c in prop_return[:bytes_after_return.value] ]) )
Xlib.XFree(prop_return)
print('#'*10)
# -------
Xlib = CDLL("libX11.so.6")
display = Xlib.XOpenDisplay(None)
if display == 0:
sys.exit(2)
w = Xlib.XRootWindow(display, c_int(0))
root = c_ulong()
children = POINTER(c_ulong)()
parent = c_ulong()
nchildren = c_uint()
Xlib.XQueryTree(display, w, byref(root), byref(parent), byref(children), byref(nchildren))
for i in range(nchildren.value):
print("Child:",children[i])
xgetwindowproperty(display,children[i])

how to get data out of voidptr with Python 3.6.3

Hello my Problem is to get my data out of an sip.voidptr.
Before I used Python 2.7 and this code:
def winEvent(self, message):
WM_COPYDATA = 0x004A
if message.message == WM_COPYDATA:
if sys.version.find("64 bit") != -1:
structure = ctypes.string_at( message.lParam, 24 )
data = struct.unpack("QQP", structure)
unused, str_len, str_adr = data
my_string = ctypes.string_at( str_adr, str_len )
Now I use Python 3 and had changed from "winevent" to "event_Type".
Does anybody have an idea or an example how to get the data out of the sip.voidptr?
The error massage i get is:
File "C:\OSGEO4~1\apps\Python36\lib\ctypes\__init__.py", line 488, in string_at
return _string_at(ptr, size)
OSError: exception: access violation reading 0x0000000000000001
and before I get as my_string:
Name ID
1 1_2
2 1_3
3 1_4
4 1_5

Can't receive the data from device RFB2000 in python

I am using the module "ctypes" to load RFBClient.dll,I use windll and the convention is stdcall. I want to remote control the device RFB2000 with these commands below:
first step for connection
All the commands
for my programme, the connection is successful but the problem is that i can't recieve the data, when I want to get temperature value, I call the function but it always returns 0, the restype is c_double and the argtypes is none, I can't see there is any problem. English is not my native language; please excuse typing errors.
import ctypes
import time
libc = ctypes.WinDLL("X:\\RFBClient.dll")
#connect to RFB software
libc.OpenRFBConnection(ctypes.c_char_p('127.0.0.1'.encode('UTF-8')))
#check if connection successful
libc.Connected()
#Set parameters
#num_automeas = 1; %Number of auto-measurement runs.
completion_count = 2; #% Number of On-Off pairs within each auto-measurement run.
OnHalfCycleTimeCount = 40; # set 2s on
OffHalfCycleTimeCount = 40; # set 2s off
Data=[]
libc.SetCompletionCount(completion_count)
libc.SetMeasureUntilCount(completion_count)
libc.SetOnHalfCycleCount(OnHalfCycleTimeCount)
libc.SetOffHalfCycleCount(OffHalfCycleTimeCount)
libc.NewAutoMeasurement()
#zeroing
time.sleep(1)
print("zeroing.....")
libc.Zero()
while libc.Zeroing()== -1:
time.sleep(1)
#libc.CheckingSensor()
print("measurement start")
libc.StartMeas()
time.sleep(0.5)
while libc.Measuring() == -1:
time.sleep(1)
print(libc.Measuring())
getTemperature = libc.GetTemperature
getTemperature.restype = ctypes.c_double
getTemperature.argtypes = []
print(getTemperature())

(WinApi) ChangeDisplaySettingsEx does not work

I'm trying to write a python script to switch the primary monitor.
I have 3 Monitors (one is plugged into my i5's graphics chip, and 2 are plugged into a ATI HD7870)
I wrote the following script:
import win32api as w
import win32con as c
i = 0
workingDevices = []
def setPrimary(id):
global workingDevices
return w.ChangeDisplaySettingsEx(
workingDevices[id].DeviceName,
w.EnumDisplaySettings(
workingDevices[id].DeviceName,
c.ENUM_CURRENT_SETTINGS
),
c.CDS_SET_PRIMARY | c.CDS_UPDATEREGISTRY | c.CDS_RESET) \
== c.DISP_CHANGE_SUCCESSFUL
while True:
try:
Device = w.EnumDisplayDevices(None, i, 1)
if Device.StateFlags & c.DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: #Attached to desktop
workingDevices.append(Device)
i += 1
except:
break
print("Num Devices: ", len(workingDevices))
for dev in workingDevices:
print("Name: ", dev.DeviceName)
Invoking it leads to:
In [192]: %run test.py
Num Devices: 3
Name: \\.\DISPLAY1
Name: \\.\DISPLAY2
Name: \\.\DISPLAY7
In [193]: setPrimary(0)
Out[193]: True
In [194]: setPrimary(1)
Out[194]: True
In [195]: setPrimary(2)
Out[195]: True
So far it looks great, but the problem is: nothing changes. My monitors flicker shortly because of the CDS_RESET but the primary screen does not change, although ChangeDisplaySettingsEx returns DISP_CHANGE_SUCCESSFUL
Does anyone have an Idea why?
(I use Python 3.5.1 and PyWin32 build 220)
PS I use 1 as the third arg for EnumDisplayDevices because the msdn states it should be set to one, although the PyWin help says it should be set to 0.
But the behaviour of the script does not change independent of this value beeing one or zero
Ok, I found the solution.
Apperantly the primary monitor must always be at position (0, 0).
So when I tried to set another monitor to primary its position was set to (0, 0) which caused it to intersect with the old primary one.
It seems the way to go is to update the positions of all Monitors, and write those changes to the registry, and then once this is done apply the changes by calling ChangeDisplaySettingsEx() with default parameters.
This is my new (now working) code:
import win32api as w
import win32con as c
def load_device_list():
"""loads all Monitor which are plugged into the pc
The list is needed to use setPrimary
"""
workingDevices = []
i = 0
while True:
try:
Device = w.EnumDisplayDevices(None, i, 0)
if Device.StateFlags & c.DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: #Attached to desktop
workingDevices.append(Device)
i += 1
except:
return workingDevices
def setPrimary(id, workingDevices, MonitorPositions):
"""
param id: index in the workingDevices list.
Designates which display should be the new primary one
param workingDevices: List of Monitors returned by load_device_list()
param MonitorPositions: dictionary of form {id: (x_position, y_position)}
specifies the monitor positions
"""
FlagForPrimary = c.CDS_SET_PRIMARY | c.CDS_UPDATEREGISTRY | c.CDS_NORESET
FlagForSec = c.CDS_UPDATEREGISTRY | c.CDS_NORESET
offset_X = - MonitorPositions[id][0]
offset_Y = - MonitorPositions[id][1]
numDevs = len(workingDevices)
#get devmodes, correct positions, and update registry
for i in range(numDevs):
devmode = w.EnumDisplaySettings(workingDevices[i].DeviceName, c.ENUM_CURRENT_SETTINGS)
devmode.Position_x = MonitorPositions[i][0] + offset_X
devmode.Position_y = MonitorPositions[i][1] + offset_Y
if(w.ChangeDisplaySettingsEx(workingDevices[i].DeviceName, devmode,
FlagForSec if i != id else FlagForPrimary) \
!= c.DISP_CHANGE_SUCCESSFUL): return False
#apply Registry updates once all settings are complete
return w.ChangeDisplaySettingsEx() == c.DISP_CHANGE_SUCCESSFUL;
if(__name__ == "__main__"):
devices = load_device_list()
for dev in devices:
print("Name: ", dev.DeviceName)
MonitorPositions = {
0: (0, -1080),
1: (0, 0),
2: (1920, 0)
}
setPrimary(0, devices, MonitorPositions)

Resources