Cómo obtener todos los atributos habituales (distinguishedName, cn, dNSHostName, lastLogon, logoncount, name, objectGUID, objectSid, operatingSystem, operatingSystemHotfix, operatingSystemServicePack y pwdLastSet) del objeto Computer (Equipo) en un LDAP de Active Directory (AD DS) de Windows Server. Usaremos el lenguaje de programación C# (C Sharp) de Visual Studio .Net para conectar con el dominio Active Directory y obtener estos datos.
La clase LDAP.cs en C#
Agregaremos una clase a nuestra aplicación Visual Studio .Net C#, con el nombre «LDAP.cs». Será la encargada de conectar con alguno de los controladores del dominio y obtener los datos del equipo indicado. El código completo de la clase LDAP.cs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
using System; using System.DirectoryServices; using System.Security.Principal; namespace ProyectoA_LDAP { class LDAP { //Obtener atributos LDAP (Active Directory) de objeto computer public static void ObtenerDatosLDAPEquipo(ref string distinguishedName, ref string cn, ref string dNSHostName, ref DateTime lastLogon, ref int logoncount, ref string name, ref string objectGUID, ref string objectSid, ref string operatingSystem, ref string operatingSystemHotfix, ref string operatingSystemServicePack, ref DateTime pwdLastSet) { Inventario inv = new Inventario(); string dominio = inv.obtenerDominioEquipo(); string equipo = inv.obtenerNombrePC(); distinguishedName = string.Empty; cn = string.Empty; dNSHostName = string.Empty; lastLogon = DateTime.MinValue; logoncount = 0; name = string.Empty; objectGUID = string.Empty; objectSid = string.Empty; operatingSystem = string.Empty; operatingSystemHotfix = string.Empty; operatingSystemServicePack = string.Empty; pwdLastSet = DateTime.MinValue; if (!string.IsNullOrEmpty(dominio) && !string.IsNullOrEmpty(equipo)) { try { using (var entradaDirectorio = new DirectoryEntry(string.Format("LDAP://{0}", dominio))) { var busqueda = new DirectorySearcher(entradaDirectorio, (string.Format("(&(objectCategory=computer)(name={0}))", equipo))); busqueda.PropertiesToLoad.Add("distinguishedName"); busqueda.PropertiesToLoad.Add("cn"); busqueda.PropertiesToLoad.Add("dNSHostName"); busqueda.PropertiesToLoad.Add("lastLogon"); busqueda.PropertiesToLoad.Add("logonCount"); busqueda.PropertiesToLoad.Add("name"); busqueda.PropertiesToLoad.Add("objectGUID"); busqueda.PropertiesToLoad.Add("objectSid"); busqueda.PropertiesToLoad.Add("operatingSystem"); busqueda.PropertiesToLoad.Add("operatingSystemHotfix"); busqueda.PropertiesToLoad.Add("operatingSystemServicePack"); busqueda.PropertiesToLoad.Add("pwdLastSet"); busqueda.SizeLimit = 1; SearchResult resultadoBusqueda = busqueda.FindOne(); if (resultadoBusqueda != null) { //Obtenemos distinguishedName if (resultadoBusqueda.Properties.Contains("distinguishedName")) { distinguishedName = (string)resultadoBusqueda.Properties["distinguishedName"][0]; } //Obtenemos cn if (resultadoBusqueda.Properties.Contains("cn")) { cn = (string)resultadoBusqueda.Properties["cn"][0]; } //Obtenemos dNSHostName if (resultadoBusqueda.Properties.Contains("dNSHostName")) { dNSHostName = (string)resultadoBusqueda.Properties["dNSHostName"][0]; } //Obtenemos lastLogon DateTime ultimoInicioObtenidoLDAP = DateTime.MinValue; if (resultadoBusqueda.Properties.Contains("lastLogon")) { ultimoInicioObtenidoLDAP = DateTime.FromFileTime((long)resultadoBusqueda.Properties["lastLogon"][0]); } if (DateTime.Compare(ultimoInicioObtenidoLDAP, lastLogon) > 0) lastLogon = ultimoInicioObtenidoLDAP; //Obtenemos logoncount if (resultadoBusqueda.Properties.Contains("logonCount")) { logoncount = (int)resultadoBusqueda.Properties["logoncount"][0]; } //Obtenemos name if (resultadoBusqueda.Properties.Contains("name")) { name = (string)resultadoBusqueda.Properties["name"][0]; } //Obtenemos objectGUID if (resultadoBusqueda.Properties.Contains("objectGUID")) { Guid _guid = new Guid((Byte[])(Array)resultadoBusqueda.Properties["objectGUID"][0]); objectGUID = _guid.ToString(); } //Obtenemos objectSid if (resultadoBusqueda.Properties.Contains("objectSid")) { //var sid = resultadoBusqueda.Properties["objectSid"][0]; byte[] sid = (byte[])resultadoBusqueda.Properties["objectSid"][0]; objectSid = new SecurityIdentifier(sid, 0).ToString(); } //Obtenemos operatingSystem if (resultadoBusqueda.Properties.Contains("operatingSystem")) { operatingSystem = (string)resultadoBusqueda.Properties["operatingSystem"][0]; } //Obtenemos operatingSystemHotfix if (resultadoBusqueda.Properties.Contains("operatingSystemHotfix")) { operatingSystemHotfix = (string)resultadoBusqueda.Properties["operatingSystemHotfix"][0]; } //Obtenemos operatingSystemServicePack if (resultadoBusqueda.Properties.Contains("operatingSystemServicePack")) { operatingSystemServicePack = (string)resultadoBusqueda.Properties["operatingSystemServicePack"][0]; } //Obtenemos pwdLastSet DateTime pwdLastSetLDAP = DateTime.MinValue; if (resultadoBusqueda.Properties.Contains("pwdLastSet")) { pwdLastSetLDAP = DateTime.FromFileTime((long)resultadoBusqueda.Properties["pwdLastSet"][0]); } if (DateTime.Compare(pwdLastSetLDAP, pwdLastSet) > 0) pwdLastSet = pwdLastSetLDAP; } } } catch (Exception) { //Capturar excepción } } } } } |
La clase Inventario.cs en C#
En la clase anterior usamos otra clase: Inventario.cs, para obtener el dominio al que está agregado el equipo actual (en el que se ejecuta el programa) y el nombre del equipo.
En la clase LDAP.cs podríamos pasarle como parámetro el nombre del equipo y el dominio, en lugar de obtenerlos, pero así la hacemos más «independiente».
El código C Sharp de la clase Inventario.cs para obtener el nombre del equipo y el dominio sería:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
using System; using System.Management; using System.Net; namespace ProyectoA_LDAP { class Inventario { public string sistemaNombre; public string nombrePC; public string usuarioPC; //Constructor public Inventario() { } //Nombre de red del equipo public string obtenerNombrePC() { string resultado; try { resultado = Environment.MachineName; //Si no ha obtenido el nombre del PC por el método anterior //puede ser porque no se ha iniciado sesión //Se intenta con otro método if (resultado == null && resultado == "") resultado = Dns.GetHostName(); //Si tampoco se ha obtenido el nombre del PC se intenta con WMI if (resultado == null && resultado == "") { obtenerSistema(); resultado = sistemaNombre; } } catch (Exception) { resultado = ""; } //Actualizamos el valor del atributo nombrePC de la clase nombrePC = resultado; return resultado; } //Usuario que ha iniciado sesión en el equipo public string obtenerUsuario() { string resultado; try { resultado = Environment.UserName; } catch (Exception) { resultado = ""; } //Actualizamos el valor del atributo usuarioPC de la clase usuarioPC = resultado; return resultado; } //Obtener datos del sistema (nombre equipo) con WMI public void obtenerSistema() { try { ManagementObjectSearcher objBusquedaWMI = new ManagementObjectSearcher("SELECT Name, PartOfDomain, Domain," + " Workgroup, Model, Manufacturer, UserName FROM Win32_ComputerSystem"); foreach (ManagementObject propiedad in objBusquedaWMI.Get()) { //Capturamos los errores propiedad a propiedad, de lo contrario, si una //propiedad no existe, da error y no captura las siguientes //No devuelve null, da error, por eso hay que capturar el error try { sistemaNombre = string.IsNullOrEmpty(propiedad["Name"].ToString()) ? "" : propiedad["Name"].ToString(); } catch { sistemaNombre = ""; } break; //Sólo habrá una instancia } } catch (Exception) { sistemaNombre = ""; } } } } |
Ejemplo de uso de la clase LDAP.cs en C#
Un ejemplo de uso de la clase LDAP.cs, para obtener todos los atributos del equipo actual, en el que se ejecuta el programa, sería:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
//Obtener datos LDAP equipo public void ObtenerLDAPEquipo() { string distinguishedName = string.Empty; string cn = string.Empty; string dNSHostName = string.Empty; DateTime lastLogon = DateTime.MinValue; int logoncount = 0; string name = string.Empty; string objectGUID = string.Empty; string objectSid = string.Empty; string operatingSystem = string.Empty; string operatingSystemHotfix = string.Empty; string operatingSystemServicePack = string.Empty; DateTime pwdLastSet = DateTime.MinValue; LDAP.ObtenerDatosLDAPEquipo(ref distinguishedName, ref cn, ref dNSHostName, ref lastLogon, ref logoncount, ref name, ref objectGUID, ref objectSid, ref operatingSystem, ref operatingSystemHotfix, ref operatingSystemServicePack, ref pwdLastSet); ldap_Equipo_distinguishedname = distinguishedName; ldap_Equipo_cn = cn; ldap_Equipo_dnshostname = dNSHostName; ldap_Equipo_lastlogon = lastLogon; ldap_Equipo_logoncount = logoncount; ldap_Equipo_name = name; ldap_Equipo_objectguid = objectGUID; ldap_Equipo_objectsid = objectSid; ldap_Equipo_operatingsystem = operatingSystem; ldap_Equipo_operatingsystemhotfix = operatingSystemHotfix; ldap_Equipo_operatingsystemservicepack = operatingSystemServicePack; ldap_Equipo_pwdlastset = pwdLastSet; } |
En el ejemplo anterior, los datos obtenidos del equipo actual (en el que se ejecuta el programa), se almacenarán en las variables ldap_xxxx, declaradas a nivel de clase para poder ser usadas desde otras clases. Con ellas, podremos hacer lo que deseemos, como por ejemplo guardarlos en base de datos.