PureBasic - форум

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » PureBasic - форум » Вопросы по PureBasic » Как получить параметры командной строки чужого процесса?


Как получить параметры командной строки чужого процесса?

Сообщений 1 страница 10 из 10

1

Прошу помочь.

Пытаюсь решить вопрос получения по известному PID параметров командной строки чужого процесса.
В результате поисков уяснил, что существует две методики:
1) через NtQueryInformationProcess
2) через WMI

Первый способ не рекомендуют, объясняя это тем, что функция NtQueryInformationProcess зависит от системы и не документирована. Т.е. способ ненадежен.
Второй способ рекомендуют. Но я не могу по своему скудоумию разобраться, как его реализовать для своей задачи.
Нашел такой пример на PB:

Получение информации через WMI
Код:
#COINIT_MULTITHREAD=0
#RPC_C_AUTHN_LEVEL_CONNECT=2
#RPC_C_IMP_LEVEL_IDENTIFY=2
#EOAC_NONE=0
#RPC_C_AUTHN_WINNT=10
#RPC_C_AUTHZ_NONE=0
#RPC_C_AUTHN_LEVEL_CALL=3
#RPC_C_IMP_LEVEL_IMPERSONATE=3
#CLSCTX_INPROC_SERVER=1
#wbemFlagReturnImmediately=16
#wbemFlagForwardOnly=32
#IFlags = #wbemFlagReturnImmediately + #wbemFlagForwardOnly
; #WBEM_INFINITE=$FFFFFFFF
 
 
Procedure.l ansi2bstr(ansi.s)
        size.l=MultiByteToWideChar_(#CP_ACP,0,ansi,Len(ansi),0,0)
        ;size =20
  Dim unicode.w(size)
  MultiByteToWideChar_(#CP_ACP, 0, ansi, Len(ansi), unicode(), size);#CP_ACP
  For i=0 To size
        tmp.s + Hex(unicode(i),#PB_Unicode)
        Next
  ;MessageRequester(Str(size), tmp )
  ProcedureReturn SysAllocString_(@unicode())
EndProcedure
 
Procedure bstr2string (bstr)
        Shared result.s
  result = PeekS(bstr, -1, #PB_Unicode)
  ProcedureReturn @result
EndProcedure
 
 
Procedure.l GetWMIData(WMIobj.s)
ClearGadgetItems(0)
SetWindowTitle(0,"WMI Reader  -  retrieving data from " + WMIobj)
If Left(LCase(WMIobj),6)="win32_": WMIobj = "SELECT * FROM " + WMIobj: EndIf
;- WMI calling
; --- Step 1: Initialize COM parameters with a call to CoInitializeEx
CoInitializeEx_(0,#COINIT_MULTITHREAD)
; --- Step 2: Initialize COM process security by calling CoInitializeSecurity.
hres=CoInitializeSecurity_(0, -1,0,0,#RPC_C_AUTHN_LEVEL_CONNECT,#RPC_C_IMP_LEVEL_IDENTIFY,0,#EOAC_NONE,0)
If hres <> 0: MessageRequester("ERROR", "unable to call CoInitializeSecurity", #MB_OK): Goto cleanup: EndIf
; --- Step 3: Obtain the initial locator to WMI by calling CoCreateInstance.
hres=CoCreateInstance_(?CLSID_WbemLocator,0,#CLSCTX_INPROC_SERVER,?IID_IWbemLocator,@loc.IWbemLocator)
If hres <> 0: MessageRequester("ERROR", "unable to call CoCreateInstance", #MB_OK): Goto cleanup: EndIf   
; --- Step 4: Obtain a pointer to IWbemServices for the root\cimv2 namespace on the local computer by calling IWbemLocator::ConnectServer.
If #PB_Compiler_Unicode = 1;we create unicode application
        hres=loc\ConnectServer(@"root\cimv2" ,0,0,0,0,0,0,@svc.IWbemServices)
Else; non unicode
        hres=loc\ConnectServer(ansi2bstr("root\cimv2"),0,0,0,0,0,0,@svc.IWbemServices)
EndIf
If hres <> 0: MessageRequester(Hex(hres), "unable To call IWbemLocator::ConnectServer", #MB_OK): Goto cleanup: EndIf
hres=svc\queryinterface(?IID_IUnknown,@pUnk.IUnknown)
; --- Step 5: Set IWbemServices proxy security so the WMI service can impersonate the client by calling CoSetProxyBlanket.
hres=CoSetProxyBlanket_(svc,#RPC_C_AUTHN_WINNT,#RPC_C_AUTHZ_NONE,0,#RPC_C_AUTHN_LEVEL_CALL,#RPC_C_IMP_LEVEL_IMPERSONATE,0,#EOAC_NONE)
If hres <> 0: MessageRequester("ERROR", "unable to call CoSetProxyBlanket", #MB_OK): Goto cleanup: EndIf   
hres=CoSetProxyBlanket_(pUnk,#RPC_C_AUTHN_WINNT,#RPC_C_AUTHZ_NONE,0,#RPC_C_AUTHN_LEVEL_CALL,#RPC_C_IMP_LEVEL_IMPERSONATE,0,#EOAC_NONE)
If hres <> 0: MessageRequester("ERROR", "unable to call CoSetProxyBlanket", #MB_OK): Goto cleanup: EndIf   
pUnk\release()
; --- Step 6: Use the IWbemServices pointer to make requests of WMI.
If #PB_Compiler_Unicode = 1
        hres=svc\ExecQuery(@"WQL",@WMIobj, #IFlags,0,@pEnumerator.IEnumWbemClassObject)
Else
        hres=svc\ExecQuery(ansi2bstr("WQL"),ansi2bstr(WMIobj), #IFlags,0,@pEnumerator.IEnumWbemClassObject)
EndIf
If hres <> 0: MessageRequester("ERROR", "unable to call IWbemServices::ExecQuery", #MB_OK): Goto cleanup: EndIf   
; --- Step 7: Get the data from the WQL query. The IEnumWbemClassObject pointer is linked to the data objects that the query returned,
; ---            and the data objects can be retrieved with the IEnumWbemClassObject::Next method. This method links the data objects to an IWbemClassObject pointer
; ---            that is passed into the method. Use the IWbemClassObject::Get method to get the desired information from the data objects.
mem=AllocateMemory(1000)
hres=pEnumerator\reset()
ItemCount.l=0
Repeat
        ItemCount+ 1
        hres = pEnumerator\Next(#WBEM_INFINITE, 1, @pclsObj.IWbemClassObject, @uReturn)
        If uReturn = 0
                Break
        Else
                AddGadgetItem(0,-1,"")
                AddGadgetItem(0,-1,"Item #" + Str(ItemCount))
                SetGadgetItemColor(0,CountGadgetItems(0)-1,#PB_Gadget_FrontColor, $900000)
        EndIf
        hres=pclsObj\GetNames(0, 0, 0,@sf.l); get a list with the names of the properties.
        SafeArrayGetLBound_(sf, 1, @lBound)
        SafeArrayGetUBound_(sf, 1, @uBound)
        Dim indices(1)
        For i = lBound To uBound
                indices(0) = i
                SafeArrayGetElement_(sf, @indices(), @temp)
                If temp
                        tmp.s = PeekS(temp, -1, #PB_Unicode)
                        If #PB_Compiler_Unicode = 1
                                hres=pclsObj\get(@tmp, 0, mem, 0, 0)
                        Else
                                hres=pclsObj\get(ansi2bstr(tmp), 0, mem, 0, 0)
                        EndIf
                       
                        type=PeekW(mem)
                       
                        Select type
                                Case 8
                                        val.s=PeekS(bstr2string(PeekL(mem+8)))
                                Case 3
                                        val.s=Str(PeekL(mem+8))
                                Default
                                        val.s=""
                        EndSelect
                        If FindString(WMIobj,"*",1) <> 0;we need everything, not just some specific properties
                                AddGadgetItem(0,-1,tmp+Chr(10)+val)
                        ElseIf Left(tmp,1)<>"_";we need some specific properties, not all, not these starting with '_'.
                                AddGadgetItem(0,-1,tmp+Chr(10)+val)
                        EndIf
                               
                EndIf
        Next
Until uReturn = 0
If CountGadgetItems(0) > 0
        RemoveGadgetItem(0,0)
        If ItemCount = 2
                RemoveGadgetItem(0,0)
        EndIf
Else
        AddGadgetItem(0,-1,""+Chr(10)+"No data to display")
EndIf
; --- Step 8: Cleanup
cleanup:
svc\release()
loc\release()
pEnumerator\release()
If uReturn: pclsObj\release(): EndIf
CoUninitialize_()
SetWindowTitle(0,"WMI Reader")
EndProcedure
 
If OpenWindow(0,0,0,800,500,"WMI Reader",#PB_Window_SystemMenu | #PB_Window_TitleBar | #PB_Window_ScreenCentered | #PB_Window_MinimizeGadget)
ListIconGadget(0,310,10,480,480,"Property",200,#PB_ListIcon_GridLines)
AddGadgetColumn(0,1,"Value",400)
AddGadgetItem(0,-1,""+Chr(10)+"Please select a class to access its data")
 
PanelGadget(1, 10,10,280,480)
AddGadgetItem(1,-1,"Hierarchical Order")
        TreeGadget(2, 6, 10, 260, 437)
AddGadgetItem(1,-1,"Alphabetical Order")
        TreeGadget(3, 6, 10, 260, 437)
AddGadgetItem(1,-1,"Custom")
        TextGadget(4, 10, 10, 260, 160,"Please enter the WMI class you want to execute."+Chr(13)+Chr(13)+"For example:"+Chr(13)+"Win32_OperatingSystem"+Chr(13)+"Or"+Chr(13)+"win32_operatingsystem"+Chr(13)+"(the name that you write is case insensitive.)"+Chr(13)+"Or"+Chr(13)+"Select * from Win32_OperatingSystem"+Chr(13)+"Or"+Chr(13)+"Select Caption, Name from Win32_OperatingSystem")
        StringGadget(5, 6,160,260,25,"")
        ButtonGadget(6,6,190,60,30,"Execute")
CloseGadgetList()
 
NewList WC.s()
ii.l=0; this var is needed to obtain the type of the inserted value, node or sub item.
Restore WMIClasses
Repeat
        Read.s tmp.s
        If tmp = "-1": Break: EndIf
        Select Left(tmp,2)
                Case "++"
                        AddGadgetItem (2, -1, Right(tmp,Len(tmp)-2),0,1)
                        SetGadgetItemColor(2,CountGadgetItems(2)-1,#PB_Gadget_FrontColor, $900000)
                        ii = 2
                Case "+ "
                        AddGadgetItem (2, -1, Right(tmp,Len(tmp)-2))
                        SetGadgetItemColor(2,CountGadgetItems(2)-1,#PB_Gadget_FrontColor, $900000)
                        ii = 1
                Default
                        AddGadgetItem(2, -1, tmp, 0, ii)
                        AddElement(WC()): WC() = tmp
                EndSelect
ForEver
 
 
 
 
SortList(WC(),#PB_Sort_Ascending)
ForEach WC()
        AddGadgetItem(3, -1, WC())
Next
 
Repeat
        Select WaitWindowEvent()
                Case #PB_Event_Gadget
         Select EventGadget()
                Case 2;hierarchical view
                        tmp = GetGadgetItemText(2,GetGadgetState(2))
                        If Left(tmp,5)="Win32"
                                GetWMIData(tmp)
                        EndIf
                Case 3;alphabetical view
                        GetWMIData(GetGadgetItemText(3,GetGadgetState(3)))
                Case 6;try to execute a user's class. we do not worry if the class is present or not.
                        GetWMIData(GetGadgetText(5))
         EndSelect
                Case #PB_Event_CloseWindow
                        Break
        EndSelect
ForEver
EndIf
 
;- DATA
DataSection
CLSID_IEnumWbemClassObject:
   ;1B1CAD8C-2DAB-11D2-B604-00104B703EFD
Data.l $1B1CAD8C
Data.w $2DAB, $11D2
Data.b $B6, $04, $00, $10, $4B, $70, $3E, $FD
IID_IEnumWbemClassObject:
   ;7C857801-7381-11CF-884D-00AA004B2E24
Data.l $7C857801
Data.w $7381, $11CF
Data.b $88, $4D, $00, $AA, $00, $4B, $2E, $24
CLSID_WbemLocator:
    ;4590f811-1d3a-11d0-891f-00aa004b2e24
Data.l $4590F811
Data.w $1D3A, $11D0
Data.b $89, $1F, $00, $AA, $00, $4B, $2E, $24
IID_IWbemLocator:
    ;dc12a687-737f-11cf-884d-00aa004b2e24
Data.l $DC12A687
Data.w $737F, $11CF
Data.b $88, $4D, $00, $AA, $00, $4B, $2E, $24
IID_IUnknown:
    ;00000000-0000-0000-C000-000000000046
Data.l $00000000
Data.w $0000, $0000
Data.b $C0, $00, $00, $00, $00, $00, $00, $46
IID_IWbemRefresher:
    ;49353c99-516b-11d1-aea6-00c04fb68820
Data.l $49353C99
Data.w $516B, $11D1
Data.b $AE, $A6, $00, $C0, $4F, $B6, $88, $20
CLSID_WbemRefresher:
    ;c71566f2-561E-11D1-AD87-00C04FD8FDFF
Data.l $C71566F2
Data.w $561E, $11D1
Data.b $AD,$87,$00,$C0,$4F,$D8,$FD,$FF
IID_IWbemConfigureRefresher:
    ;49353c92-516b-11d1-aea6-00c04fb68820
Data.l $49353C92
Data.w $516B, $11D1
Data.b $AE, $A6, $00, $C0, $4F, $B6, $88, $20
IID_IWbemObjectAccess:
    ;49353c9a-516b-11d1-aea6-00c04fb68820
Data.l $49353C9A
Data.w $516B, $11D1
Data.b $AE, $A6, $00, $C0, $4F, $B6, $88, $20
EndDataSection


;WMI classes, the '+' symbol indicates new node
DataSection
WMIClasses:
Data.s "+ Computer System Hardware Classes"
Data.s "++Cooling Device"
Data.s "Win32_Fan"
Data.s "Win32_HeatPipe"
Data.s "Win32_Refrigeration"
Data.s "Win32_TemperatureProbe"
Data.s "++Input Device"
Data.s "Win32_Keyboard"
Data.s "Win32_PointingDevice"
Data.s "++Mass Storage"
Data.s "Win32_AutochkSetting"
Data.s "Win32_CDROMDrive"
Data.s "Win32_DiskDrive"
Data.s "Win32_FloppyDrive"
Data.s "Win32_LogicalDisk"
Data.s "Win32_PhysicalMedia"
Data.s "Win32_TapeDrive"
Data.s "++Motherboard, Controller, and Port"
Data.s "Win32_1394Controller"
Data.s "Win32_1394ControllerDevice"
Data.s "Win32_AllocatedResource"
Data.s "Win32_AssociatedProcessorMemory"
Data.s "Win32_BaseBoard"
Data.s "Win32_BIOS"
Data.s "Win32_Bus"
Data.s "Win32_CacheMemory"
Data.s "Win32_ControllerHasHub"
Data.s "Win32_DeviceBus"
Data.s "Win32_DeviceMemoryAddress"
Data.s "Win32_DeviceSettings"
Data.s "Win32_DMAChannel"
Data.s "Win32_FloppyController"
Data.s "Win32_IDEController"
Data.s "Win32_IDEControllerDevice"
Data.s "Win32_InfraredDevice"
Data.s "Win32_IRQResource"
Data.s "Win32_MemoryArray"
Data.s "Win32_MemoryArrayLocation"
Data.s "Win32_MemoryDevice"
Data.s "Win32_MemoryDeviceArray"
Data.s "Win32_MemoryDeviceLocation"
Data.s "Win32_MotherboardDevice"
Data.s "Win32_OnBoardDevice"
Data.s "Win32_ParallelPort"
Data.s "Win32_PCMCIAController"
Data.s "Win32_PhysicalMemory"
Data.s "Win32_PhysicalMemoryArray"
Data.s "Win32_PhysicalMemoryLocation"
Data.s "Win32_PNPAllocatedResource"
Data.s "Win32_PNPDevice"
Data.s "Win32_PNPEntity"
Data.s "Win32_PortConnector"
Data.s "Win32_PortResource"
Data.s "Win32_Processor"
Data.s "Win32_SCSIController"
Data.s "Win32_SCSIControllerDevice"
Data.s "Win32_SerialPort"
Data.s "Win32_SerialPortConfiguration"
Data.s "Win32_SerialPortSetting"
Data.s "Win32_SMBIOSMemory"
Data.s "Win32_SoundDevice"
Data.s "Win32_SystemBIOS"
Data.s "Win32_SystemDriverPNPEntity"
Data.s "Win32_SystemEnclosure"
Data.s "Win32_SystemMemoryResource"
Data.s "Win32_SystemSlot"
Data.s "Win32_USBController"
Data.s "Win32_USBControllerDevice"
Data.s "Win32_USBHub"
Data.s "++Networking Device"
Data.s "Win32_NetworkAdapter"
Data.s "Win32_NetworkAdapterConfiguration"
Data.s "Win32_NetworkAdapterSetting"
Data.s "++Power"
Data.s "Win32_AssociatedBattery"
Data.s "Win32_Battery"
Data.s "Win32_CurrentProbe"
Data.s "Win32_PortableBattery"
Data.s "Win32_PowerManagementEvent"
Data.s "Win32_UninterruptiblePowerSupply"
Data.s "Win32_VoltageProbe"
Data.s "++Printing"
Data.s "Win32_DriverForDevice"
Data.s "Win32_Printer"
Data.s "Win32_PrinterConfiguration"
Data.s "Win32_PrinterController"
Data.s "Win32_PrinterDriver"
Data.s "Win32_PrinterDriverDll"
Data.s "Win32_PrinterSetting"
Data.s "Win32_PrintJob"
Data.s "Win32_TCPIPPrinterPort"
Data.s "++Telephony"
Data.s "Win32_POTSModem"
Data.s "Win32_POTSModemToSerialPort"
Data.s "++Video and Monitor"
Data.s "Win32_DesktopMonitor"
Data.s "Win32_DisplayConfiguration"
Data.s "Win32_DisplayControllerConfiguration"
Data.s "Win32_VideoConfiguration"
Data.s "Win32_VideoController"
Data.s "Win32_VideoSettings"
Data.s "+ Operating System"
Data.s "++COM"
Data.s "Win32_ClassicCOMApplicationClasses"
Data.s "Win32_ClassicCOMClass"
Data.s "Win32_ClassicCOMClassSettings"
Data.s "Win32_ClientApplicationSetting"
Data.s "Win32_COMApplication"
Data.s "Win32_COMApplicationClasses"
Data.s "Win32_COMApplicationSettings"
Data.s "Win32_COMClass"
Data.s "Win32_ComClassAutoEmulator"
Data.s "Win32_ComClassEmulator"
Data.s "Win32_ComponentCategory"
Data.s "Win32_COMSetting"
Data.s "Win32_DCOMApplication"
Data.s "Win32_DCOMApplicationAccessAllowedSetting"
Data.s "Win32_DCOMApplicationLaunchAllowedSetting"
Data.s "Win32_DCOMApplicationSetting"
Data.s "Win32_ImplementedCategory"
Data.s "++Desktop"
Data.s "Win32_Desktop"
Data.s "Win32_Environment"
Data.s "Win32_TimeZone"
Data.s "Win32_UserDesktop"
Data.s "++Drivers"
Data.s "Win32_DriverVXD"
Data.s "Win32_SystemDriver"
Data.s "++File System"
Data.s "Win32_CIMLogicalDeviceCIMDataFile"
Data.s "Win32_Directory"
Data.s "Win32_DirectorySpecification"
Data.s "Win32_DiskDriveToDiskPartition"
Data.s "Win32_DiskPartition"
Data.s "Win32_DiskQuota"
Data.s "Win32_LogicalDisk"
Data.s "Win32_LogicalDiskRootDirectory"
Data.s "Win32_LogicalDiskToPartition"
Data.s "Win32_MappedLogicalDisk"
Data.s "Win32_OperatingSystemAutochkSetting"
Data.s "Win32_QuotaSetting"
Data.s "Win32_ShortcutFile"
Data.s "Win32_SubDirectory"
Data.s "Win32_SystemPartitions"
Data.s "Win32_Volume"
Data.s "Win32_VolumeQuota"
Data.s "Win32_VolumeQuotaSetting"
Data.s "Win32_VolumeUserQuota"
Data.s "++Job Objects"
Data.s "Win32_CollectionStatistics"
Data.s "Win32_LUID"
Data.s "Win32_LUIDandAttributes"
Data.s "Win32_NamedJobObject"
Data.s "Win32_NamedJobObjectActgInfo"
Data.s "Win32_NamedJobObjectLimit"
Data.s "Win32_NamedJobObjectLimitSetting"
Data.s "Win32_NamedJobObjectProcess"
Data.s "Win32_NamedJobObjectSecLimit"
Data.s "Win32_NamedJobObjectSecLimitSetting"
Data.s "Win32_NamedJobObjectStatistics"
Data.s "Win32_SIDandAttributes"
Data.s "Win32_TokenGroups"
Data.s "Win32_TokenPrivileges"
Data.s "++Memory And Page Files"
Data.s "Win32_LogicalMemoryConfiguration"
Data.s "Win32_PageFile"
Data.s "Win32_PageFileElementSetting"
Data.s "Win32_PageFileSetting"
Data.s "Win32_PageFileUsage"
Data.s "Win32_SystemLogicalMemoryConfiguration"
Data.s "++Multimedia Audio Or Visual"
Data.s "Win32_CodecFile"
Data.s "++Networking"
Data.s "Win32_ActiveRoute"
Data.s "Win32_IP4PersistedRouteTable"
Data.s "Win32_IP4RouteTable"
Data.s "Win32_IP4RouteTableEvent"
Data.s "Win32_NetworkClient"
Data.s "Win32_NetworkConnection"
Data.s "Win32_NetworkProtocol"
Data.s "Win32_NTDomain"
Data.s "Win32_PingStatus"
Data.s "Win32_ProtocolBinding"
Data.s "++Operating System Events"
Data.s "Win32_ComputerShutdownEvent"
Data.s "Win32_ComputerSystemEvent"
Data.s "Win32_DeviceChangeEvent"
Data.s "Win32_ModuleLoadTrace"
Data.s "Win32_ModuleTrace"
Data.s "Win32_ProcessStartTrace"
Data.s "Win32_ProcessStopTrace"
Data.s "Win32_ProcessTrace"
Data.s "Win32_SystemConfigurationChangeEvent"
Data.s "Win32_SystemTrace"
Data.s "Win32_ThreadStartTrace"
Data.s "Win32_ThreadStopTrace"
Data.s "Win32_ThreadTrace"
Data.s "Win32_VolumeChangeEvent"
Data.s "++Operating System Settings"
Data.s "Win32_BootConfiguration"
Data.s "Win32_ComputerSystem"
Data.s "Win32_ComputerSystemProcessor"
Data.s "Win32_ComputerSystemProduct"
Data.s "Win32_DependentService"
Data.s "Win32_LoadOrderGroup"
Data.s "Win32_LoadOrderGroupServiceDependencies"
Data.s "Win32_LoadOrderGroupServiceMembers"
Data.s "Win32_OperatingSystem"
Data.s "Win32_OperatingSystemQFE"
Data.s "Win32_OSRecoveryConfiguration"
Data.s "Win32_QuickFixEngineering"
Data.s "Win32_StartupCommand"
Data.s "Win32_SystemBootConfiguration"
Data.s "Win32_SystemDesktop"
Data.s "Win32_SystemDevices"
Data.s "Win32_SystemLoadOrderGroups"
Data.s "Win32_SystemNetworkConnections"
Data.s "Win32_SystemOperatingSystem"
Data.s "Win32_SystemProcesses"
Data.s "Win32_SystemProgramGroups"
Data.s "Win32_SystemResources"
Data.s "Win32_SystemServices"
Data.s "Win32_SystemSetting"
Data.s "Win32_SystemSystemDriver"
Data.s "Win32_SystemTimeZone"
Data.s "Win32_SystemUsers"
Data.s "++Processes"
Data.s "Win32_Process"
Data.s "Win32_ProcessStartup"
Data.s "Win32_Thread"
Data.s "++Registry"
Data.s "Win32_Registry"
Data.s "++Scheduler Jobs"
Data.s "Win32_CurrentTime"
Data.s "Win32_ScheduledJob"
Data.s "Win32_LocalTime"
Data.s "Win32_UTCTime"
Data.s "++Security"
Data.s "Win32_AccountSID"
Data.s "Win32_ACE"
Data.s "Win32_LogicalFileAccess"
Data.s "Win32_LogicalFileAuditing"
Data.s "Win32_LogicalFileGroup"
Data.s "Win32_LogicalFileOwner"
Data.s "Win32_LogicalFileSecuritySetting"
Data.s "Win32_LogicalShareAccess"
Data.s "Win32_LogicalShareAuditing"
Data.s "Win32_LogicalShareSecuritySetting"
Data.s "Win32_PrivilegesStatus"
Data.s "Win32_SecurityDescriptor"
Data.s "Win32_SecuritySetting"
Data.s "Win32_SecuritySettingAccess"
Data.s "Win32_SecuritySettingAuditing"
Data.s "Win32_SecuritySettingGroup"
Data.s "Win32_SecuritySettingOfLogicalFile"
Data.s "Win32_SecuritySettingOfLogicalShare"
Data.s "Win32_SecuritySettingOfObject"
Data.s "Win32_SecuritySettingOwner"
Data.s "Win32_SID"
Data.s "Win32_Trustee"
Data.s "++Services"
Data.s "Win32_BaseService"
Data.s "Win32_Service"
Data.s "++Shares"
Data.s "Win32_DFSNode"
Data.s "Win32_DFSNodeTarget"
Data.s "Win32_DFSTarget"
Data.s "Win32_ServerConnection"
Data.s "Win32_ServerSession"
Data.s "Win32_ConnectionShare"
Data.s "Win32_PrinterShare"
Data.s "Win32_SessionConnection"
Data.s "Win32_SessionProcess"
Data.s "Win32_ShareToDirectory"
Data.s "Win32_Share"
Data.s "++Start Menu"
Data.s "Win32_LogicalProgramGroup"
Data.s "Win32_LogicalProgramGroupDirectory"
Data.s "Win32_LogicalProgramGroupItem"
Data.s "Win32_LogicalProgramGroupItemDataFile"
Data.s "Win32_ProgramGroup"
Data.s "Win32_ProgramGroupContents"
Data.s "Win32_ProgramGroupOrItem"
Data.s "++Storage"
Data.s "Win32_ShadowBy"
Data.s "Win32_ShadowContext"
Data.s "Win32_ShadowCopy"
Data.s "Win32_ShadowDiffVolumeSupport"
Data.s "Win32_ShadowFor"
Data.s "Win32_ShadowOn"
Data.s "Win32_ShadowProvider"
Data.s "Win32_ShadowStorage"
Data.s "Win32_ShadowVolumeSupport"
Data.s "Win32_Volume"
Data.s "Win32_VolumeUserQuota"
Data.s "++Users"
Data.s "Win32_Account"
Data.s "Win32_Group"
Data.s "Win32_GroupInDomain"
Data.s "Win32_GroupUser"
Data.s "Win32_LogonSession"
Data.s "Win32_LogonSessionMappedDisk"
Data.s "Win32_NetworkLoginProfile"
Data.s "Win32_SystemAccount"
Data.s "Win32_UserAccount"
Data.s "Win32_UserInDomain"
Data.s "++Windows NT Event Log"
Data.s "Win32_NTEventlogFile"
Data.s "Win32_NTLogEvent"
Data.s "Win32_NTLogEventComputer"
Data.s "Win32_NTLogEventLog"
Data.s "Win32_NTLogEventUser"
Data.s "++Windows Product Activation"
Data.s "Win32_ComputerSystemWindowsProductActivationSetting"
Data.s "Win32_Proxy"
Data.s "Win32_WindowsProductActivation"
Data.s "+ Installed Applications"
Data.s "Win32_ActionCheck"
Data.s "Win32_ApplicationCommandLine"
Data.s "Win32_ApplicationService"
Data.s "Win32_Binary"
Data.s "Win32_BindImageAction"
Data.s "Win32_CheckCheck"
Data.s "Win32_ClassInfoAction"
Data.s "Win32_CommandLineAccess"
Data.s "Win32_Condition"
Data.s "Win32_CreateFolderAction"
Data.s "Win32_DuplicateFileAction"
Data.s "Win32_EnvironmentSpecification"
Data.s "Win32_ExtensionInfoAction"
Data.s "Win32_FileSpecification"
Data.s "Win32_FontInfoAction"
Data.s "Win32_IniFileSpecification"
Data.s "Win32_InstalledSoftwareElement"
Data.s "Win32_LaunchCondition"
Data.s "Win32_ManagedSystemElementResource"
Data.s "Win32_MIMEInfoAction"
Data.s "Win32_MoveFileAction"
Data.s "Win32_MSIResource"
Data.s "Win32_ODBCAttribute"
Data.s "Win32_ODBCDataSourceAttribute"
Data.s "Win32_ODBCDataSourceSpecification"
Data.s "Win32_ODBCDriverAttribute"
Data.s "Win32_ODBCDriverSoftwareElement"
Data.s "Win32_ODBCDriverSpecification"
Data.s "Win32_ODBCSourceAttribute"
Data.s "Win32_ODBCTranslatorSpecification"
Data.s "Win32_Patch"
Data.s "Win32_PatchFile"
Data.s "Win32_PatchPackage"
Data.s "Win32_Product"
Data.s "Win32_ProductCheck"
Data.s "Win32_ProductResource"
Data.s "Win32_ProductSoftwareFeatures"
Data.s "Win32_ProgIDSpecification"
Data.s "Win32_Property"
Data.s "Win32_PublishComponentAction"
Data.s "Win32_RegistryAction"
Data.s "Win32_RemoveFileAction"
Data.s "Win32_RemoveIniAction"
Data.s "Win32_ReserveCost"
Data.s "Win32_SelfRegModuleAction"
Data.s "Win32_ServiceControl"
Data.s "Win32_ServiceSpecification"
Data.s "Win32_ServiceSpecificationService"
Data.s "Win32_SettingCheck"
Data.s "Win32_ShortcutAction"
Data.s "Win32_ShortcutSAP"
Data.s "Win32_SoftwareElement"
Data.s "Win32_SoftwareElementAction"
Data.s "Win32_SoftwareElementCheck"
Data.s "Win32_SoftwareElementCondition"
Data.s "Win32_SoftwareElementResource"
Data.s "Win32_SoftwareFeature"
Data.s "Win32_SoftwareFeatureAction"
Data.s "Win32_SoftwareFeatureCheck"
Data.s "Win32_SoftwareFeatureParent"
Data.s "Win32_SoftwareFeatureSoftwareElements"
Data.s "Win32_TypeLibraryAction"
Data.s "+ WMI Service Management"
Data.s "++WMI Configuration"
Data.s "Win32_MethodParameterClass"
Data.s "++WMI Management"
Data.s "Win32_WMISetting"
Data.s "Win32_WMIElementSetting"
Data.s "+ Performance Counter"
Data.s "++Formatted Performance Counter"
Data.s "Win32_PerfFormattedData"
Data.s "Win32_PerfFormattedData_ASP_ActiveServerPages"
Data.s "Win32_PerfFormattedData_ContentFilter_IndexingServiceFilter"
Data.s "Win32_PerfFormattedData_ContentIndex_IndexingService"
Data.s "Win32_PerfFormattedData_InetInfo_InternetInformationServicesGlobal"
Data.s "Win32_PerfFormattedData_ISAPISearch_HttpIndexingService"
Data.s "Win32_PerfFormattedData_MSDTC_DistributedTransactionCoordinator"
Data.s "Win32_PerfFormattedData_NTFSDRV_SMTPNTFSStoreDriver"
Data.s "Win32_PerfFormattedData_PerfDisk_LogicalDisk"
Data.s "Win32_PerfFormattedData_PerfDisk_PhysicalDisk"
Data.s "Win32_PerfFormattedData_PerfNet_Browser"
Data.s "Win32_PerfFormattedData_PerfNet_Redirector"
Data.s "Win32_PerfFormattedData_PerfNet_Server"
Data.s "Win32_PerfFormattedData_PerfNet_ServerWorkQueues"
Data.s "Win32_PerfFormattedData_PerfOS_Cache"
Data.s "Win32_PerfFormattedData_PerfOS_Memory"
Data.s "Win32_PerfFormattedData_PerfOS_Objects"
Data.s "Win32_PerfFormattedData_PerfOS_PagingFile"
Data.s "Win32_PerfFormattedData_PerfOS_Processor"
Data.s "Win32_PerfFormattedData_PerfOS_System"
Data.s "Win32_PerfFormattedData_PerfProc_FullImage_Costly"
Data.s "Win32_PerfFormattedData_PerfProc_Image_Costly"
Data.s "Win32_PerfFormattedData_PerfProc_JobObject"
Data.s "Win32_PerfFormattedData_PerfProc_JobObjectDetails"
Data.s "Win32_PerfFormattedData_PerfProc_Process"
Data.s "Win32_PerfFormattedData_PerfProc_ProcessAddressSpace_Costly"
Data.s "Win32_PerfFormattedData_PerfProc_Thread"
Data.s "Win32_PerfFormattedData_PerfProc_ThreadDetails_Costly"
Data.s "Win32_PerfFormattedData_PSched_PSchedFlow"
Data.s "Win32_PerfFormattedData_PSched_PSchedPipe"
Data.s "Win32_PerfFormattedData_RemoteAccess_RASPort"
Data.s "Win32_PerfFormattedData_RemoteAccess_RASTotal"
Data.s "Win32_PerfFormattedData_RSVP_ACSRSVPInterfaces"
Data.s "Win32_PerfFormattedData_RSVP_ACSRSVPService"
Data.s "Win32_PerfFormattedData_SMTPSVC_SMTPServer"
Data.s "Win32_PerfFormattedData_Spooler_PrintQueue"
Data.s "Win32_PerfFormattedData_TapiSrv_Telephony"
Data.s "Win32_PerfFormattedData_Tcpip_ICMP"
Data.s "Win32_PerfFormattedData_Tcpip_IP"
Data.s "Win32_PerfFormattedData_Tcpip_NBTConnection"
Data.s "Win32_PerfFormattedData_Tcpip_NetworkInterface"
Data.s "Win32_PerfFormattedData_Tcpip_TCP"
Data.s "Win32_PerfFormattedData_Tcpip_UDP"
Data.s "Win32_PerfFormattedData_TermService_TerminalServices"
Data.s "Win32_PerfFormattedData_TermService_TerminalServicesSession"
Data.s "Win32_PerfFormattedData_W3SVC_WebService"
Data.s "++Raw Performance Counter"
Data.s "Win32_PerfRawData"
Data.s "Win32_PerfRawData_ASP_ActiveServerPages"
Data.s "Win32_PerfRawData_ContentFilter_IndexingServiceFilter"
Data.s "Win32_PerfRawData_ContentIndex_IndexingService"
Data.s "Win32_PerfRawData_InetInfo_InternetInformationServicesGlobal"
Data.s "Win32_PerfRawData_ISAPISearch_HttpIndexingService"
Data.s "Win32_PerfRawData_MSDTC_DistributedTransactionCoordinator"
Data.s "Win32_PerfRawData_NTFSDRV_SMTPNTFSStoreDriver"
Data.s "Win32_PerfRawData_PerfDisk_LogicalDisk"
Data.s "Win32_PerfRawData_PerfDisk_PhysicalDisk"
Data.s "Win32_PerfRawData_PerfNet_Browser"
Data.s "Win32_PerfRawData_PerfNet_Redirector"
Data.s "Win32_PerfRawData_PerfNet_Server"
Data.s "Win32_PerfRawData_PerfNet_ServerWorkQueues"
Data.s "Win32_PerfRawData_PerfOS_Cache"
Data.s "Win32_PerfRawData_PerfOS_Memory"
Data.s "Win32_PerfRawData_PerfOS_Objects"
Data.s "Win32_PerfRawData_PerfOS_PagingFile"
Data.s "Win32_PerfRawData_PerfOS_Processor"
Data.s "Win32_PerfRawData_PerfOS_System"
Data.s "Win32_PerfRawData_PerfProc_FullImage_Costly"
Data.s "Win32_PerfRawData_PerfProc_Image_Costly"
Data.s "Win32_PerfRawData_PerfProc_JobObject"
Data.s "Win32_PerfRawData_PerfProc_JobObjectDetails"
Data.s "Win32_PerfRawData_PerfProc_Process"
Data.s "Win32_PerfRawData_PerfProc_ProcessAddressSpace_Costly"
Data.s "Win32_PerfRawData_PerfProc_Thread"
Data.s "Win32_PerfRawData_PerfProc_ThreadDetails_Costly"
Data.s "Win32_PerfRawData_PSched_PSchedFlow"
Data.s "Win32_PerfRawData_PSched_PSchedPipe"
Data.s "Win32_PerfRawData_RemoteAccess_RASPort"
Data.s "Win32_PerfRawData_RemoteAccess_RASTotal"
Data.s "Win32_PerfRawData_RSVP_ACSRSVPInterfaces"
Data.s "Win32_PerfRawData_RSVP_ACSRSVPService"
Data.s "Win32_PerfRawData_SMTPSVC_SMTPServer"
Data.s "Win32_PerfRawData_Spooler_PrintQueue"
Data.s "Win32_PerfRawData_TapiSrv_Telephony"
Data.s "Win32_PerfRawData_Tcpip_ICMP"
Data.s "Win32_PerfRawData_Tcpip_IP"
Data.s "Win32_PerfRawData_Tcpip_NBTConnection"
Data.s "Win32_PerfRawData_Tcpip_NetworkInterface"
Data.s "Win32_PerfRawData_Tcpip_TCP"
Data.s "Win32_PerfRawData_Tcpip_UDP"
Data.s "Win32_PerfRawData_TermService_TerminalServices"
Data.s "Win32_PerfRawData_TermService_TerminalServicesSession"
Data.s "Win32_PerfRawData_W3SVC_WebService"
Data.s "+ Security Descriptor Helper"
Data.s "Win32_SecurityDescriptor"
Data.s "-1";end of data
EndDataSection

Проверил, код рабочий, но естественно для моей задачи избыточен, требует сокращения и упрощения.
А так как это самый WMI для меня темный лес, то решить вопрос с упрощением и сокращением пока самостоятельно не могу.
Основная трудность у меня возникла с этим участком кода:

Код:
; --- Step 7: Get the data from the WQL query. The IEnumWbemClassObject pointer is linked to the data objects that the query returned,
; ---            and the data objects can be retrieved with the IEnumWbemClassObject::Next method. This method links the data objects to an IWbemClassObject pointer
; ---            that is passed into the method. Use the IWbemClassObject::Get method to get the desired information from the data objects.
mem=AllocateMemory(1000)
hres=pEnumerator\reset()
ItemCount.l=0
Repeat
        ItemCount+ 1
        hres = pEnumerator\Next(#WBEM_INFINITE, 1, @pclsObj.IWbemClassObject, @uReturn)
        If uReturn = 0
                Break
        Else
                AddGadgetItem(0,-1,"")
                AddGadgetItem(0,-1,"Item #" + Str(ItemCount))
                SetGadgetItemColor(0,CountGadgetItems(0)-1,#PB_Gadget_FrontColor, $900000)
        EndIf
        hres=pclsObj\GetNames(0, 0, 0,@sf.l); get a list with the names of the properties.
        SafeArrayGetLBound_(sf, 1, @lBound)
        SafeArrayGetUBound_(sf, 1, @uBound)
        Dim indices(1)
        For i = lBound To uBound
                indices(0) = i
                SafeArrayGetElement_(sf, @indices(), @temp)
                If temp
                        tmp.s = PeekS(temp, -1, #PB_Unicode)
                        If #PB_Compiler_Unicode = 1
                                hres=pclsObj\get(@tmp, 0, mem, 0, 0)
                        Else
                                hres=pclsObj\get(ansi2bstr(tmp), 0, mem, 0, 0)
                        EndIf
                       
                        type=PeekW(mem)
                       
                        Select type
                                Case 8
                                        val.s=PeekS(bstr2string(PeekL(mem+8)))
                                Case 3
                                        val.s=Str(PeekL(mem+8))
                                Default
                                        val.s=""
                        EndSelect
                        If FindString(WMIobj,"*",1) <> 0;we need everything, not just some specific properties
                                AddGadgetItem(0,-1,tmp+Chr(10)+val)
                        ElseIf Left(tmp,1)<>"_";we need some specific properties, not all, not these starting with '_'.
                                AddGadgetItem(0,-1,tmp+Chr(10)+val)
                        EndIf
                               
                EndIf
        Next
Until uReturn = 0

Как я понял именно здесь получаются данные.
Как это приспособить для получения параметров ком. строки по известному PID ума не приложу.

Нашел подобный код (Ссылка), вроде бы решающий мою задачу. Но он на C++ в синтаксисе которого ногу сломишь:

Помогите реализовать GetCommandLines(PID).

0

2

Код:
Procedure GetCommandLines()
  hr = 0
  WbemLocator.IWbemLocator
  WbemServices.IWbemServices
  EnumWbem.IEnumWbemClassObject
  
  ;Step 1: --------------------------------------------------
  ;Initialize COM. ------------------------------------------
  hr = CoInitializeEx_(0, #COINIT_MULTITHREADED);
  
  ;Step 2: --------------------------------------------------
  ;Set general COM security levels --------------------------
  ;Note: If you are using Windows 2000, you need To specify -
  ;the Default authentication credentials For a user by using
  ;a SOLE_AUTHENTICATION_LIST Structure in the pAuthList ----
  ;parameter of CoInitializeSecurity ------------------------
  hr = CoInitializeSecurity_(#Null, -1, #Null, #Null, #RPC_C_AUTHN_LEVEL_DEFAULT, #RPC_C_IMP_LEVEL_IMPERSONATE, #Null, #EOAC_NONE, #Null);
  
  ;Step 3: ---------------------------------------------------
  ;Obtain the initial locator To WMI -------------------------
  hr = CoCreateInstance_(?CLSID_WbemLocator, 0, #CLSCTX_INPROC_SERVER, ?IID_IWbemLocator, @WbemLocator);
  
  ;Step 4: -----------------------------------------------------
  ;Connect To WMI through the IWbemLocator::ConnectServer method
  hr = WbemLocator\ConnectServer(@"ROOT\CIMV2", #Null, #Null, #Null, 0, #Null, #Null, @WbemServices);
  
  ;Step 5: --------------------------------------------------
  ;Set security levels on the proxy -------------------------
  hr = CoSetProxyBlanket_(WbemServices, #RPC_C_AUTHN_WINNT, #RPC_C_AUTHZ_NONE, #Null, #RPC_C_AUTHN_LEVEL_CALL, #RPC_C_IMP_LEVEL_IMPERSONATE, #Null, #EOAC_NONE);
  
  ;Step 6: --------------------------------------------------
  ;Use the IWbemServices pointer To make requests of WMI ----
  hr = WbemServices\ExecQuery(@"WQL", @"SELECT ProcessId,CommandLine FROM Win32_Process", #WBEM_FLAG_FORWARD_ONLY, #Null, @EnumWbem);
  
  ;Step 7: -------------------------------------------------
  ;Get the Data from the query in Step 6 -------------------
  If EnumWbem <> #Null
    result.IWbemClassObject = #Null;
    returnedCount.l = 0            ;
    
    While EnumWbem\Next(#WBEM_INFINITE, 1, @result, @returnedCount) = #S_OK
      ProcessId.VARIANT;
      CommandLine.VARIANT;
      
      ;access the properties
      hr = result\Get(@"ProcessId", 0, @ProcessId, 0, 0);
      hr = result\Get(@"CommandLine", 0, @CommandLine, 0, 0);            
      If (Not (CommandLine\vt=#VT_NULL))
        ;wprintf(L"%u  %s \r\n", ProcessId.uintVal, CommandLine.bstrVal);
        Debug ""+ ProcessId\uintVal+"  "+CommandLine\bstrVal+"  "+PeekS(CommandLine\bstrVal)
      EndIf
      result\Release();
     Wend
  EndIf
  
  ;Cleanup
  ;========
  EnumWbem\Release();
  WbemServices\Release();
  WbemLocator\Release();
  
  CoUninitialize_();
  
  DataSection
    CLSID_WbemLocator:
    ;4590f811-1d3a-11d0-891f-00aa004b2e24
    Data.l $4590F811
    Data.w $1D3A, $11D0
    Data.b $89, $1F, $00, $AA, $00, $4B, $2E, $24
    IID_IWbemLocator:
    ;dc12a687-737f-11cf-884d-00aa004b2e24
    Data.l $DC12A687
    Data.w $737F, $11CF
    Data.b $88, $4D, $00, $AA, $00, $4B, $2E, $24
  EndDataSection
EndProcedure

GetCommandLines()

0

3

Пётр написал(а):

Уважаемый Петр, Вы сделали мой этот день светлым и праздничным. Процедура офигительная. То, что мне и надо. Проверил, работает с полтыка. Главное для меня не содержит избыточного функционала. Могу смело вставлять в свой основной модуль.

Вчера вечером наткнулся на рабочий интересный модуль, который и хотел использовать, под свои нужды. Самое короткое и удобное в применении готовое решение, которое я нашел самостоятельно. Оставлю здесь, вдруг кому либо пригодится (Ссылка):

Получение информации по отдельным WMI классам
Код:
;- WMI Intialisierung, Datenabruf und Deinitialisierung
; https://www.purebasic.fr/english/viewtopic.php?t=14764&highlight=wmi
; rewritten for PB4 and use as an "IncludeFile"
; save this code as "wmi.pbi"
; use it in your project with:
;
; includefile "wmi.pbi"
; WMI_INIT()
; WMI_Call("Select * FROM Win32_OperatingSystem", "Caption, CSDVersion, SerialNumber, RegisteredUser, Organization")
; ResetList(wmidata())
; While NextElement(wmidata())
;   Debug wmidata()  ; Alle Listenelemente darstellen / show all elements
; Wend
; WMI_RELEASE("OK")
;
;----------------------------------------------------------------------------------------------------------------
; Update für PB4 Final by ts-soft
; unnötige Konstanten und Structuren entfernt (sind in PB enthalten)
; voller Unicode support
; ---------------------------------------------------------------------------------------------------------------
;- KONSTANTEN  PROZEDUREN  STRUKTUREN

#COINIT_MULTITHREAD = 0
#RPC_C_AUTHN_LEVEL_CONNECT = 2
#RPC_C_IMP_LEVEL_IDENTIFY = 2
#EOAC_NONE = 0
#RPC_C_AUTHN_WINNT = 10
#RPC_C_AUTHZ_NONE = 0
#RPC_C_AUTHN_LEVEL_CALL = 3
#RPC_C_IMP_LEVEL_IMPERSONATE = 3
#CLSCTX_INPROC_SERVER = 1
#wbemFlagReturnImmediately = 16
#wbemFlagForwardOnly = 32
#IFlags = #wbemFlagReturnImmediately + #wbemFlagForwardOnly
;#WBEM_INFINITE = $FFFFFFFF
#WMISeparator = ","

Procedure StringToBStr(string$)
    Protected Unicode$ = Space(StringByteLength(string$, #PB_Unicode) + 1)
    Protected bstr_string
    PokeS(@Unicode$, String$, -1, #PB_Unicode)
    bstr_string = SysAllocString_(@Unicode$)
    ProcedureReturn bstr_string
EndProcedure

Procedure.s UniToPB(*Unicode)
    ProcedureReturn PeekS(*Unicode, #PB_Any, #PB_Unicode)
EndProcedure

Global txt$, loc.IWbemLocator, svc.IWbemServices, pEnumerator.IEnumWbemClassObject, pclsObj.IWbemClassObject, x.Variant, error
Global NewList wmidata.s()

Procedure.s wmi_release(dumdum$)
    ;- WMI Release
    svc\release()
    loc\release()
    pEnumerator\release()
    If error=0
        pclsObj\release()
    EndIf
    CoUninitialize_()
    If FindString(dumdum$, "ERROR", 1)
        MessageRequester("", dumdum$)
        End
    EndIf
EndProcedure

Procedure.s wmi_init()
    ;- WMI Initialize
    txt$=""
    CoInitializeEx_(0,#COINIT_MULTITHREAD)
    hres=CoInitializeSecurity_(0, -1,0,0,#RPC_C_AUTHN_LEVEL_CONNECT,#RPC_C_IMP_LEVEL_IDENTIFY,0,#EOAC_NONE,0)
    If hres <> 0: txt$="ERROR: unable To call CoInitializeSecurity": wmi_release(txt$): EndIf
    hres=CoCreateInstance_(?CLSID_WbemLocator,0,#CLSCTX_INPROC_SERVER,?IID_IWbemLocator,@loc.IWbemLocator)
    If hres <> 0: txt$="ERROR: unable To call CoCreateInstance": wmi_release(txt$): EndIf
    hres=loc\ConnectServer(StringToBStr("root\cimv2"),0,0,0,0,0,0,@svc.IWbemServices)
    If hres <> 0: txt$="ERROR: unable To call IWbemLocator::ConnectServer": wmi_release(txt$): EndIf
    hres=svc\queryinterface(?IID_IUnknown,@pUnk.IUnknown)
    hres=CoSetProxyBlanket_(svc,#RPC_C_AUTHN_WINNT,#RPC_C_AUTHZ_NONE,0,#RPC_C_AUTHN_LEVEL_CALL,#RPC_C_IMP_LEVEL_IMPERSONATE,0,#EOAC_NONE)
    If hres <> 0: txt$="ERROR: unable To call CoSetProxyBlanket": wmi_release(txt$): EndIf
    hres=CoSetProxyBlanket_(pUnk,#RPC_C_AUTHN_WINNT,#RPC_C_AUTHZ_NONE,0,#RPC_C_AUTHN_LEVEL_CALL,#RPC_C_IMP_LEVEL_IMPERSONATE,0,#EOAC_NONE)
    If hres <> 0: txt$="ERROR: unable To call CoSetProxyBlanket": wmi_release(txt$): EndIf
    pUnk\release()
    ProcedureReturn txt$
EndProcedure

Procedure.s WMI_Call(WMISelect.s, WMICommand.s)
    ;- Call Data
    ;OnErrorResume()
    error=0
    WMICommand=WMISelect+","+WMICommand
    ClearList(wmidata())
    k=CountString(WMICommand,#WMISeparator)
    Dim wmitxt$(k)
    For i=0 To k
        wmitxt$(i) = Trim(StringField(WMICommand,i+1,#WMISeparator))
    Next
    
    hres=svc\ExecQuery(StringToBStr("WQL"),StringToBStr(wmitxt$(0)), #IFlags,0,@pEnumerator.IEnumWbemClassObject)
    If hres <> 0: txt$="ERROR: unable To call IWbemServices::ExecQuery": wmi_release(txt$): EndIf
    hres=pEnumerator\reset()
    Repeat
        hres=pEnumerator\Next(#WBEM_INFINITE, 1, @pclsObj.IWbemClassObject, @uReturn)
        For i=1 To k
            Sleep_(0)
            If uReturn <> 0
                
                hres=pclsObj\get(StringToBStr(wmitxt$(i)), 0, @x.Variant, 0, 0)
                
                type=x\vt
                
                Select type
                        
                    Case 8200
                        val.s=""
                        nDim=SafeArrayGetDim_(x\lVal)
                        SafeArrayGetUBound_(x\lVal, nDim, @plUbound)
                        For z=0 To plUbound
                            SafeArrayGetElement_(x\lVal, @z, @rgVar)
                            val.s=val.s+", "+UniToPB(rgVar)
                        Next
                        val.s=Mid(val.s, 3, Len(val.s))
                        
                    Case 8195
                        val.s=""
                        nDim=SafeArrayGetDim_(x\scode)
                        SafeArrayGetUBound_(x\scode, nDim, @plUbound)
                        For z=0 To plUbound
                            SafeArrayGetElement_(x\scode, @z, @rgVar)
                            val.s=val.s + ", " +  Str(rgVar)
                        Next
                        val.s=Mid(val.s, 3, Len(val.s))
                        
                    Case 11
                        If x\boolVal=0
                            val.s="FALSE"
                        ElseIf x\boolVal=-1
                            val.s="TRUE"
                        EndIf
                        
                    Case 8
                        val.s=UniToPB(x\bstrVal)
                        
                    Case 3
                        val.s=Str(x\lVal)
                        
                    Case 1
                        val.s="n/a"
                        
                    Default
                        val.s=""
                        
                EndSelect
                
                If FindString(wmitxt$(i), "Date", 1) Or FindString(wmitxt$(i), "Time", 1)
                    AddElement(wmidata())
                    wmidata()=Mid(val, 7, 2)+"."+Mid(val, 5, 2)+"."+Mid(val, 1, 4)+" "+Mid(val, 9, 2)+":"+Mid(val, 11,2)+":"+Mid(val, 13,2) ;+Chr(10)+Chr(13)
                Else
                    AddElement(wmidata())
                    wmidata()=Trim(val) ;+Chr(10)+Chr(13)
                EndIf
            EndIf
        Next
        
    Until uReturn = 0
    If ListSize(wmidata())=0
        For i=1 To k
            AddElement(wmidata())
            wmidata()="n/a"
        Next
        error=1
    EndIf
    ProcedureReturn wmidata()
EndProcedure

;- Data Section
DataSection
    CLSID_IEnumWbemClassObject:
    ;1B1CAD8C-2DAB-11D2-B604-00104B703EFD
    Data.i $1B1CAD8C
    Data.w $2DAB, $11D2
    Data.b $B6, $04, $00, $10, $4B, $70, $3E, $FD
    IID_IEnumWbemClassObject:
    ;7C857801-7381-11CF-884D-00AA004B2E24
    Data.i $7C857801
    Data.w $7381, $11CF
    Data.b $88, $4D, $00, $AA, $00, $4B, $2E, $24
    CLSID_WbemLocator:
    ;4590f811-1d3a-11d0-891f-00aa004b2e24
    Data.i $4590F811
    Data.w $1D3A, $11D0
    Data.b $89, $1F, $00, $AA, $00, $4B, $2E, $24
    IID_IWbemLocator:
    ;dc12a687-737f-11cf-884d-00aa004b2e24
    Data.i $DC12A687
    Data.w $737F, $11CF
    Data.b $88, $4D, $00, $AA, $00, $4B, $2E, $24
    IID_IUnknown:
    ;00000000-0000-0000-C000-000000000046
    Data.i $00000000
    Data.w $0000, $0000
    Data.b $C0, $00, $00, $00, $00, $00, $00, $46
    
EndDataSection

WMI_INIT()
WMI_Call("Select * FROM Win32_Process", "Handle, CommandLine")
ResetList(wmidata())
While NextElement(wmidata())
    Debug wmidata()  ; Alle Listenelemente darstellen / show all elements
Wend
WMI_RELEASE("OK")

Но, несмотря на простоту использования, код его, в силу универсальности, слишком избыточен для моих нужд.
Большое спасибо за предложенное Вами решение.

Отредактировано kichrot (19.01.2021 15:12:51)

0

4

Пётр написал(а):

Уважаемый Петр, Ваша процедура свою функцию в моей программе выполняет отлично. Но, вызывает утечку памяти моей программы. Ставлю вместо процедуры заглушку, все нормально. Подключаю процедуру, при каждом ее вызове объем памяти, занимаемой моей программой в ОЗУ, увеличивается и суммируется.
Не могли бы Вы посмотреть, что не так с освобождением памяти в Вашей процедуре.
Заранее благодарю и извиняюсь за беспокойство.

0

5

Это не моя процедура, а переведенная с Си из первого сообщения.
Попробуйте добавить

Код:
SysFreeString_(CommandLine\bstrVal)

после строки

Код:
Debug ""+ ProcessId\uintVal+"  "+CommandLine\bstrVal+"  "+PeekS(CommandLine\bstrVal)

0

6

Пётр написал(а):

... Попробуйте добавить ...

Добавил. Вроде стало получше, но эффект остался.

Сегодня испытал реализации информации WMI из модуля COMatePLUS и библиотеки  Droopy.
Так там утечки памяти, при использовании WMI, еще больше, чем в предоставленной Вами процедуре.

Мне кажется, что тут два варианта: или механизм обращения к WMI изначально страдает утечкой памяти, или я эту утечку неправильно определяю.
Я смотрю на текущие значения для моего процесса:
- память (выделенный объем)
- память (частный рабочий объем)
- память (частные байты)
- память (рабочий набор)
По всем этим показателям объем памяти, занимаемой процессом моей программы, нарастает, по мере обращения к WMI, вне зависимости от реализации.
Может так и должно быть и я неверно интерпретирую и зря паникую???

Отредактировано kichrot (21.01.2021 16:30:39)

0

7

Оказалось, что проблема утечки памяти свойственна самому WMI. Жалоб очень много: Ссылка

Люди как то с этим борются. Например: Ссылка

Но, для PB я ни чего не нашел.

Уважаемый Петр, может быть Вы что либо придумаете? Или иные опытные участники форума, что либо подскажут?

0

8

Утечки памяти в WMI заставили продолжить поиск решения.
Нашел рабочее решение с использованием NtQueryInformationProcess (Ссылка).
Немного переделал под свои нужды. Выкладываю, вдруг кому либо пригодится:

Модуль получения командной строки чужого процесса по PID
Код:
; https://www.purebasic.fr/english/viewtopic.php?p=442019#p442019  Posted: Tue Apr 08, 2014 6:32 pm
; компилировать для 32-х и 64-х разрядных систем отдельно
Structure UNICODE_STRING Align #PB_Structure_AlignC
    Length.w
    MaximumLength.w
    Buffer.i
EndStructure

Structure RTL_DRIVE_LETTER_CURDIR Align #PB_Structure_AlignC
    Flags.w
    Length.w
    TimeStamp.l
    DosPath.UNICODE_STRING
EndStructure

Structure RTL_USER_PROCESS_PARAMETERS Align #PB_Structure_AlignC
    MaximumLength.l
    Length.l
    Flags.l
    DebugFlags.l
    ConsoleHandle.i
    ConsoleFlags.i
    StdInputHandle.i
    StdOutputHandle.i
    StdErrorHandle.i
    CurrentDirectoryPath.UNICODE_STRING
    CurrentDirectoryHandle.i
    DllPath.UNICODE_STRING
    ImagePathName.UNICODE_STRING
    CommandLine.UNICODE_STRING
    Environment.i
    StartingPositionLeft.l
    StartingPositionTop.l
    Width.l
    Height.l
    CharWidth.l
    CharHeight.l
    ConsoleTextAttributes.l
    WindowFlags.l
    ShowWindowFlags.l
    WindowTitle.UNICODE_STRING
    DesktopName.UNICODE_STRING
    ShellInfo.UNICODE_STRING
    RuntimeData.UNICODE_STRING
    DLCurrentDirectory.RTL_DRIVE_LETTER_CURDIR[$20]
EndStructure

Structure PEB Align #PB_Structure_AlignC
    InheritedAddressSpace.b
    ReadImageFileExecOptions.b
    BeingDebugged.b
    Spare.b
    Mutant.i
    ImageBaseAddress.i
    *LoaderData.PEB_LDR_DATA
    *ProcessParameters.RTL_USER_PROCESS_PARAMETERS
    SubSystemData.i
    ProcessHeap.i
    FastPebLock.i
    *FastPebLockRoutine.PEBLOCKROUTINE
    *FastPebUnlockRoutine.PEBLOCKROUTINE
    EnvironmentUpdateCount.l
    KernelCallbackTable.i
    EventLogSection.i
    EventLog.i
    *FreeList.PEB_FREE_BLOCK
    TlsExpansionCounter.l
    TlsBitmap.i
    TlsBitmapBits.l[$2]
    ReadOnlySharedMemoryBase.i
    ReadOnlySharedMemoryHeap.i
    ReadOnlyStaticServerData.i
    AnsiCodePageData.i
    OemCodePageData.i
    UnicodeCaseTableData.i
    NumberOfProcessors.l
    NtGlobalFlag.l
    Spare2.b[$4]
    CriticalSectionTimeout.LARGE_INTEGER
    HeapSegmentReserve.l
    HeapSegmentCommit.l
    HeapDeCommitTotalFreeThreshold.l
    HeapDeCommitFreeBlockThreshold.l
    NumberOfHeaps.l
    MaximumNumberOfHeaps.l
    ProcessHeaps.i
    GdiSharedHandleTable.i
    ProcessStarterHelper.i
    GdiDCAttributeList.i
    LoaderLock.i
    OSMajorVersion.l
    OSMinorVersion.l
    OSBuildNumber.l
    OSPlatformId.l
    ImageSubsystem.l
    ImageSubSystemMajorVersion.l
    ImageSubSystemMinorVersion.l
    GdiHandleBuffer.l[$22]
    PostProcessInitRoutine.l
    TlsExpansionBitmap.l
    TlsExpansionBitmapBits.b[$80]
    SessionId.l
EndStructure

Structure PROCESS_BASIC_INFORMATION Align #PB_Structure_AlignC
    ExitStatus.i
    *PebBaseAddress.PEB
    AffinityMask.i
    BasePriority.i
    UniqueProcessId.i
    InheritedFromUniqueProcessId.i
EndStructure

Procedure TestForError()
    dwMessageId = GetLastError_()
    
    If dwMessageId
        *lpBuffer = AllocateMemory(#MAX_PATH)
        FormatMessage_(#FORMAT_MESSAGE_FROM_SYSTEM, #Null, dwMessageId, #Null, *lpBuffer, #MAX_PATH, #Null)
        dwErrorMsg.s = Trim(PeekS(*lpBuffer, #MAX_PATH, #PB_Ascii))
        Debug "-- Error: " + Str(dwMessageId) + " - " + Left(dwErrorMsg, Len(dwErrorMsg) - 2)
        FreeMemory(*lpBuffer)
    EndIf
EndProcedure

Procedure.b AdjustProcessPrivilege()
    Protected Result.b = #False
    
    If OpenProcessToken_(GetCurrentProcess_(), #TOKEN_ADJUST_PRIVILEGES | #TOKEN_QUERY, @TokenHandle)
        lpLuid.LUID
        
        If LookupPrivilegeValue_(#Null, #SE_DEBUG_NAME, @lpLuid)
            NewState.TOKEN_PRIVILEGES
            
            With NewState
                \PrivilegeCount = 1
                \Privileges[0]\Luid\LowPart = lpLuid\LowPart
                \Privileges[0]\Luid\HighPart = lpLuid\HighPart
                \Privileges[0]\Attributes = #SE_PRIVILEGE_ENABLED
            EndWith
            Result = AdjustTokenPrivileges_(TokenHandle, #False, @NewState, SizeOf(TOKEN_PRIVILEGES), @PreviousState.TOKEN_PRIVILEGES, @ReturnLength)
        EndIf
        CloseHandle_(TokenHandle)
    EndIf
    ProcedureReturn Result
EndProcedure

Procedure GetPBI(hProcess)
    Protected Result = #Null
    #ProcessBasicInformation = 0
    Protected pbi.PROCESS_BASIC_INFORMATION
    
    If Not NtQueryInformationProcess_(hProcess, #ProcessBasicInformation, @pbi, SizeOf(pbi), @ReturnLength)
        If pbi\PebBaseAddress
            Result = pbi\PebBaseAddress
        EndIf
    EndIf
    ProcedureReturn Result
EndProcedure

Procedure GetPEB(hProcess, PebBaseAddress)
    Protected Result = #Null
    Protected peb.PEB
    
    If ReadProcessMemory_(hProcess, PebBaseAddress, @peb, SizeOf(PEB), #Null)
        If peb\ProcessParameters
            Result = peb\ProcessParameters
        EndIf
    EndIf
    ProcedureReturn Result
EndProcedure

Procedure.s GetCMD(hProcess, ProcessParameters)
    Protected Result.s = ""
    Protected rtl.RTL_USER_PROCESS_PARAMETERS
    ZeroMemory_(@rtl, SizeOf(rtl))
    
    If ReadProcessMemory_(hProcess, ProcessParameters, @rtl, SizeOf(rtl), #Null)
        If rtl\CommandLine\Buffer
            *CmdLine = AllocateMemory(rtl\CommandLine\MaximumLength)
            
            If ReadProcessMemory_(hProcess, rtl\CommandLine\Buffer, *CmdLine, rtl\CommandLine\MaximumLength, #Null)
                Result = PeekS(*CmdLine, rtl\CommandLine\MaximumLength, #PB_Unicode)
            EndIf
            FreeMemory(*CmdLine)
        EndIf
    EndIf
    ProcedureReturn Result
EndProcedure

Procedure.s NQIP_GetCommandLine(PID)
    hSnapshot = CreateToolhelp32Snapshot_(#TH32CS_SNAPPROCESS, #Null)
    If hSnapshot
        ProcEntry.PROCESSENTRY32
        ProcEntry\dwSize = SizeOf(PROCESSENTRY32)
        If Process32First_(hSnapshot, @ProcEntry)
            While Process32Next_(hSnapshot, @ProcEntry)
                AdjustProcessPrivilege()
                dwProcessId = ProcEntry\th32ProcessID
                If PID=dwProcessId
                    hProcess = OpenProcess_(#PROCESS_QUERY_INFORMATION | #PROCESS_VM_READ, #False, dwProcessId)
                    If hProcess
                        Protected pbi.PROCESS_BASIC_INFORMATION
                        ZeroMemory_(@pbi, SizeOf(pbi))
                        pbi\PebBaseAddress = GetPBI(hProcess)
                        Protected peb.PEB
                        ZeroMemory_(@peb, SizeOf(PEB))
                        peb\ProcessParameters = GetPEB(hProcess, pbi\PebBaseAddress)
                        CommandLine.s = GetCMD(hProcess, peb\ProcessParameters)
                        If CommandLine <>""
                            CloseHandle_(hProcess)
                            ProcedureReturn Trim(CommandLine)            
                            ;Debug Str(dwProcessId)+"  "+CommandLine : 
                        Else 
                            TestForError()  
                        EndIf
                    EndIf
                EndIf
            Wend
        EndIf
        CloseHandle_(hSnapshot)
    EndIf
EndProcedure
; Debug NQIP_GetCommandLine(вставить реальный PID для теста)

С данным модулем проблем утечки памяти нет.
Единственное неудобство в том, что для 32-х и 64-х разрядных систем следует компилировать отдельно.
На последней версии 64-х разрядной версии WINDOWS10 работает. Компилировал на PB 5.72.
Уважаемому Петру большое спасибо за помощь.

Отредактировано kichrot (21.01.2021 21:39:27)

0

9

После добавления SysFreeString утечки памяти не наблюдается.

0

10

Пётр написал(а):

После добавления SysFreeString утечки памяти не наблюдается.

Как мне не жаль, но у меня наблюдается, несмотря на выполнение Вашей рекомендации.
Люди в интернете пишут, что WMI вызывает утечки памяти на разных версиях ОС по разному. Встречал сообщения, что даже на одой версии ОС, но на разных машинах, ситуация с утечкой памяти WMI разная.
Майкрософт несколько раз выпускал по этому поводу патчи, но видимо воз и ныне там.
Вам помогло, а мне не повезло.
Видимо процедуры на основе WMI не следует использовать для проверок в цикле, как это реализуется у меня. В иных случаях небольшой утечкой памяти можно было бы и пренебречь и даже не заметить.

0


Вы здесь » PureBasic - форум » Вопросы по PureBasic » Как получить параметры командной строки чужого процесса?