如何检测Windows Server 2019?(C++)

12
微软于2018年10月2日发布了Windows Server 2019。从Windows 2000版本到这个版本,你可以调用WinAPI函数GetVersionEx并使用结构体OSVERSIONINFOEX,根据dwMajorVersiondwMinorVersionwProductType的变量来确定Windows版本,例如Windows 8.1、Windows 10、Windows Server 2012 R2等。大家通常使用的代码类似于:
OSVERSIONINFOEX osvi;
SecureZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (GetVersionEx(&osvi)) {
    if (osvi.dwMajorVersion == 10 &&
        osvi.dwMinorVersion == 0 &&
        osvi.wProductType != VER_NT_WORKSTATION) {
            Console->Log("We are running on Windows Server 2016");
        }
}

根据维基百科的说法,Windows Server 2019与Server 2016具有相同的NT 10.0版本号。因此上述代码不再起作用。
此外,Microsoft Docs包含以下注释:GetVersionEx可能在Windows 8.1之后的版本中被更改或不可用。请改用Version Helper函数。 不幸的是,Version Helper函数没有一个函数可以检测Server 2019。而且奇怪的是,关于Targeting的Docs页面仅涵盖了Windows 10,并未讨论Server版本,尽管这些Targeting清单对于检测高于Windows 8.1或Server 2012的OS是强制性的。 更新1。由于@IInspectable和@RbMm评论了RtlGetVersion函数的使用。因此,我运行了以下代码(取自此答案):
typedef LONG NTSTATUS, *PNTSTATUS;
#define STATUS_SUCCESS (0x00000000)

typedef NTSTATUS (WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);

RTL_OSVERSIONINFOW GetRealOSVersion() {
    HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
    if (hMod) {
        RtlGetVersionPtr fxPtr = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
        if (fxPtr != nullptr) {
            RTL_OSVERSIONINFOW rovi = { 0 };
            rovi.dwOSVersionInfoSize = sizeof(rovi);
            if ( STATUS_SUCCESS == fxPtr(&rovi) ) {
                return rovi;
            }
        }
    }
    RTL_OSVERSIONINFOW rovi = { 0 };
    return rovi;
}

以下是Windows 10的结果:

  • dwMajorVersion = 10
  • dwMinorVersion = 0
  • dwBuildNumber = 17134
  • dwPlatformId = 2

Windows Server 2019:

  • dwMajorVersion = 10
  • dwMinorVersion = 0
  • dwBuildNumber = 17763
  • dwPlatformId = 2

更新2。 根据要求,发布了通过包含所有目标直到Windows 10的清单文件进行的GetVersionEx调用获得的OSVERSIONINFOEX结构的完整信息(请参见上面的目标链接):

// Windows 10
osvi.dwOSVersionInfoSize = 284
osvi.dwMajorVersion = 10
osvi.dwMinorVersion = 0
osvi.dwBuildNumber = 17134
osvi.dwPlatformId = 2
osvi.szCSDVersion =
osvi.wServicePackMinor = 0
osvi.wServicePackMinor = 0
osvi.wSuiteMask = 256  // 0x100
osvi.wProductType = 1
osvi.wReserved = 0

// Windows Server 2016
osvi.dwOSVersionInfoSize = 284
osvi.dwMajorVersion = 10
osvi.dwMinorVersion = 0
osvi.dwBuildNumber = 14393
osvi.dwPlatformId = 2
osvi.szCSDVersion =
osvi.wServicePackMinor = 0
osvi.wServicePackMinor = 0
osvi.wSuiteMask = 400
osvi.wProductType = 3
osvi.wReserved = 0

// Windows Server 2019
osvi.dwOSVersionInfoSize = 284
osvi.dwMajorVersion = 10
osvi.dwMinorVersion = 0
osvi.dwBuildNumber = 17763
osvi.dwPlatformId = 2
osvi.szCSDVersion =
osvi.wServicePackMinor = 0
osvi.wServicePackMinor = 0
osvi.wSuiteMask = 400  // 0x190
osvi.wProductType = 3
osvi.wReserved = 0

更新3。 使用结构体RTL_OSVERSIONINFOEXW调用RtlGetVersion,我们得到与更新2完全相同的结果。


1
当检测Windows 10版本并传递OSVERSIONINFOEX结构时,您会得到什么值? - IInspectable
1
应注意的是,通常情况下不应检测版本,而应检查所需功能是否可用 - 例如,如果需要使用仅在某些操作系统上可用的API,请使用“ GetProcAddress”来查看是否提供该API,而不是测试Windows版本。 - Matteo Italia
1
@MatteoItalia,我在哪里写了我需要检测“实际功能”?有许多原因可以想要检测操作系统版本,包括预填表单错误/崩溃报告。不,这不是我提出问题的原因。 - Maris B.
3
你只发布了 OSVERSIONINFO 结构的结果。相应地初始化一个 OSVERSIONINFOEX 结构并传递它。该结构具有额外的成员,可以存储您正在寻找的信息。Matteo 提出了一个有效的观点:如果您计划根据运行代码的操作系统版本做出运行时决策,最好测试功能而不是版本。另一方面,如果你需要这个信息来进行诊断,那么这样做没有任何问题。 - IInspectable
1
这是一个服务器,你可以通过 wProductType == VER_NT_SERVER 来检测,但具体是哪种类型的服务器,只能根据 dwBuildNumber 确定。 - RbMm
显示剩余11条评论
5个回答

2
根据在Windows Server 2019版本信息中的讨论:

[Windows] Server 2019数据中心版build 17744,ReleaseId字段显示为1809。

因此,可以使用类似以下的内容来解决问题: "最初的回答"。
const auto isWinServer2019Plus =
  IsWindowsServer() &&
  IsWindowsVersionOrGreater(10, 0, 1803);

1803这个数字从哪里来? - Maris B.
从这个链接中:https://techcommunity.microsoft.com/t5/Windows-Server-Insiders/Windows-Server-2019-version-info/td-p/234472@MarisB。 - NuSkooler

1
除了检查MajorVersionMinorVersionProductType之外,您还需要检查ReleaseIdBuildNumberReleaseId: 1809BuildNumber: 17763Windows Server 2019Windows Server, version 1809发布版本相关联。因此,通过检查这些数字,您应该至少确定您正在处理Windows Server 2019Windows Server,version 1809(半年频道)(数据中心核心,标准核心)

enter image description here

请参阅:Windows Server 发布信息

注意:Windows Server 2019 的 Insider Preview 构建可能具有 ReleaseId 1803 或 BuildNumbers 低于 17763。


此帖子中,微软的Mary Hoffman说:

ReleaseId

1809与Windows Server 2019和Windows Server版本1809相关。 (文章)

Windows Server 2016将始终为1607。一旦产品发布,该ID将不会更改。 (文章)

按照这个逻辑,Windows Server 2019也将始终是1809

您可以从此注册表键中读取ReleaseId:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion - ReleaseId

请参考:如何从Windows注册表中读取值

BuildNumber

Windows Server 2019的版本号最终停留在17763。

任何高于此版本号的(>=17764)都是vNext版本。(文章链接)

Windows Server 2016的版本号始终为10.0.14393.###,其中###随着累积更新而递增。

Windows Server 2019的版本号始终为10.0.17763.###,其中###随着累积更新而递增。(文章链接)

所以BuildNumber 17763应该始终对应于Windows Server 2019Windows Server,版本1809(或Windows 10 1809,但检查ProductType可以告诉您它是否为服务器)。

谢谢您的回答。不过,我正在寻找微软官方文档中的方法... - Maris B.

0

我不明白如何使用VerifyVersionInfoW来判断我们是否在运行Windows Server 2019上。您能详细说明一下吗? - Maris B.
嗨,Maris。请查看以下链接:https://learn.microsoft.com/en-us/windows/desktop/api/versionhelpers/nf-versionhelpers-iswindowsversionorgreater / https://dev59.com/0VwY5IYBdhLWcg3w37CG 。这些解决方案用于绕过不相关的GetVersionEx。 - Herve K.
我仍然不清楚如何区分Windows Server 2016和Windows Server 2019,例如... - Maris B.

0
唯一的区别在于dwBuildNumber。所以这段代码对我有效:
else if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0) 
{
    if (osvi.wProductType == VER_NT_WORKSTATION)
        m_csOsType += _T("10 ");
    else
    {
        if (osvi.dwBuildNumber >= 17763)
            m_csOsType += _T("Server 2019 ");
        else
            m_csOsType += _T("Server 2016 ");
    }
        
}

0
我发现最好的方法是使用您提到的GetVersionEx方法,如果它返回6.2(对于Windows 8.1及以上版本),则回退到wmic api。
下面的代码取自Microsoft,使用wmic api获取操作系统名称。
参考资料:https://learn.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

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

int main(int argc, char **argv)
{
HRESULT hres;

// Step 1: --------------------------------------------------
// Initialize COM. ------------------------------------------

hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
if (FAILED(hres))
{
    cout << "Failed to initialize COM library. Error code = 0x" 
        << hex << hres << endl;
    return 1;                  // Program has failed.
}

// Step 2: --------------------------------------------------
// Set general COM security levels --------------------------

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 1;                    // Program has failed.
}

// Step 3: ---------------------------------------------------
// 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;
    CoUninitialize();
    return 1;                 // Program has failed.
}

// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method

IWbemServices *pSvc = NULL;

// Connect to the root\cimv2 namespace with
// the current user and obtain pointer pSvc
// to make IWbemServices calls.
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 (for example, 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 1;                // Program has failed.
}

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


// Step 5: --------------------------------------------------
// Set security levels on the proxy -------------------------

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 1;               // Program has failed.
}

// Step 6: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----

// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
    bstr_t("WQL"), 
    bstr_t("SELECT * FROM Win32_OperatingSystem"),
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
    NULL,
    &pEnumerator);

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

// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------

IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;

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

    if(0 == uReturn)
    {
        break;
    }

    VARIANT vtProp;

    // Get the value of the Name property
    hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
    wcout << " OS Name : " << vtProp.bstrVal << endl;
    VariantClear(&vtProp);

    pclsObj->Release();
}

// Cleanup
// ========

pSvc->Release();
pLoc->Release();
pEnumerator->Release();
CoUninitialize();

return 0;   // Program successfully completed.

}

你能发布一下你得到的结果吗?我的意思是输出。 - Maris B.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接