2012-11-19 54 views
1

我正在嘗試重新編寫一個邏輯,這個邏輯已經在批處理腳本中寫入了一個C++代碼和一個DLL。在C++代碼中調用WMIC命令

在我的批處理腳本中,我正在使用WMIC檢查所有java進程的命令行參數。這裏是腳本 -

FOR /F "tokens=*" %%A IN ('2^>nul wmic process where^(name^="java.exe"^) get commandline ^| Findstr "XYZ"') DO SET Var=%%A 
IF DEFINED Var (
cscript MessageBox.vbs "Message IN POP-UP." 
GOTO :EOF 
) 
FOR /F "tokens=*" %%A IN ('2^>nul wmic process where^(name^="javaw.exe"^) get commandline ^| Findstr "XYZ"') DO SET Var=%%A 
IF DEFINED Var (
cscript MessageBox.vbs "Message IN POP-UP." 
GOTO :EOF 
) 

我想重新使用相同的WMIC邏輯,但現在在c + +代碼。基本上我想避免使用vb scipt彈出,我將使用一些C++命令將「彈出消息」稱爲「消息」。

任何出發點??我可以使用system()調用,但是接下來我將如何執行像在批處理腳本中的IF條件中寫入的檢查。

+0

爲什麼代碼重複 –

+0

代碼不重複...我正在檢查一次爲java和一次爲javaw .. – ayush

回答

4

不用從C++執行WMIC應用程序,您可以直接使用COM訪問WMI。試試這個示例應用。

#include "stdafx.h" 
#define _WIN32_DCOM 
#include <iostream> 
using namespace std; 
#include <comdef.h> 
#include <Wbemidl.h> 
# pragma comment(lib, "wbemuuid.lib") 

//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(
      _bstr_t(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(
      _bstr_t(strNetworkResource), // Object path of WMI namespace 
      _bstr_t(pszName),    // User name 
      _bstr_t(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 * FROM Win32_Process Where Name='java.exe'", 
    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 
        wcout << "CommandLine : " << vtProp.bstrVal << 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. 
} 
+0

使用COM將是最好的方法,但不幸的是我想工作在一個已知的框架。 COM將是全新的。你能建議我如何開始使用C++。 – ayush

0

對於容易,但醜陋的解決方法,你可以嘗試「按文件」 使用WMIC通過查詢,與控制檯的工作。

注意,它會在您每次執行新的系統時間顯示控制檯()命令

所以你用系統(「在WMIC> youroutputfile.format您的查詢」),並通過你的C++

檢索

system("wmic csproduct get name, identifyingnumber, uuid > c:\Temp\test.test"); wstring Return = MyReadingClass(L"c:\\Temp\\test.test").Read();

01:

你也可以,如果你的查詢是更復雜一點

的例子在這裏執行批處理文件

wmic爲您提供簡單,這是您應該首先尋求的。

這種方法非常簡單明瞭,但由於HDD限制+寫入/讀取操作+系統安全操作,對於實時進程非常緩慢。