通過WMI擷取網卡MAC地址、硬碟序號、主板序號、CPU ID、BIOS序號

來源:互聯網
上載者:User

標籤:

   最近由於項目的需要,需要在程式中擷取機器的硬碟序號和MAC地址等資訊,在C#下,可以很容易的獲得這些資訊,但是在C++程式中感覺比較麻煩。經過百度,發現很多大蝦都是通過WMI來擷取這些硬體資訊的,網上也有相關的代碼,通過實際調試,也發現確實可以通過WMI來擷取這些資訊。前兩天,在網上突然搜到一位大牛寫的比較完整的程式,為了以後使用方便,就轉載記錄一下。同時,也會在大牛的代碼中增加一些自己的注釋,都是自己在實際使用過程中遇到的問題。

#define _WIN32_DCOM

#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string>
#include "direct.h"
#include <tchar.h>
#include <time.h>
#include <comdef.h>
#include <Wbemidl.h>
#include <conio.h>
#include "atlstr.h"
#include "atlbase.h"
//#include "TcpCtl.h"
//#include "winsock2.h"
//#include "InitDll.h"
using namespace std;

# pragma comment(lib, "wbemuuid.lib")
# pragma comment(lib, "ws2_32.lib")

//通過WMI擷取主板號
BOOL ManageWMIBord(char bord[])
{
HRESULT hres;
// Step 1:  初始化COM 
//hres = CoInitializeEx(0, COINIT_MULTITHREADED); //網上的代碼都是使用這行語句進行初始化,但是我在實際使用中,發現也可以採用下面的語句進行初始化
hres = CoInitialize(0);

//網上的代碼是沒有注釋下面這個判斷的,但是實際使用中發現,如果之前已經初始化成功了,在第二次初始化的時候,下面的代碼就會導致返回false,所以,實際使用中我就注釋掉了
//if (FAILED(hres))
//{
// cout << "Failed to initialize COM library. Error code = 0x"
// << hex << hres << endl;
// return false; // Program has failed.
//}


// Step 2:  設定COM的安全認證層級  

//在實際使用過程中,我發現如果這一步不注釋掉的話,程式總是返回false,注釋掉之後程式反而可以正常運行,原因未知

// 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 ------------------------
////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
//// );
////
////if (FAILED(hres))
////{
//// cout << "Failed to initialize security. Error code = 0x"
//// << hex << hres << endl;
//// CoUninitialize();
//// return false; // Program has failed.
////}

// Step 3:  獲得WMI串連COM介面  
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;
CoUninitialize();
return false; // Program has failed.
}


// Step 4:  通過串連介面串連WMI的核心對象名"ROOT//CIMV2"  
IWbemServices *pSvc = NULL;

hres = pLoc->ConnectServer(

_bstr_t(L"ROOT\\CIMV2"), // 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
);

if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x"
<< hex << hres << endl;
pLoc->Release();
CoUninitialize();
return false; // Program has failed.
}
//cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;

// Step 5:  佈建要求代理的安全層級   
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
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return false; // Program has failed.
}
// Step 6: 通過請求代理來向WMI發送請求----
// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
//bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = ‘TRUE‘"),
bstr_t("SELECT * FROM Win32_BaseBoard"),//只需要通過修改這裡的查詢語句,就可以實現對MAC地址等其他資訊的查詢
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);

if (FAILED(hres))
{
cout << "Query for Network Adapter Configuration failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return false; // Program has failed.
}


// Step 7:  迴圈枚舉所有的結果對象

IWbemClassObject *pclsObj;
ULONG uReturn = 0;

while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
VARIANT vtProp;
VariantInit(&vtProp);

hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);//查詢不同的硬體資訊,除了修改上面的查詢語句,這裡的欄位也要修改

if(!FAILED(hr))
{
CW2A tmpstr1(vtProp.bstrVal);
strcpy_s(bord,200,tmpstr1);//這裡的200是可調的,自己根據實際情況設定,但是肯定不能大於bord的長度
//cout << "BordSN:" << sn << endl;

}

VariantClear(&vtProp);
}//end while

// 釋放資源  
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
pclsObj->Release();
CoUninitialize();
return true; // Program successfully completed.

}

 

附:

// WQL查詢語句
const T_WQL_QUERY szWQLQuery[] = {
// 網卡原生MAC地址
"SELECT * FROM Win32_NetworkAdapter WHERE (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE ‘ROOT%‘))",
L"PNPDeviceID",

// 硬碟序號
"SELECT * FROM Win32_DiskDrive WHERE (SerialNumber IS NOT NULL) AND (MediaType LIKE ‘Fixed hard disk%‘)",
L"SerialNumber",

// 主板序號
"SELECT * FROM Win32_BaseBoard WHERE (SerialNumber IS NOT NULL)",
L"SerialNumber",

// 處理器ID
"SELECT * FROM Win32_Processor WHERE (ProcessorId IS NOT NULL)",
L"ProcessorId",

// BIOS序號
"SELECT * FROM Win32_BIOS WHERE (SerialNumber IS NOT NULL)",
L"SerialNumber",

// 主板型號
"SELECT * FROM Win32_BaseBoard WHERE (Product IS NOT NULL)",
L"Product",

// 網卡當前MAC地址
"SELECT * FROM Win32_NetworkAdapter WHERE (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE ‘ROOT%‘))",
L"MACAddress",

//當前機器的型號和廠商

"SELECT * FROM Win32_computersystem",

L"Manufacturer",L"Model"


}

(轉)通過WMI擷取網卡MAC地址、硬碟序號、主板序號、CPU ID、BIOS序號

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.