Club Delphi  
    FTP   CCD     Buscar   Trucos   Trabajo   Foros

Retroceder   Foros Club Delphi > Otros entornos y lenguajes > C++ Builder
Registrarse FAQ Miembros Calendario Guía de estilo Temas de Hoy

Respuesta
 
Herramientas Buscar en Tema Desplegado
  #1  
Antiguo 21-06-2012
Toni Toni is offline
Miembro
 
Registrado: may 2003
Ubicación: Barcelona - España
Posts: 364
Poder: 21
Toni Va por buen camino
Leer el nº de serie fisico del disco duro utilizando WMI

Hola,

Necesito hacer una funcion en C++ Builder 6 para poder leer el nº de serie fisico del disco duro, ademas necesito que esto corra en Windows 2008 server. Por lo que lno sirven antiguas funciones que utilizaban la funcion CreateFile de la API de Windows. Y hay que acceder mediante WMI. En el foro he encontrado un ejemplo realizado en Pascal y como ya he realizado otras veces he intentado incorporarlo en projecto de builder, pero en esta ocasion no me funciona. Parece que pide alguna libreria para utilizar el WMI que en mi Builder 6 no viene.

Alguien puede hechar un poco de luz a todo esto.

Gracias!
__________________
Saludos,

Bitman
Responder Con Cita
  #2  
Antiguo 21-06-2012
Avatar de rruz
[rruz] rruz is offline
Miembro Premium
 
Registrado: jun 2006
Posts: 146
Poder: 18
rruz Va por buen camino
Para obtener el numero serial del disco duro debes usa rla propiedad SerialNumber de la clase Win32_DiskDrive

Aqui tienes un ejemplo

Código Delphi [-]
#pragma hdrstop
#include 
using namespace std;
#include 
#include  

//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_DiskDrive class represents a physical disk drive as seen by a computer running the Win32 operating system. Any interface to a Win32 physical disk drive is a descendent (or member) of this class. The features of the disk drive seen through this object correspond to the logical and management characteristics of the drive. In some cases, this may not reflect the actual physical characteristics of the device. Any object based on another logical device would not be a member of this class.
// Example: IDE Fixed Disk.

#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 * FROM Win32_DiskDrive",
    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"SerialNumber", 0, &vtProp, 0, 0);// String
                if (!FAILED(hr))
                {
                  if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
                    wcout << "SerialNumber : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
                  else
                  if ((vtProp.vt & VT_ARRAY))
                    wcout << "SerialNumber : " << "Array types not supported (yet)" << endl;
                  else
                    wcout << "SerialNumber : " << 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.
}

Como ayuda puedes utilizar la herramienta WMI Delphi Code Creator que puede generar codigo compatible con C++ builder 6.
Responder Con Cita
  #3  
Antiguo 25-06-2012
Toni Toni is offline
Miembro
 
Registrado: may 2003
Ubicación: Barcelona - España
Posts: 364
Poder: 21
Toni Va por buen camino
Hola rruz,

Muchas gracias por tu aporte, tanto por el código como por la herramienta que desconocia totalmente.

Voy a probarlo a ver que tal me funciona.

Saludos,
__________________
Saludos,

Bitman
Responder Con Cita
Respuesta



Normas de Publicación
no Puedes crear nuevos temas
no Puedes responder a temas
no Puedes adjuntar archivos
no Puedes editar tus mensajes

El código vB está habilitado
Las caritas están habilitado
Código [IMG] está habilitado
Código HTML está deshabilitado
Saltar a Foro

Temas Similares
Tema Autor Foro Respuestas Último mensaje
Obtener serial físico de disco duro thecidmx Varios 11 09-01-2012 00:31:51
obtener el número de serie de un disco duro serial ATA mgc API de Windows 4 27-03-2009 15:54:18
Número de serie físico del disco duro REDCOM Varios 10 23-03-2009 20:35:53
Numero serie disco duro ESTEBANC C++ Builder 1 04-02-2009 01:32:24
Modificar el numero de serie de una unidad de disco duro Sick boy API de Windows 2 06-10-2004 12:45:33


La franja horaria es GMT +2. Ahora son las 12:20:24.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi
Copyright 1996-2007 Club Delphi