0

https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryinformationfile?redirectedfrom=MSDN

How can I call the above kernel method in python? I found an example on another stackoverflow post: Winapi: Get the process which has specific handle of a file

The answer on this other post is essentially what I want to do, but in python. The goal is to be able to get a list of processes which currently are accessing/locking a file. This NtQueryInformationFile method seems to be exactly what I want. I know this can be done with ctypes, but I am not familiar or comfortable enough with ctypes to do this myself. How can I do this?

Ryan Glenn
  • 1,325
  • 4
  • 17
  • 30

1 Answers1

0

If there's no available wrapper for the function, you'll need to call the function yourself using ctypes. The dlls windows uses are exposed through ctypes.windll, with cytpes.windll.ntdll being the one that exposes the function you need.

To help python convert arguments, it's usually a good idea to specify the function's argument and return types, which can be done through the argtypes and restype attributes on the function object, like so:

function = cytpes.windll.ntdll.NtQueryInformationFile
function.argtypes = [ctypes.wintypes.HANDLE, ...]
function.restype = ctypes.c_long

ctypes exposes the common window types in the ctypes.wintypes module, though for most structures like the PIO_STATUS_BLOCK in your function you'll need to define the struct yourself and add it to the argument list to use it properly. In case it's optional a void pointer and passing it None will suffice.

Also, do mind that windows handles are not the file descriptors that python exposes, to convert to/from them you can use the ..._osfhandle functions from the msvcrt module

Numerlor
  • 799
  • 1
  • 3
  • 16
  • Looks like it would also require me to run multiple other windows functions like NtOpenFile :( – Ryan Glenn Jan 10 '22 at 00:56
  • Does the function need some special handle? if it's an ordinary windows handle then you should be able to use a python file and a handle from it's file descriptor that you can get with the fileno method – Numerlor Jan 10 '22 at 01:00
  • I am not sure. I've been just doing some research into ctypes. – Ryan Glenn Jan 10 '22 at 01:02