Mostrando las entradas con la etiqueta Windows Server. Mostrar todas las entradas
Mostrando las entradas con la etiqueta Windows Server. Mostrar todas las entradas

viernes, 5 de octubre de 2012

Windows - net user options


You can use the following parameters with the net user command:
  • username
    Is the name of the user account you want to add, delete, modify, or view. The name of the user account can have as many as 20 characters.
  • password
    Assigns or changes a password for the user's account. A password must satisfy the minimum length set with the/minpwlen option of the net accounts command. It can contain as many as 14 characters.
  • *
    Produces a prompt for the password. The password is not displayed when you type it at a password prompt.
  • /domain
    Performs the operation on the primary domain controller (PDC) of the current domain. This parameter applies only to computers running Windows NT Workstation that are members of a Windows NT Server domain. By default, Windows NT Server-based computers perform operations on the PDC.
  • /add
    Adds a user account to the user accounts database.
  • /delete
    Removes a user account from the user accounts database.

Options for the Net User Command

  • /active:{yes | no}
    Activates or deactivates the account. If the account is not active, the user cannot gain access to the server. The default is yes.
  • /comment:"text"
    Provides a descriptive comment about the user's account (maximum of 48 characters). Be sure to put quotation marks around the text you use.
  • /countrycode:nnn
    Uses the operating system country code to implement the specified language files for a user's help and error messages. A value of 0 signifies the default country code.
  • /expires:{date | never}
    Causes the account to expire if date is set. The never option sets no time limit on the account. An expiration date is in the form mm/dd/yy or dd/mm/yy, depending on the country code. Months can be a number, spelled out, or abbreviated with three letters. Year can be two or four numbers. Use slashes (/) with no spaces to separate parts of the date.
  • /fullname:"name"
    Is a user's full name (rather than a user name). Enclose the name in quotation marks.
  • /homedir:pathname
    Sets the path for the user's home directory. The path must exist.
  • /passwordchg:{yes | no}
    Specifies whether users can change their own password. The default is yes.
  • /passwordreq:{yes | no}
    Specifies whether a user account must have a password. The default is yes.
  • /profilepath[:path]
    Sets a path for the user's logon profile.
  • /scriptpath:pathname
    Is the location of the user's logon script.
  • /times:{times | all}
    Is the logon hours. The times option is expressed as day[-day][,day[-day]],time[-time][,time [-time]], and is limited to 1-hour increments. Days can be spelled out or abbreviated. Hours can be 12-hour or 24-hour notation. For 12-hour notation, use am, pm, a.m., or p.m. The all option specifies that a user can always log on, and a blank value specifies that a user can never log on. Separate day and time entries with a comma, and separate multiple day and time entries with a semicolon.
  • /usercomment:"text"
    Lets an administrator add or change the user comment for the account.
  • /workstations:{computername[,...] | *}
    Lists as many as eight computers from which a user can log on to the network. If the /workstations option has no list or if the list is *, the user can log on from any computer.
  • net help user | more
    Displays Help one screen at a time.


jueves, 4 de octubre de 2012

Export Audit Policy Configuration - Windows


secedit command allows to export Security policy configurations besides other acctions.

The possible actions are:
  • configure 
  • analyze
  • import
  • export
  • validate
  • generaterollback
To use secedit you must have a Security Database.

To create a Security Database (sdb) you must:
  1. open "mmc" (from start>run just type "mmc")
  2. click on File > add/remove snap-in
  3. Select "Security configuration and analysis"
  4. Button "Add" & "OK"
  5. Right click & New database & Select a name for the database & click open
  6. Define the policies you would like to export (define any value if you only need to export the configuration. define the propper values if you like to analyze)
  7.  
psexec @filserver.txt secedit /export /db security.sdb /areas SECURITYPOLICY GROUP_MGMT  GROUP_MGMT  GROUP_MGMT GROUP_MGMT  GROUP_MGMT /cfg output.txt >> outputLog.txt

psexec is used to run this command in several computers. The @filserver.txt file contains a list computers / servers.

viernes, 31 de agosto de 2012

Windows: Local account management


To create a local user massively in a list of servers, you can use this command:

Psexec \\server1 net user user01 Pass.128 /ADD
Psexec \\server2 net user user01 Pass.128 /ADD
...

Use the excel to concatenate the fields, so you can have a full list of command, without typing each server.

Then, add the propper permission:

Psexec \\server1 net localgroup administrators /add user01
Psexec \\server2 net localgroup administrators /add user01 
...

If  you just want to allow access to a domain user, is pretty similar:

Psexec \\server1 net localgroup administrators /add contoso\user02
Psexec \\server2 net localgroup administrators /add contoso\user02
...

Then if you need to remove permissions, issue this command

Psexec \\server1 net localgroup administrators contoso\user02  /delete



jueves, 19 de julio de 2012

Delegar permisos sobre Security logs

En los entornos corporativos y sobre todo para los ambientes Windows es muy comun encontrar que las áreas de Auditoría cuyos usuarios no son privilegiados deseen visualizar logs de Seguridad. En Windows Server 2003 esto es una tarea algo compleja y riesgosa para lo que nos tiene acostumbrados Microsoft y deberemos utilizar el lenguaje SDDL:

CUIDADO: Este procedimiento mal implementado puede impedir el acceso y requiere de reinicio del equipo.

Delegating access to the event logs

In Windows Server® 2003, Windows Vista, and Windows Server® 2008, it is possible to customize the permissions on each event log on a computer. This capability was not available in previous versions of Windows. Some organizations may want to grant read-only access to one or more of the System event logs to some members of the IT team, such as auditors. The access control list (ACL) is stored as a Security Descriptor Definition Language (SDDL) string, in a REG_SZ value called "CustomSD" for each event log in the registry. The following procedure shows how to delegate read-only access for an event log. You will need to repeat this procedure for each event log that you wish to delegate read-only access to by changing the registry key as needed.
CautionCaution
Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on the computer.
To delegate access to an event log using the registry
  1. Open Registry Editor.
  2. Navigate to the following registry path:
    HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\EventLog
    You will see that there are keys available for each event log. Select the event log for which you want to delegate read-only access.
  3. Add a new key with the name CustomSD to the event log you selected.
  4. Add a new String value to the CustomSD key. The name of this string is not required, but it represents the access control list for the event log in the Security Descriptor Definition Language (SDDL) syntax. In this procedure this value will be referred to as SDDLACL.
  5. Set the value of the SDDLACL to the following:
    O:BAG:SYD:(D;;0xf0007;;;AN)(D;;0xf0007;;;BG) (A;;0xf0007;;;SY)(A;;0x7;;;BA)(A;;0x5;;;SO)(A;;0x1;;;IU)(A;;0x1;;;SU) (A;;0x1;;;S-1-5-3)(A;;0x2;;;LS)(A;;0x2;;;NS)
Once you edit this value and restart the computer, the new setting will take effect. Be certain that you fully understand SDDL and the default permissions that are placed on each event log before you use this procedure. Also, be certain to test any changes thoroughly before you implement them in a production environment, because you could accidentally configure the ACLs on an event log in such a way that no one could access it.

Additional references

The following links provide additional information about event logging in Windows Server 2003 and Windows Vista:



Extraido de: http://technet.microsoft.com/en-us/library/cc722385(WS.10).aspx

Mas info: http://support.microsoft.com/default.aspx?scid=kb;en-us;323076

jueves, 21 de junio de 2012

Obtener datos de Active Directory desde Excel

En el día de hoy tuve la necesidad de buscar información en Active Directory a partir de un listado de usuarios que tenia en excel con  información faltante.


En vez de hacer un script WMI o una consulta utilizando dsget / dsquery, decidí investigar que herramientas existen para hacer busquedas en AD desde excel. Para una grata sorpresa mia encontré la siguiente herramienta gratuita:


http://excelldapsearch.sourceforge.net/


Hasta ahora rara vez me he encontrado decepcionado con los proyectos hosteados en sourceforge, por lo que me embarque en la prueba.


El producto se instaló muy bien en mi Windows 7 x64 (english). Luego realicé la customización del archivo ini que se abre al finalizar la instalación.


Los parametros a modificar son:


En la sección [Connection]
;#colocar el servidor que corresponda, perferentemente el mas cercano

server=server.dominio.empresa.ccf
;#dejar el default
port=389
;#colocar el usuario que corresponda utilizar para conectarse
binddn=CN=myUser,OU=AR,OU=Users,OU=Accounts,DC=americas,DC=empresa,DC=ccf 
bindpw=<password>


No es necesario utilizar un usuario que sea Domain Admin, solo con un usuario miembro de Users bastará (si es que la configuración de AD es la default)


En la sección [Search]
;#colocar el que corresponda, esto restringe la búsqueda de objetos para que sea mas performante
basedn=OU=AR,OU=Users,OU=Accounts,DC=americas,DC=dominio,DC=ccf



En la sección [LDAP Attribute Descriptions] agregúe esta propiedad que me resulta util
manager=Manager


En caso de que necesites algún otro atributo que no esté por default en el ini, puede usar la tool AD Explorer de sysinternals (www.sysinternals.com) para browsear el Active Directory y obtener el nombre de todos los atributos de los objetos deseados.


Luego de realizadas estas parametrizaciones, procedemos a abrir el excel y en la opcion Add-ins del ribon aparece Run LDAP Search. (si teniamos el excel abierto es cuestion de cerrarlo y abrirlo para que aparezca la opción)


Con el excel con la información que queremos buscar, abrimos el LDAP Search y le definimos:

  1. Que filas buscar
  2. En que campo buscarlas
  3. Cuantas columnas mas hacia la derecha devolver los resultados
  4. que atributo/s devolver





viernes, 1 de junio de 2012

Windows Server 2012 Release Candidate

Windows Server 2012 conocido en nombre código como Windows Server 8 ya cuenta con su release candidate.

Este nuevo SO para Servidores está optimizado para “Cloud”. Ya hemos visto hace poco que Oracle lanzó su nuevo Solaris 11 optimizado para “Cloud” tambien.

La ERA Cloud ha comenzado…




Download:http://www.microsoft.com/en-us/server-cloud/new.aspx
(Seleccionen la opcion para developers, ya que la otra no está funcionando al momento.)

Requiere procesador 64 bits, ya no mas x86 en servidores.

martes, 24 de enero de 2012

Query local admin name - Consultar el nombre del adminsitrator local

Dado que la cuenta built-in puede ser renombrada es importante para distintas tareas conocer el nombre real del adminsitrator. Tambien puede variar el nombre según el idioma del SO.


Para esto lo mejor es buscar el usuario teniendo en cuenta su SID.
El SID del adminsitrator siempre termina en 500 y comienza con S-1-5:

A continuación el script para hacer la consulta:


strComputer="127.0.0.1"    ' local computer by default   
Set objUser=GetObject("WinNT://" & strComputer & "/" & GetAdminName & ",user")     


msgbox (getAdminName())




Function GetAdminName   
  Set objNetwork = CreateObject("Wscript.Network") 'get the current computer name 
  objComputerName = objNetwork.ComputerName    
  Set objwmi = GetObject("winmgmts:{impersonationLevel=impersonate}!//" & objComputerName)


  qry = "SELECT * FROM Win32_Account where Domain = '" & cstr(objComputerName) & "'" 


  For Each Admin in objwmi.ExecQuery(qry)   
    if (left(admin.sid, 6) = "S-1-5-" and right(admin.sid,4) = "-500") then 'look for admin sid
       GetAdminName = admin.name
    end if   
  next    
end Function

miércoles, 5 de octubre de 2011

Windows: Password required vulnerability

Hay ciertas cuentas que genera Windows en forma predeterminada que no requieren password y son una vulnerabilidad, ya que es posible utilizarlas sin ingresar su password.

Para conocer si una cuenta requiere password o no, debemos ejecutar el siguiente comando:

>net user IUSR_testServer
User name                    IUSR_testServer
Full Name
Comment                      Built-in account for IIS
User's comment
Country code                 000 (System Default)
Account active               Yes
Account expires              Never
Password last set            03/06/2011 11:12:42 p.m.
Password expires             Never
Password changeable          03/06/2011 11:12:42 p.m.
Password required            No
User may change password     Yes
Workstations allowed         All
Logon script
User profile
Home directory
Last logon                   03/06/2011 11:12:42 p.m.
Logon hours allowed          All
Local Group Memberships      *Users
Global Group memberships     *None
The command completed successfully.

Una vez que detectamos estas cuentas debemos analizar si la aplicacion que la usa (En nuestro caso el IIS) puede reconfigurarse y setearle el password para que sea utilizado.

Una vez realizado este analisis es necesario forzar que requiera password con el siguiente comando:




net user /passwordreq:yes NombreUsusario


Una vez realizado esto, es recomendable reiniciar el servicio que utilice este usuario para comprobar que todo siga funcionando sin problemas.

Tambien será necesario controlar que el IIS tenga el password correcto ingresado en los sites que utilicen dicha cuenta. Si fuera otra aplicación verificar que la aplicación tenga el password correctamente ingresado.



martes, 27 de septiembre de 2011

How to force WSUS updates to install on a computer

LA forma de fozar a un computer (workstation o server) a que se comunique con WSUS y descargue los paquetes que tiene pendientes de instalación es reiniciando los servicios que utiliza WSUS:

Desde un CMD ejcutar lo siguiente:

net stop "windows installer"
net start "windows installer"
net stop "
automatic updates"
net start "automatic updates"
net stop "background intelligent Transfer Service"
net start "background intelligent Transfer Service"



Si quieren hacer un vbscript puede hacerlo de la siguiente forma:

'Iniciar servicios de Windows Update
WSHShell.run "cmd.exe /K net stop ""windows installer"" & net start ""windows installer"" & exit", 1, true
WSHShell.run "cmd.exe /K net stop ""automatic updates"" & net start ""automatic updates"" & exit", 1, true
WSHShell.run "cmd.exe /K net stop ""background intelligent Transfer Service"" & net start ""background intelligent Transfer Service"" & exit", 1, true



Para ver el log de windows update y chequear los mensajes, desde Inicio > Ejecutar peguen esto:

notepad %WinDir%\WindowsUpdate.log

jueves, 8 de septiembre de 2011

Como evaluar que bloquea un usuario


Este post puede servir para identificar quien o que bloquea un usuario de dominio o local.

1. Primero ejecutar el tool EventCombMT.exe



Nota: Los números de eventos de Seguridad de Windows a utilizar pueden consultarse desde esta URL: 
http://support.microsoft.com/kb/174074 (Aplica para Windows Server 2003)
http://support.microsoft.com/kb/947226 (Aplica para Windows Server 2008)
*Tener en cuenta que en Windows Vista / Server 2008 / Seven / Server 2012 tienen códigos de eventos de Seguridad diferentes a Windows 2003. Lo bueno es que no se solapan, arrancan de una nuemeración distinta a la que posee 2003.



Nota 3: Como utilizar el EventCombMT en esta URL : 
http://support.microsoft.com/kb/824209 

Una vez que la herramienta finaliza generará un txt en el directorio %temp%. Una linea de ejemplo es la siguiente:

644,AUDIT SUCCESS,Security,Sat Sep 03 07:07:48 2011,NT AUTHORITY\SYSTEM,User Account Locked Out:     Target Account Name: usuario1    Target Account ID: %{S-1-5-21-3880413253-2914564469-1958111818-20410}     Caller Machine Name: server1 Caller User Name: DCServer$     Caller Domain: contoso     Caller Logon ID: (0x0,0x3E7)    


Con esto vemos que usuario1 se esta bloqueando en el dominio contoso por una intento fallido de login desde el server1, a traves del Domain Controller DCServer$

2.Analizar en el servidor desde donde se realiza el login (en nuestro ejemplo server1)
Debemos analizar si:
  • El usuario tiene tareas en ejecución logeado (desde un cmd TASKLIST /FI "USERNAME ne usuario1")
  • Existen procesos que corren con este usuario (services.msc)
  • Existen tareas programadas (taskschd.msc)

3. Si con el paso anterior no encontramos que es lo que bloquea al usuario, analicemos el EventId: 529 para determinar que proceso bloquea el usuario.

En este caso vemos que el usuario se bloquea desde el Process ID 2592, que corresponde al servicio de Reporting Services


lunes, 5 de septiembre de 2011

Como delegar permisos de Active Directory

Para delegar permisos de Active Directory a un grupo de usuarios y no morir en el intento, recomiendo utilizar la herramienta de linea de comando dsacls.


Si utilizan el wizard que ofrece Windows 2003 server, van a encontrar que genera problemas con la herencia la mayoría de las veces.


A continuación un ejemplo del comando applicado en una delegación concreta de permisos sobre un atributo de un objeto user


dsacls "OU=Sites,OU=Argentina,DC=dominio,DC=ccf" /I:S /G domino\group:WP;personalTitle;user


Ejemplo para permitir a un grupo modificar la expiracion de los usuarios:


Para delegar el permiso de modificar el atributo accountExpires

dsacls "CN=Pepe,OU=Usuarios,OU=ARGENTINA,DC=dominio,DC=ccf" /I:S /G SA\HelpServicesGroup:RPWP;accountExpires;user >> out.log


Para delegar el permiso de modificar el atributo expirationTime:

dsacls "CN=Pepe,OU=Usuarios,OU=ARGENTINA,DC=dominio,DC=ccf" /I:S /G SA\HelpServicesGroup:RPWP;expirationTime;user >> out.log

Se puede poner RP (read) y WP (write) seguidos en una misma línea, como están arriba (RPWP;) y no tener que hacer 2 líneas por separado para cada Property.
El “>> out.log” se puede usar para tener registro de los resultados, si vamos a ejecutar muchos comandos juntos. Puede que fallen si el nombre (CN=) tiene caracteres no permitidos (Ñ,  comilla simple, etc.).




Mas info sobre el comando:


This article describes how to use the Dsacls.exe tool (Dsacls.exe) to manage access control lists (ACLs) for directory services in Microsoft Windows Server 2003 and Microsoft Windows 2000 Server. Dsacls.exe is a command-line tool that you can use to query the security attributes and to change permissions and security attributes of Active Directory objects. It is the command-line equivalent of the Security tab in the Windows Active Directory snap-in tools such as Active Directory Users and Computers and Active Directory Sites and Services.

Dsacls.exe is included with the Windows Support Tools. To install the Support Tools, run Setup.exe from the Support\Tools folder on the Windows Server 2003 or Windows 2000 Server CD-ROM. 

You can use Dsacls.exe and another Windows Support Tool, ACL Diagnostics (Acldiag.exe), to provide security configuration and diagnosis functionality on Active Directory objects from the command prompt.

Note You can use Dsacls.exe to display and change permissions (access control entries) in the access control list (ACL) of objects in Active Directory Application Mode (ADAM) in Windows Server 2003.

Important Do not use Dsacls.exe to modify permissions if you have implemented a Hosting solution such as Windows-based Hosting, High Volume Exchange (HVE), Hosted Messaging and Collaboration, or Hosted Exchange, or if the customer is using Microsoft Provisioning Service. The Hosting solutions depend on specific security model to isolate the ISP's customers from each other. 
DsAcls uses the following syntax:

dsacls object [/a] [/d {user | group}:permissions [...]] [/g {user | group}:permissions [...]] [/i:{p | s | t}] [/n] [/p:{y | n}] [/r {user | group} [...]] [/s [/t]]
You can use the following parameters with Dsacls.exe:
  • object: This is the path to the directory services object on which to display or change the ACLs. This path must be a distinguished name (also known as RFC 1779 or x.500 format). For example:
    CN=Someone,OU=Software,OU=Engineering,DC=Microsoft,DC=Com
    To specify a server, add \\Servername\ before the object. For example:
    \\MyServer\CN=Someone,OU=Software,OU=Engineering,DC=Microsoft,DC=Com
    When you run the dsacls command with only the object parameter (dsacls object), the security information about the object is displayed.
  • /a : Use this parameter to display the ownership and auditing information with the permissions.
  • /d {user | group}:permissions: Use this parameter to deny specified permissions to a user or group.User must use either user@domain or domain\user format, and group must use either group@domain ordomain\group format. You can specify more than one user or group in a command. For more information about the correct syntax to use for permissions, see the <Permissions> Syntax section later in this article.
  • /g {user | group}:permissions: Use this parameter to grant specified permissions to a user or group.User must use either user@domain or domain\user format, and group must use either group@domain ordomain\group format. You can specify more than one user or group in a command. For more information about the correct syntax to use for permissions, see the <Permissions> Syntax section later in this article.
  • /i:{p | t} : Use this parameter to specify one of the following inheritance flags:
    • p: Use this option to propagate inheritable permissions one level only.
    • s: Use this option to propagate inheritable permissions to subobjects only.
    • t: Use this option to propagate inheritable permissions to this object and subobjects.
  • /n : Use this parameter to replace the current access on the object, instead of editing it.
  • /p:{n}: This parameter determines whether the object can inherit permissions from its parent objects. If you omit this parameter, the inheritance properties of the object are not changed. Use this parameter to mark the object as protected (y = yes) or not protected (n = no).

    Note This parameter changes a property of the object, not of an Access Control Entry (ACE). To determine whether an ACE is inheritable, use the /I parameter.
  • /r {user | group}: Use this parameter to remove all permissions for the specified user or group. You can specify more than one user or group in a command. User must use either user@domain or domain\userformat, and group must use either group@domain or domain\group format.
  • /s: Use this parameter to restore the security on the object to the default security for that object class, as defined in the Active Directory schema.
  • /t : Use this parameter to restore the security on the tree of objects to the default for each object class. This switch is valid only when you also use the /s parameter.

Permissions Syntax

You must use the following syntax for permissions when you use the /d {user | group}:permissions or /g {user |group}:permissions parameter :
[PermissionBits];[{Object|Property}];[InheritedObjectType]
  • PermissionBits can use any of the following values, which can be concatenated together without spaces:

    Generic Permissions
    GRGeneric Read
    GEGeneric Execute
    GWGeneric Write
    GAGeneric All

    Specific Permissions
    SDDelete
    DTDelete an object and all its child objects.
    RCRead security information
    WDChange security information
    WOChange owner information
    LCList the child objects of an object
    CCCreate child object. If {Object|Property} is not specified to define a specific property, this applies to all properties of an object. Otherwise, it applies to the specified property of the object.
    DCDelete child object. If {Object|Property} is not specified to define a specific property, this applies to all properties of an object. Otherwise, it applies to the specified property of the object.
    WSWrite to self object. If {Object|Property} is not specified to define a specific property, this applies to all properties of an object. Otherwise, it applies to the specified property of the object.
    RPRead property. If {Object|Property} is not specified to define a specific property, this applies to all properties of an object. Otherwise, it applies to the specified property of the object.
    WPWrite property. If {Object|Property} is not specified to define a specific property, this applies to all properties of an object. Otherwise, it applies to the specified property of the object.
    CAControl access right. If {Object|Property} is not specified to define a specific property, this applies to all properties of an object. Otherwise, it applies to the specified property of the object.
    LOList the object access. Can be used to grant list access to a specific object if List Children (LC) is not also granted to the parent. Can also be denied on specific objects to hide those objects if the user or group has LC on the parent. By default, Active Directory does not enforce this permission.
  • {Object|Property}: This represents the display name of the object type or property. For example, "user" (without the quotation marks) is the display name for user objects, and "telephone number" (without the quotation marks) is the display name for the telephone number property.

    For example, the following command permits the user to create all types of child objects:
    /G Domain\User:CC

    However, the following command permits the user to create only child computer objects:
    /G Domain\User:CC;computer
  • InheritedObjectType: This represents the display name of the object type by which the permissions are expected to be inherited.

    If an object type is not specified, the permission can be inherited by all object types. This parameter is used only when permissions are inheritable.

    For example, the following command permits all types of objects to inherit the permission:
    /G Domain\User:CC
    However, the following command permits only user objects to inherit the permission:
    /G Domain\User:CC;;user
IMPORTANT: Use permissions only when you define object-specific permissions that override the default permissions defined in the Active Directory schema for that object type. Use with caution and only if you have a full understanding of object-specific permissions. 






Examples of Permissions
  • SDRCWDWO;;user

    This notation represents Delete, Read security information, Change security information, and Change ownership permissions on objects of type "user".
  • CCDC;group;

    This notation represents Create child and Delete child permissions to create or delete objects of type "group".
  • RPWP;telephonenumber;

    This notation represents Read property and Write property permissions on the telephone number property.



sábado, 14 de mayo de 2011

GPOs - From novice to specialist

Este video contiene un entrenamiento brindado sobre Microsoft Group Policy Objects.
Se trata la evolución de las GPOs a lo largo de los distintos sistemas operativos Windows. Las mejoras presentadas en Windows 2003 Server y Windows 2008 Server.

http://www.youtube.com/watch?v=-3UPATjsK4s

Tambien se presentan funcionalidades tales como WMI y RSoP.

Espero les sea de utilidad.

miércoles, 20 de abril de 2011

Linea de comandos Windows

Los que adminsitramos Unix y Windows a veces nos preguntamos porque a MS le gusta tanto generarnos artritis usando el mouse todo el dia. Sin embargo desde hace ya un largo tiempo MS viene recuperando el tiempo perdido y nos brinda herramientas para adminsitración via linea de comandos. El problema es que muy pocos adminsitradores Wintel las usan.

Aca un pequeño aporte para adminstración de Active Directory… he visto a gente haciendo print screen de los grupos o anotando uno por uno los usuarios de los grupos!!!! Tambien hay algunas herramientitas bastante limitadas que no tienen razon de ser si usamos la linea de comandos.

Les paso como listar miembros de grupos en Windows:

#Un Grupo local de un server / workstation
net localgroup nombregrupo

#Un Grupo de Dominio (ejemplo mostrando solo el DN del usuario)
dsget group “CN=PIMA,OU=Grupos,OU=Grupos Globais,OU=InfraBR,OU=Brasil,DC=contoso,DC=Corp,DC=net” –members

#Un Grupo de Dominio (mostrando el nombre del usuario y la descripcion)
#Acá concatenamos la/las salidas del dsget group en el dsget user (al mejor estilo Unix :P )
dsget group “CN=PIMA,OU=Grupos Legados,OU=Grupos Globais,OU=InfraBR,OU=Brasil,DC=contoso,DC=Corp,DC=net” -members | dsget user –display -desc

#Si la salida es larga conviene direccionarla a un archivo
dsget group “CN=PIMA,OU=Grupos Legados,OU=Grupos Globais,OU=InfraBR,OU=Brasil,DC=contoso,DC=Corp,DC=net” -members | dsget user –display -desc > GroupMembers.txt

mas info para AD:
http://technet.microsoft.com/en-us/library/cc731202(WS.10).aspx
http://technet.microsoft.com/en-us/library/cc732535(WS.10).aspx

lunes, 11 de abril de 2011

Script: List Active Directory computer objects

A la hora de analizar la cantidad de maquinas presentes en un dominio y poder conocer sus caracteristicas rapidamente, nada me ha dado mejor resultado que este script que he ido "tuneando" y mejorando a lo largo de los diferentes usos.
Espero este sea el primer post de una serie de scripts que le sean útiles al resto de la comunidad.

Aqui va:

'*******************************************************************
'*******************************************************************
'List computers to txt File
'Version: 0.3
'Author: Pablo Pagani
'Change Log:
'       V2: Format of the file changed to csv
'    v3: Added more properties
'*******************************************************************
'*******************************************************************


Const ADS_SCOPE_SUBTREE = 2
'*******************************************************************
'Definir el nombre del dominio
strDomain = "contoso.ccf"
'*******************************************************************

Set Shell = CreateObject("WScript.Shell")

'*******************************************************************
file=Shell.ExpandEnvironmentStrings("%temp%") &"\Computers.csv"
'*******************************************************************

Set Fso = CreateObject("Scripting.FileSystemObject")

If Fso.FileExists(file) Then
    Fso.DeleteFile file, True    'True forces override of Read-Only
end if

Set TxtS0 = Fso.CreateTextFile(file, ForWriting)

Set objConnection = CreateObject("ADODB.Connection")
Set objCommand =   CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"

Set objCOmmand.ActiveConnection = objConnection
objCommand.CommandText = "Select Name, Location, operatingSystem, operatingSystemServicePack, operatingSystemVersion, whenCreated,

whenChanged, description from 'LDAP://" & strDomain & "' " _
        & "Where objectCategory='computer'" 
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst

'********* HEADING *************************
line= "Computer; Location; SO; SO SP; SO Version; When Created; When Modified; Description" & vbcrlf

'********** DETAIL ************************
Do Until objRecordSet.EOF
    line = line & objRecordSet.Fields("name").Value & ";" & objRecordSet.Fields("location").Value & ";" _
    & objRecordSet.Fields("operatingSystem").Value & ";" & objRecordSet.Fields("operatingSystemServicePack").Value & ";" _
    & objRecordSet.Fields("operatingSystemVersion").Value & "; " & ";" & cstr(objRecordSet.Fields("whenCreated").Value) & ";" _
    & objRecordSet.Fields("whenChanged").Value & ";" & vbcrlf

'& objRecordSet.Fields("description").Value

    objRecordSet.MoveNext
Loop


TxtS0.WriteLine line
TxtS0.Close

set shell = nothing

msgbox "END!!"