Имя пользователя, путь до exe + processID

Mr.Power

Всем доброго времени суток.1как можно определить имя пользователя исполняемого файла по processID?2как можно определить полный путь до EXE по processID?Заранее благодарен!=)))
24 ответа

Mr.Power

up ^?


Mr.Power

Mr.Power,1 (ACCESS = TOKEN_QUERY)2


Mr.Power

Бенедикт,Спасибо, проверим. А ты не смотрел в первом случае показываются все пользователи?Я нашёл несколько примеров, но они отдают только своего пользователа и Систем.Ж/


Mr.Power

Бенедикт,чёта не прёт както,1й.вот я немного переделал.
Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

Private Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long

Const TOKEN_DUPLICATE As Long = &H2
Const TOKEN_IMPERSONATE As Long = &H4
Const TOKEN_QUERY As Long = &H8

Private Declare Function OpenProcessToken Lib "advapi32" ( _
ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
TokenHandle As Long) As Long

Private Declare Function GetTokenInformation Lib "advapi32.dll" ( _
ByVal TokenHandle As Long, _
ByVal TokenInformationClass As Integer, _
TokenInformation As Any, _
ByVal TokenInformationLength As Long, _
ReturnLength As Long) As Long

Private Declare Function LookupAccountSid Lib "advapi32.dll" Alias "LookupAccountSidA" (ByVal lpSystemName As String, ByRef Sid As Any, ByVal name As String, ByRef cbName As Long, ByVal ReferencedDomainName As String, ByRef cbReferencedDomainName As Long, ByRef peUse As Long) As Long


Const TOKEN_USER = <b>1</b>
Const SPARE_LEN = <b>512</b>

Private Type SID_AND_ATTRIBUTES
Sid As Long
Attributes As Long
Spare(SPARE_LEN) As Byte
End Type

Private Function sDecodeTokenUser(hToken As Long) As String
' Returns the 'domain\user' owner of the specified access token
Dim lSidNameUse As Long
Dim sUser As String
Dim sDomain As String
Dim lUserLen As Long
Dim lDomainLen As Long
Dim tInfoStructure As SID_AND_ATTRIBUTES
Dim lInfoLen As Long

If GetTokenInformation(hToken, TOKEN_USER, tInfoStructure, _
SPARE_LEN + <b>4</b>, lInfoLen) = <b>0</b> Then

Else
sUser = String$(<b>100</b>, Chr$(<b>0</b>))
sDomain = String$(<b>100</b>, Chr$(<b>0</b>))
lUserLen = Len(sUser)
lDomainLen = Len(sDomain)

If LookupAccountSid(vbNullString, tInfoStructure.Sid, _
sUser, lUserLen, sDomain, lDomainLen, lSidNameUse) = <b>0</b> Then

Else
sUser = Left$(sUser, InStr(sUser, Chr$(<b>0</b>)) - <b>1</b>)
sDomain = Left$(sDomain, InStr(sDomain, Chr$(<b>0</b>)) - <b>1</b>)
sDecodeTokenUser = sDomain & "\" & sUser
End If
End If
End Function





Public Function getUSERbyPID(lPID As Long) As String
ACCESS = TOKEN_QUERY

 Dim hProcess As Long
 Dim hToken As Long
 Dim lStatus As Long

' Get a handle to the process whose ID is in lPID
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, False, lPID)


' Now get its primary access token
lStatus = OpenProcessToken(hProcess, ACCESS, hToken)


getUSERbyPID = sDecodeTokenUser(hToken)
CloseHandle hToken
CloseHandle hProcess

End Function
возвращается пустота, Чё делать


Mr.Power

OpenProcess(PROCESS_QUERY_INFORMATION, 0, lPID) возвращает 0


Mr.Power

> Автор: Mr.Power> OpenProcess(PROCESS_QUERY_INFORMATION, 0, lPID) возвращает 0И чего говорит GetLastError? ;)


Mr.Power

наверное ERROR_ACCESS_DENIED =)


Mr.Power

тьфу там всё нормомLookupAccountSid(vbNullString, tInfoStructure.sid, _sUser, lUserLen, sDomain, lDomainLen, lSidNameUse)возвращает 0 хотя должен возвращать чтото другоекороче функция почемуто не выполгняется


Mr.Power

наверное ERROR_ACCESS_DENIED =)
Скорее всего :)Вот франкенштейнчик, быстренько сляпанный из обоих примеров.Но для тех процессов, что в Task Manager показываются с именем пользователя "LOCAL SERVICE" или "NETWORK SERVICE" под моей учётной записью та же самая Access Denied. cкачать


Mr.Power

ну всё вот готовый код, только надо подумать над тем чтобы выдавались все пользователи. Как Это сделать?


Mr.Power

Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

Private Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long

Const TOKEN_DUPLICATE As Long = &H2
Const TOKEN_IMPERSONATE As Long = &H4
Const TOKEN_QUERY As Long = &H8
Private Const PROCESS_QUERY_INFORMATION As Long = (&H400)
Private Const ERROR_ACCESS_DENIED As Long = <b>5</b>&

Private Declare Function OpenProcessToken Lib "advapi32" ( _
ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
TokenHandle As Long) As Long

Private Declare Function GetTokenInformation Lib "advapi32.dll" ( _
ByVal TokenHandle As Long, _
ByVal TokenInformationClass As Integer, _
TokenInformation As Any, _
ByVal TokenInformationLength As Long, _
ReturnLength As Long) As Long

Private Declare Function LookupAccountSid Lib "advapi32.dll" Alias "LookupAccountSidA" ( _
ByVal lpSystemName As String, _
ByVal Sid As Long, _
ByVal Name As String, _
cbName As Long, _
ByVal ReferencedDomainName As String, _
cbReferencedDomainName As Long, _
peUse As Long) As Long


Const TOKEN_USER = <b>1</b>
Const SPARE_LEN = <b>512</b>

Private Type SID_AND_ATTRIBUTES
Sid As Long
Attributes As Long
Spare(SPARE_LEN) As Byte
End Type

Private Function sDecodeTokenUser(hToken As Long) As String
' Returns the 'domain\user' owner of the specified access token
Dim lSidNameUse As Long
Dim sUser As String
Dim sDomain As String
Dim lUserLen As Long
Dim lDomainLen As Long
Dim tInfoStructure As SID_AND_ATTRIBUTES
Dim lInfoLen As Long
Dim Sid As Long
If GetTokenInformation(hToken, TOKEN_USER, tInfoStructure, _
SPARE_LEN + <b>4</b>, lInfoLen) = <b>0</b> Then

Else
sUser = String$(<b>100</b>, Chr(<b>0</b>))
sDomain = String$(<b>100</b>, Chr(<b>0</b>))
lUserLen = Len(sUser)
lDomainLen = Len(sDomain)

Form1.Caption = LookupAccountSid(vbNullString, tInfoStructure.Sid, _
sUser, lUserLen, sDomain, lDomainLen, lSidNameUse)




sUser = Left$(sUser, InStr(sUser, Chr$(<b>0</b>)) - <b>1</b>)
sDomain = Left$(sDomain, InStr(sDomain, Chr$(<b>0</b>)) - <b>1</b>)
sDecodeTokenUser = sUser

End If

End Function





Public Function getUSERbyPID(lPID As Long) As String
ACCESS = TOKEN_QUERY

 Dim hProcess As Long
 Dim hToken As Long
 Dim lStatus As Long

' Get a handle to the process whose ID is in lPID
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, <b>0</b>, lPID)


' Now get its primary access token
lStatus = OpenProcessToken(hProcess, ACCESS, hToken)


d = sDecodeTokenUser(hToken)
getUSERbyPID = d


CloseHandle hToken
CloseHandle hProcess

End Function


Mr.Power

кстати, где там http://support.microsoft.com/kb/187913 нашли ответ на мой 2й вопрос?:)


Mr.Power

я хочу получть полный путь до исполняемого файла зная его processID


Mr.Power

> Автор: Mr.Power> кстати, где там http://support.microsoft.com/kb/187913> нашли ответ на мой 2й вопрос?:)Отвечу вопросом, а ты пример оттуда запускал?


Mr.Power

кстати, где там http://support.microsoft.com/kb/187913 нашли ответ на мой 2й вопрос?:)я хочу получть полный путь до исполняемого файла зная его processID
"- Шо, опять?!!" ((с) "Жил-был пёс")Да, вот ещё обсуждение, копай.


Mr.Power

извиняюсь ступил


Mr.Power

Можно попробовать WMI:
Private Sub GetInfoByProcessId(PID As Long)
 Dim WMI As Object
 Dim wProcesses As Object
 Dim wProcess As Object
 Dim wUser As String
 Dim wDomain As String
 
 Set WMI = GetObject("WinMgmts:\\.\Root\CIMV2")
 
 Set wProcesses = WMI.ExecQuery("select * from Win32_Process where ProcessId='" + LTrim(Str(PID)) + "'")
 
 For Each wProcess In wProcesses
 With wProcess
 MsgBox .ExecutablePath
 .GetOwner wUser, wDomain
 MsgBox wUser
 MsgBox wDomain
 End With
 Next
End Sub


Mr.Power

Да, с WMI будет значительно проще. Вылетело из головы.


Mr.Power

Бенедикт,ты не знаешь а чё так виснет при использовании этого кода?


Mr.Power

а может попробовать прокачать тему с привилегиями?вот код только он какбудто не работает.
Private Const SE_PRIVILEGE_ENABLED As Long = &H2

Private Const SE_PRIVILEGE_ENABLED_BY_DEFAULT As Long = &H1
Private Const SE_PRIVILEGE_USED_FOR_ACCESS As Long = &H80000000


Private Const ANYSIZE_ARRAY As Long = <b>1</b>

Private Const TOKEN_ADJUST_PRIVILEGES As Long = &H20




Private Type LUID
 LowPart As Long
 HighPart As Long
End Type

Private Type LUID_AND_ATTRIBUTES
 pLuid As LUID
 Attributes As Long
End Type



Private Type LARGE_INTEGER
 LowPart As Long
 HighPart As Long
End Type

Private Type TOKEN_PRIVILEGES
 PrivilegeCount As Long
 Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type







Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LARGE_INTEGER) As Long
Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Long) As Long
Private Declare Function GetCurrentProcessId Lib "kernel32.dll" () As Long

Private Declare Function CloseHandle Lib "kernel32.dll" (ByVal hObject As Long) As Long

Private Declare Function OpenProcess Lib "kernel32" ( _
ByVal dwDesiredAccess As Long, _
ByVal bInheritHandle As Long, _
ByVal dwProcessId As Long) As Long

Const TOKEN_DUPLICATE As Long = &H2
Const TOKEN_IMPERSONATE As Long = &H4
Const TOKEN_QUERY As Long = &H8
Private Const PROCESS_QUERY_INFORMATION As Long = (&H400)
Private Const ERROR_ACCESS_DENIED As Long = <b>5</b>&

Private Declare Function OpenProcessToken Lib "advapi32" ( _
ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, _
TokenHandle As Long) As Long

Private Declare Function GetTokenInformation Lib "advapi32.dll" ( _
ByVal TokenHandle As Long, _
ByVal TokenInformationClass As Integer, _
TokenInformation As Any, _
ByVal TokenInformationLength As Long, _
ReturnLength As Long) As Long

Private Declare Function LookupAccountSid Lib "advapi32.dll" Alias "LookupAccountSidA" ( _
ByVal lpSystemName As String, _
ByVal Sid As Long, _
ByVal Name As String, _
cbName As Long, _
ByVal ReferencedDomainName As String, _
cbReferencedDomainName As Long, _
peUse As Long) As Long

Public Function setPrivileges(PrivilegeName As Variant)
Dim tkp As TOKEN_PRIVILEGES
Dim pr As LARGE_INTEGER
result = OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, token)
If Not result Then Exit Function
result = LookupPrivilegeValue(vbNullString, PrivilegeName, pr)
If Not result Then Exit Function
tkp.PrivilegeCount = <b>1</b>

tkp.Privileges(<b>0</b>).Attributes = SE_PRIVILEGE_ENABLED
Dim tpss As TOKEN_PRIVILEGES
cb = <b>0</b>
result = AdjustTokenPrivileges(token, False, tkp, Len(tkp), tpss, cb)
CloseHandle (token)
End Function


Mr.Power

> Автор: Mr.Power> а может попробовать прокачать тему с привилегиями?А чего прокачивать? на остове этой (и ещё одной) статьи: HOWTO: Use the SeDebugPrivilege to Acquire Any Process Handle я делал программу для сетапа, которая создавала пользователей, раздавала им права ра ветки реестра, файлы и папки. А именно эту привилегию необходимо иметь для програмного прибивания другого работающего процесса в системе.


Mr.Power

ничего не понятно, почемуто не хочет у меня сробатывать функция AdjustTokenPrivilegesDim tkp As TOKEN_PRIVILEGESDim pr As LARGE_INTEGERDim TkpOld As TOKEN_PRIVILEGESresult = OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, token)Dim rets As LongRet = LookupPrivilegeValue(vbNullString, PrivilegeName, tkp.Privileges(0).pLuid)tkp.PrivilegeCount = 1tkp.Privileges(0).Attributes = SE_PRIVILEGE_ENABLEDaOkReboot = AdjustTokenPrivileges(token, -1, tkp, LenB(tkp), TkpOld, rets)не пойму в чём дело вроде всё правильно token есть, tpk, тоже.все значения поступают правильно, однако функция не выполняется, возвращает 0Как тут быть?


Mr.Power

> Автор: Mr.Power> Как тут быть?Смотреть что говорит GetLastError
If the function fails, the return value is zero. To get extended error information, call GetLastError.


Mr.Power

вот вроде всё отладил однако ничего не происходит, остальные юзеры как были невидимыми так и остались
Function priva()


Dim hToken As Long
Dim hProcess As Long
Dim tp As TOKEN_PRIVILEGES
Dim ttk As TOKEN_PRIVILEGES



If OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hToken) = <b>0</b> Then

End If

 If LookupPrivilegeValue("", "SeDebugPrivilege", tp.Privileges(<b>0</b>).pLuid) = <b>0</b> Then
'If LookupPrivilegeValue(vbNullString, "SeImpersonatePrivilege", tp.Privileges(0).pLuid) = 0 Then

End If

tp.PrivilegeCount = <b>1</b>
tp.Privileges(<b>0</b>).Attributes = SE_PRIVILEGE_ENABLED

If AdjustTokenPrivileges(hToken, False, tp, Len(tp), ttk, m) = <b>0</b> Then
Beep
End If

End Function