c - Få kommandolinjeparametrene for en anden proces i Windows

Indlæg af Hanne Mølgaard Plasc

Problem



Hvordan får jeg kommandolinjeparametrene for alle kørende processer i Windows ved hjælp af WMI på C-sproget?

Bedste reference


Du skal bruge Win32\_Process WMI-klassen og kontrollere værdien af ​​egenskaben CommandLine. Se også på denne artikel How do I get the command line of another process, der forklarer at streng er ...just "preinitialized variable", a process could in principle (and many do in practice, although usually inadvertently) write to the memory that holds the command line [6] [7]


Opdater


C Prøve



#define \_WIN32\_WINNT 0x0400
#define \_WIN32\_DCOM

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <wbemidl.h>

void \_tmain(int argc, \_TCHAR* argv[])
{
    HRESULT hr = 0;
    IWbemLocator         *WbemLocator  = NULL;
    IWbemServices        *WbemServices = NULL;
    IEnumWbemClassObject *EnumWbem  = NULL;

    //initializate the Windows security
    hr = CoInitializeEx(0, COINIT\_MULTITHREADED);
    hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC\_C\_AUTHN\_LEVEL\_DEFAULT, RPC\_C\_IMP\_LEVEL\_IMPERSONATE, NULL, EOAC\_NONE, NULL);

    hr = CoCreateInstance(&CLSID\_WbemLocator, 0, CLSCTX\_INPROC\_SERVER, &IID\_IWbemLocator, (LPVOID *) &WbemLocator);
    //connect to the WMI
    hr = WbemLocator->lpVtbl->ConnectServer(WbemLocator, L"ROOT\CIMV2", NULL, NULL, NULL, 0, NULL, NULL, &WbemServices);   
    //Run the WQL Query
    hr = WbemServices->lpVtbl->ExecQuery(WbemServices, L"WQL", L"SELECT ProcessId,CommandLine FROM Win32\_Process", WBEM\_FLAG\_FORWARD\_ONLY, NULL, &EnumWbem);

    // Iterate over the enumerator
    if (EnumWbem != NULL) {
        IWbemClassObject *result = NULL;
        ULONG returnedCount = 0;

        while((hr = EnumWbem->lpVtbl->Next(EnumWbem, WBEM\_INFINITE, 1, &result, &returnedCount)) == S\_OK) {
            VARIANT ProcessId;
            VARIANT CommandLine;

            // access the properties
            hr = result->lpVtbl->Get(result, L"ProcessId", 0, &ProcessId, 0, 0);
            hr = result->lpVtbl->Get(result, L"CommandLine", 0, &CommandLine, 0, 0);            
            if (!(CommandLine.vt==VT\_NULL))
            wprintf(L"\%u  \%s 
", ProcessId.uintVal, CommandLine.bstrVal);

            result->lpVtbl->Release(result);
        }
    }

    // Release the resources
    EnumWbem->lpVtbl->Release(EnumWbem);
    WbemServices->lpVtbl->Release(WbemServices);
    WbemLocator->lpVtbl->Release(WbemLocator);

    CoUninitialize();    
    getchar();
}


Borland C ++ Sample



#pragma hdrstop
#include <iostream>
using namespace std;
#include <wbemcli.h>
#include <comdef.h> 

//CREDENTIAL structure
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788\%28v=vs.85\%29.aspx
#define CRED\_MAX\_USERNAME\_LENGTH            513
#define CRED\_MAX\_CREDENTIAL\_BLOB\_SIZE       512
#define CREDUI\_MAX\_USERNAME\_LENGTH CRED\_MAX\_USERNAME\_LENGTH
#define CREDUI\_MAX\_PASSWORD\_LENGTH (CRED\_MAX\_CREDENTIAL\_BLOB\_SIZE / 2)

// The Win32\_Process class represents a sequence of events on a Win32 system. Any sequence consisting of the interaction of one or more processors or interpreters, some executable code, and a set of inputs, is a descendent (or member) of this class.
// Example: A client application running on a Win32 system.

#pragma argsused
int main(int argc, char* argv[])
{
    wchar\_t pszName[CREDUI\_MAX\_USERNAME\_LENGTH+1] = L"user";
    wchar\_t pszPwd[CREDUI\_MAX\_PASSWORD\_LENGTH+1]  = L"password";
    BSTR strNetworkResource;
    //To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource
    bool localconn = true;  
    strNetworkResource = localconn ?  L"\\.\root\CIMV2" : L"\\remote--machine\root\CIMV2";

    COAUTHIDENTITY *userAcct =  NULL ;
    COAUTHIDENTITY authIdent;

    // Initialize COM. ------------------------------------------

    HRESULT hres;
    hres =  CoInitializeEx(0, COINIT\_MULTITHREADED);
    if (FAILED(hres))
    {
        cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
        cout << \_com\_error(hres).ErrorMessage() << endl;
        cout << "press enter to exit" << endl;
        cin.get();      
        return 1;                  // Program has failed.
    }

    // Set general COM security levels --------------------------

    if (localconn)
        hres =  CoInitializeSecurity(
            NULL,
            -1,                          // COM authentication
            NULL,                        // Authentication services
            NULL,                        // Reserved
            RPC\_C\_AUTHN\_LEVEL\_DEFAULT,   // Default authentication
            RPC\_C\_IMP\_LEVEL\_IMPERSONATE, // Default Impersonation
            NULL,                        // Authentication info
            EOAC\_NONE,                   // Additional capabilities
            NULL                         // Reserved
            );
    else
        hres =  CoInitializeSecurity(
            NULL,
            -1,                          // COM authentication
            NULL,                        // Authentication services
            NULL,                        // Reserved
            RPC\_C\_AUTHN\_LEVEL\_DEFAULT,   // Default authentication
            RPC\_C\_IMP\_LEVEL\_IDENTIFY,    // Default Impersonation
            NULL,                        // Authentication info
            EOAC\_NONE,                   // Additional capabilities
            NULL                         // Reserved
            );

    if (FAILED(hres))
    {
        cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl;
        cout << \_com\_error(hres).ErrorMessage() << endl;
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();      
        return 1;                    // Program has failed.
    }

    // Obtain the initial locator to WMI -------------------------

    IWbemLocator *pLoc = NULL;
    hres = CoCreateInstance(CLSID\_WbemLocator, 0, CLSCTX\_INPROC\_SERVER, IID\_IWbemLocator, (LPVOID *) &pLoc);

    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object." << " Err code = 0x" << hex << hres << endl;
        cout << \_com\_error(hres).ErrorMessage() << endl;
        CoUninitialize();       
        cout << "press enter to exit" << endl;
        cin.get();      
        return 1;                 // Program has failed.
    }

    // Connect to WMI through the IWbemLocator::ConnectServer method

    IWbemServices *pSvc = NULL;

    if (localconn)  
        hres = pLoc->ConnectServer(
             strNetworkResource,      // Object path of WMI namespace
             NULL,                    // User name. NULL = current user
             NULL,                    // User password. NULL = current
             0,                       // Locale. NULL indicates current
             NULL,                    // Security flags.
             0,                       // Authority (e.g. Kerberos)
             0,                       // Context object
             &pSvc                    // pointer to IWbemServices proxy
             );
    else
        hres = pLoc->ConnectServer(
            strNetworkResource,  // Object path of WMI namespace
            pszName,             // User name
            pszPwd,              // User password
            NULL,                // Locale
            NULL,                // Security flags
            NULL,                // Authority
            NULL,                // Context object
            &pSvc                // IWbemServices proxy
            );

    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" << hex << hres << endl;    
        cout << \_com\_error(hres).ErrorMessage() << endl;
        pLoc->Release();
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();          
        return 1;                // Program has failed.
    }

    cout << "Connected to root\CIMV2 WMI namespace" << endl;

    // Set security levels on the proxy -------------------------
    if (localconn)
        hres = CoSetProxyBlanket(
           pSvc,                        // Indicates the proxy to set
           RPC\_C\_AUTHN\_WINNT,           // RPC\_C\_AUTHN\_xxx
           RPC\_C\_AUTHZ\_NONE,            // RPC\_C\_AUTHZ\_xxx
           NULL,                        // Server principal name
           RPC\_C\_AUTHN\_LEVEL\_CALL,      // RPC\_C\_AUTHN\_LEVEL\_xxx
           RPC\_C\_IMP\_LEVEL\_IMPERSONATE, // RPC\_C\_IMP\_LEVEL\_xxx
           NULL,                        // client identity
           EOAC\_NONE                    // proxy capabilities
        );
    else
    {
        // Create COAUTHIDENTITY that can be used for setting security on proxy
        memset(&authIdent, 0, sizeof(COAUTHIDENTITY));
        authIdent.PasswordLength = wcslen (pszPwd);
        authIdent.Password = (USHORT*)pszPwd;
        authIdent.User = (USHORT*)pszName;
        authIdent.UserLength = wcslen(pszName);
        authIdent.Domain = 0;
        authIdent.DomainLength = 0;
        authIdent.Flags = SEC\_WINNT\_AUTH\_IDENTITY\_UNICODE;
        userAcct = &authIdent;

        hres = CoSetProxyBlanket(
           pSvc,                           // Indicates the proxy to set
           RPC\_C\_AUTHN\_DEFAULT,            // RPC\_C\_AUTHN\_xxx
           RPC\_C\_AUTHZ\_DEFAULT,            // RPC\_C\_AUTHZ\_xxx
           COLE\_DEFAULT\_PRINCIPAL,         // Server principal name
           RPC\_C\_AUTHN\_LEVEL\_PKT\_PRIVACY,  // RPC\_C\_AUTHN\_LEVEL\_xxx
           RPC\_C\_IMP\_LEVEL\_IMPERSONATE,    // RPC\_C\_IMP\_LEVEL\_xxx
           userAcct,                       // client identity
           EOAC\_NONE                       // proxy capabilities
        );
    }

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
        cout << \_com\_error(hres).ErrorMessage() << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();      
        return 1;               // Program has failed.
    }

    // Use the IWbemServices pointer to make requests of WMI ----

    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery( L"WQL", L"SELECT CommandLine,ProcessId  FROM Win32\_Process",
    WBEM\_FLAG\_FORWARD\_ONLY | WBEM\_FLAG\_RETURN\_IMMEDIATELY, NULL, &pEnumerator);

    if (FAILED(hres))
    {
        cout << "ExecQuery failed" << " Error code = 0x"    << hex << hres << endl;
        cout << \_com\_error(hres).ErrorMessage() << endl;
        pSvc->Release();
        pLoc->Release();
        CoUninitialize();
        cout << "press enter to exit" << endl;
        cin.get();      
        return 1;               // Program has failed.
    }

    // Secure the enumerator proxy
    if (!localconn)
    {

        hres = CoSetProxyBlanket(
            pEnumerator,                    // Indicates the proxy to set
            RPC\_C\_AUTHN\_DEFAULT,            // RPC\_C\_AUTHN\_xxx
            RPC\_C\_AUTHZ\_DEFAULT,            // RPC\_C\_AUTHZ\_xxx
            COLE\_DEFAULT\_PRINCIPAL,         // Server principal name
            RPC\_C\_AUTHN\_LEVEL\_PKT\_PRIVACY,  // RPC\_C\_AUTHN\_LEVEL\_xxx
            RPC\_C\_IMP\_LEVEL\_IMPERSONATE,    // RPC\_C\_IMP\_LEVEL\_xxx
            userAcct,                       // client identity
            EOAC\_NONE                       // proxy capabilities
            );

        if (FAILED(hres))
        {
            cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl;
            cout << \_com\_error(hres).ErrorMessage() << endl;
            pEnumerator->Release();
            pSvc->Release();
            pLoc->Release();
            CoUninitialize();
            cout << "press enter to exit" << endl;
            cin.get();              
            return 1;               // Program has failed.
        }
    }

    // Get the data from the WQL sentence
    IWbemClassObject *pclsObj = NULL;
    ULONG uReturn = 0;

    while (pEnumerator)
    {
        HRESULT hr = pEnumerator->Next(WBEM\_INFINITE, 1, &pclsObj, &uReturn);

        if(0 == uReturn || FAILED(hr))
          break;

        VARIANT vtProp;

                hr = pclsObj->Get(L"CommandLine", 0, &vtProp, 0, 0);// String
                if (!FAILED(hr))
                {
                  if ((vtProp.vt==VT\_NULL) || (vtProp.vt==VT\_EMPTY))
                    wcout << "CommandLine : " << ((vtProp.vt==VT\_NULL) ? "NULL" : "EMPTY") << endl;
                  else
                  if ((vtProp.vt & VT\_ARRAY))
                    wcout << "CommandLine : " << "Array types not supported (yet)" << endl;
                  else
                    wcout << "CommandLine : " << vtProp.bstrVal << endl;
                }
                VariantClear(&vtProp);

                hr = pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);// Uint32
                if (!FAILED(hr))
                {
                  if ((vtProp.vt==VT\_NULL) || (vtProp.vt==VT\_EMPTY))
                    wcout << "ProcessId : " << ((vtProp.vt==VT\_NULL) ? "NULL" : "EMPTY") << endl;
                  else
                  if ((vtProp.vt & VT\_ARRAY))
                    wcout << "ProcessId : " << "Array types not supported (yet)" << endl;
                  else
                    wcout << "ProcessId : " << vtProp.uintVal << endl;
                }
                VariantClear(&vtProp);


        pclsObj->Release();
        pclsObj=NULL;
    }

    // Cleanup

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    if (pclsObj!=NULL)
     pclsObj->Release();

    CoUninitialize();
    cout << "press enter to exit" << endl;
    cin.get();
    return 0;   // Program successfully completed.
}