0

Предположим мне известен PID процесса, как мне получить путь вида \Device\HarddiskVolumeX\...\application.exe зная этот PID?

3 ответа 3

1

Добиться желаемого в Windows (без использования сторонних модулей) можно несколькими способами, идеологически правильным из которых считается использование функции QueryFullProcessImageName. Последняя является оберткой над NTAPI'шной функцией NtQueryInformationProcess. Помимо прочего можно воспользоваться услугами NtQuerySystemInformation. Если облачить всё вышесказанное в код "на коленке":

from ctypes import (
   POINTER, Structure, addressof, byref, cast, create_unicode_buffer, c_long,
   c_ulong, c_ushort, c_void_p, c_wchar_p, sizeof, windll
)

ProcessImageFileName       = 27
SystemProcessIdInformation = 88
# пример "на коленке", так что restype и argtypes не заданы
CloseHandle               = windll.kernel32.CloseHandle
OpenProcess               = windll.kernel32.OpenProcess
NtQueryInformationProcess = windll.ntdll.NtQueryInformationProcess
NtQuerySystemInformation  = windll.ntdll.NtQuerySystemInformation
QueryFullProcessImageName = windll.kernel32.QueryFullProcessImageNameW

class UNICODE_STRING(Structure):
   _fields_ = (
      ('Length', c_ushort),
      ('MaximumLength', c_ushort),
      ('Buffer', c_wchar_p),
   )

class SYSTEM_PROCESS_ID_INFORMATION(Structure):
   _fields_ = (
      ('ProcessId', c_void_p),
      ('ImageName', UNICODE_STRING),
   )

def getexepath_1(pid):
   buf  = create_unicode_buffer(0x100)
   spii = SYSTEM_PROCESS_ID_INFORMATION()
   spii.ProcessId = c_void_p(pid)
   spii.ImageName.MaximumLength = len(buf)
   spii.ImageName.Buffer = addressof(buf)
   nts  = NtQuerySystemInformation(SystemProcessIdInformation, spii, sizeof(spii), None)
   return buf.value if 0 == nts else 'n/a'

def getexepath_2(hndl):
   buf = create_unicode_buffer(0x100)
   req = c_ulong(len(buf))
   return buf.value if QueryFullProcessImageName(hndl, 1, buf, byref(req)) else 'n/a'

def getexepath_3(hndl):
   req = c_ulong()
   nts = NtQueryInformationProcess(hndl, ProcessImageFileName, None, None, byref(req))
   if c_long(0xC0000004).value != nts:
      return 'n/a'
   buf = create_unicode_buffer(req.value)
   nts = NtQueryInformationProcess(hndl, ProcessImageFileName, buf, len(buf), None)
   if 0 != nts:
      return 'n/a'
   return cast(buf, POINTER(UNICODE_STRING)).contents.Buffer

if __name__ == '__main__':
   print(getexepath_1(2032)) # какой-нибудь Id
   hndl = None
   try:
      hndl = OpenProcess(0x1000, False, 2032)
      print(getexepath_2(hndl))
      print(getexepath_3(hndl))
   except Exception as e:
      print(e)
   finally:
      if not CloseHandle(hndl):
         print('Опаньки!')
0
import psutil

print(psutil.Process(PID).exe())

Создаётся объект класса Process на основе PID, далее с помощью метода exe() можно получить его исполняемый файл.

0
import psutil
for proc in psutil.process_iter ():
    try:
        if proc.pid == 1560:
            print (f'{proc.exe ()}')
    except psutil.AccessDenied:
        print ('(You do not have access to this process)')

примерно так, взял фрагмент кода с буржуйского сайта UPD: поправил код - проверил - показывает полный путь

1
  • cwd() возвращает путь до текущей директории, а не исполняемого файла. И на всякий случай - гораздо эффективнее сделать psutil.Process(PID).method() # получить процесс по PID, тоже самое получение процесса (как у вас в цикле), но эффективнее
    – Стас
    21 сен 2020 в 14:52

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.