Dkmetalcol

(En rediseño)


martes, 5 de junio de 2012

Script Active Directory VBS

Listar todos los usuarios del dominio


'Global variables
    Dim oContainer
    Dim OutPutFile
    Dim FileSystem
'Initialize global variables
    Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
    Set OutPutFile = FileSystem.CreateTextFile("Lista de todos los usuarios del dominio.txt", True)
    Set oContainer=GetObject("LDAP://DC=acme,DC=com")
'Enumerate Container
    EnumerateUsers oContainer
'Clean up
    OutPutFile.Close
    Set FileSystem = Nothing
    Set oContainer = Nothing
    WScript.Echo "Archivo creado"
    WScript.Quit(0)
Sub EnumerateUsers(oCont)
    Dim oUser
    For Each oUser In oCont
        Select Case LCase(oUser.Class)
               Case "user"
                    If Not IsEmpty(oUser.distinguishedName) Then
                       OutPutFile.WriteLine "dn: " & oUser.distinguishedName
                    End If
                    If Not IsEmpty(oUser.name) Then
                       OutPutFile.WriteLine "name: " & oUser.Get ("name")
                    End If
                    If Not IsEmpty(oUser.userPrincipalName) Then
                       OutPutFile.WriteLine "Login: " & oUser.userPrincipalName
                    End If
                    If Not IsEmpty(oUser.givenName) Then
                       OutPutFile.WriteLine "Nombres completos: " & oUser.givenName
                    End If
                    If Not IsEmpty(oUser.sn) Then
                       OutPutFile.WriteLine "Apellidos: " & oUser.sn
                    End If
                    If Not IsEmpty(oUser.telephoneNumber) Then
                       OutPutFile.WriteLine "Teléfono: " & oUser.telephoneNumber
                    End If
               Case "organizationalunit", "container"
                    EnumerateUsers oUser
        End Select
        OutPutFile.WriteLine
    Next
End Sub

Crear Usuarios por medio de un archivo de Excel


Option Explicit
Dim objRootLDAP, objContainer, objUser, objShell
Dim objExcel, objSpread, intRow
Dim strUser, strOU, strSheet
Dim strCN, strSam, strFirst, strLast, strPWD
' -----------------------------------------------'
' Important change OU= and strSheet to reflect your domain
' -----------------------------------------------'
strOU = "OU=ingenieria ," ' Note the comma
strSheet = "C:\usuarios.xlsx"
' Bind to Active Directory, Users container.
Set objRootLDAP = GetObject("LDAP://rootDSE")
Set objContainer = GetObject("LDAP://" & strOU & _
objRootLDAP.Get("defaultNamingContext"))
' Open the Excel spreadsheet
Set objExcel = CreateObject("Excel.Application")
Set objSpread = objExcel.Workbooks.Open(strSheet)
intRow = 3 'Row 1 often contains headings
' Here is the 'DO...Loop' that cycles through the cells
' Note intRow, x must correspond to the column in strSheet
Do Until objExcel.Cells(intRow,1).Value = ""
   strSam = Trim(objExcel.Cells(intRow, 1).Value)
   strCN = Trim(objExcel.Cells(intRow, 2).Value)
   strFirst = Trim(objExcel.Cells(intRow, 3).Value)
   strLast = Trim(objExcel.Cells(intRow, 4).Value)
   strUser = Trim(objExcel.Cells(intRow, 5).Value)
   strPWD = Trim(objExcel.Cells(intRow, 6).Value)
   ' Build the actual User from data in strSheet.
   Set objUser = objContainer.Create("User", "cn=" & strCN)
   objUser.sAMAccountName = strSam
   objUser.givenName = strFirst
   objUser.UserPrincipalName = strUser
 
   objUser.sn = strLast

   objUser.SetInfo
   ' Separate section to enable account with its password
   objUser.userAccountControl = 512
   objUser.pwdLastSet = 0
   objUser.SetPassword strPWD
   objUser.SetInfo
intRow = intRow + 1
Loop
objExcel.Quit
WScript.Quit
' End of free example UserSpreadsheet VBScript.

Archivo de Excel



Crear un grupo



Set objOU = GetObject("LDAP://OU=ingenieria,dc=acme,dc=com") 
Set objGroup = objOU.Create("Group", "cn=grupoingenieria") 
objGroup.Put "sAMAccountName", "grupoingenieria"objGroup.SetInfo

 Agregar usuarios de una unidad organizativa a un grupo



Option Explicit
Dim objRootLDAP, objGroup, objUser, objOU
Dim strOU, strGroup, strDNSDomain
Dim intCounter
' Check these objects referenced by strOU, strGroup exist in strOU
strOU = "OU=produccion,"
strGroup = "CN=grupoproduccion,"
' Bind to Active Directory and get LDAP name
Set objRootLDAP = GetObject("LDAP://RootDSE")
strDNSDomain = objRootLDAP.Get("DefaultNamingContext")
' Prepare the OU and the Group
Set objGroup = GetObject("LDAP://"& strGroup _
& strOU & strDNSDomain)
Set objOU =GetObject("LDAP://" & strOU & strDNSDomain)
' On Error Resume next
intCounter = 1
For Each objUser In objOU
   If objUser.Class = lcase("User") then
      objGroup.add(objUser.ADsPath)
      intCounter = intcounter +1
   End If
Next
WScript.Echo strGroup & " has " & intCounter & " new members"
Wscript.Quit


Agregar el atributo de protección contra borrado accidental 


Get-ADobject -Filter * -SearchBase “OU=Users,DC=Domain,DC=com” | Set-adobject -ProtectedFromAccidentalDeletion $true




Para poder agregar esto como un Script ejecutable sobre PowerShell y cargar el modulo de Active Directory



Comando para permitir ejecutar script's sobre Powershell

PS C:\> Get-ExecutionPolicy
AllSigned

PS C:\> Set-ExecutionPolicy RemoteSigned

Para poder cargar el modulo de Active Directory, en la primera linea del Script se ejecuta

Import-Module ActiveDirectory



Ahora para ponérselo a usuarios individualmente_

Import-Module ActiveDirectory
Get-ADobject -Filter * -SearchBase “CN=usuario1,OU=ingenieria,DC=acme,DC=com” | Set-adobject -ProtectedFromAccidentalDeletion $true
Get-ADobject -Filter * -SearchBase “CN=usuario2,OU=ingenieria,DC=acme,DC=com” | Set-adobject -ProtectedFromAccidentalDeletion $true
Y guardar el archivo con extensión *.ps1 y con el archivo guardado y luego de permitir ejecutar Script sobre PowerShell, dar click derecho "Run With PowerShell"

Para quitarle la protección contra escritura:

Import-Module ActiveDirectory 
Get-ADobject -Filter * -SearchBase “CN=usuario1,OU=ingenieria,DC=acme,DC=com” | Set-adobject -ProtectedFromAccidentalDeletion $false
Get-ADobject -Filter * -SearchBase “CN=usuario2,OU=ingenieria,DC=acme,DC=com” | Set-adobject -ProtectedFromAccidentalDeletion $false

Agregar un atributo a todos los usuarios de una unidad organizativa


En nuestro caso, vamos a ponerle el mismo teléfono (telephoneNumber) a todos los usuarios de una unidad organizativa (ingenieria)



Dim oContainer
    Set oContainer=GetObject("LDAP://OU=ingenieria,DC=acme,DC=com")
ModifyUsers oContainer
'cleanup
    Set oContainer = Nothing
    WScript.Echo "Finished"
    WScript.Quit
Sub ModifyUsers(oObject)
    Dim oUser
    oObject.Filter = Array("user")
    For Each oUser in oObject
        oUser.Put "telephoneNumber","5260000"
        oUser.SetInfo
    Next
End Sub




Eliminar usuarios del Active Directory


De forma individual




' Get the NETBIOS Domain name
SET objSystemInfo = CREATEOBJECT("ADSystemInfo") 
strDomain = objSystemInfo.DomainShortName


' Prompt for userName
strUserName = INPUTBOX("Por favor ingrese el Username (sAMAccountName) del usuario a borrar:")
IF strUserName = "" THEN wscript.quit


' Call function to delete user
DeleteUser strUserName,strDomain


SUB DeleteUser(BYVAL strUserName,strDomain)
' Function to delete a user account.
' Use GetUserDN to convert username to distinguished name.
' Use DN to bind to user object.  Get the container object
' for the use (OU) and call the Delete method of the containter
' object, passing the users common-name as a parameter.

userDN = GetUserDN(strUserName,strDomain)
SET objUser = GETOBJECT("LDAP://" & userDN)
SET objContainer = GETOBJECT(objUser.Parent)
objContainer.Delete "user","cn=" & objUser.cn


END SUB


FUNCTION GetUserDN(BYVAL strUserName,BYVAL strDomain)
' Use name translate to return the distinguished name
' of a user from the NT UserName (sAMAccountName)
' and the NETBIOS domain name.
' e.g. cn=user1,cn=users,dc=wisesoft,dc=co,dc=uk


SET objTrans = CREATEOBJECT("NameTranslate")
objTrans.Init 1, strDomain
objTrans.SET 3, strDomain & "\" & strUserName 
strUserDN = objTrans.GET(1) 
GetUserDN = strUserDN


END FUNCTION


Ahora eliminar varios usuarios con el mismo Script


Set objOU = GetObject("LDAP://ou=ingenieria,dc=acme,dc=com")
objOU.Delete "user", "cn=usuario1"
Set objOU = GetObject("LDAP://ou=ingenieria,dc=acme,dc=com") 
objOU.Delete "user", "cn=usuario2"

Listar los integrantes de una unidad organizativa




'Global variables
    Dim oContainer
    Dim OutPutFile
    Dim FileSystem
'Initialize global variables
    Set FileSystem = WScript.CreateObject("Scripting.FileSystemObject")
    Set OutPutFile = FileSystem.CreateTextFile("Listadeproduccion.txt", True) 
    Set oContainer=GetObject("LDAP://OU=produccion,DC=acme,DC=com")
'Enumerate Container
    EnumerateUsers oContainer
'Clean up
    OutPutFile.Close
    Set FileSystem = Nothing
    Set oContainer = Nothing
    WScript.Echo "Archivo creado"
    WScript.Quit(0)
Sub EnumerateUsers(oCont)
    Dim oUser
    For Each oUser In oCont
        Select Case LCase(oUser.Class)
               Case "user"
                    If Not IsEmpty(oUser.distinguishedName) Then
                       OutPutFile.WriteLine "dn: " & oUser.distinguishedName
                    End If
                    If Not IsEmpty(oUser.name) Then
                       OutPutFile.WriteLine "name: " & oUser.Get ("name")
                    End If
                    If Not IsEmpty(oUser.userPrincipalName) Then
                       OutPutFile.WriteLine "Login: " & oUser.userPrincipalName
                    End If
                    If Not IsEmpty(oUser.givenName) Then
                       OutPutFile.WriteLine "Nombres completos: " & oUser.givenName
                    End If
                    If Not IsEmpty(oUser.sn) Then
                       OutPutFile.WriteLine "Apellidos: " & oUser.sn
                    End If
                    If Not IsEmpty(oUser.telephoneNumber) Then
                       OutPutFile.WriteLine "Teléfono: " & oUser.telephoneNumber
                    End If
               Case "organizationalunit", "container"
                    EnumerateUsers oUser
        End Select
        OutPutFile.WriteLine
    Next
End Sub




Obtener el nombre de los servidores que tienen los roles principales del domino (FSMO Flexible Single Master Operations).




SET objRootDSE = GETOBJECT("LDAP://rootDSE")


' Schema Master
SET objSchema = GETOBJECT _
    ("LDAP://" & objRootDSE.GET("schemaNamingContext"))
strSchemaMaster = objSchema.GET("fSMORoleOwner")
SET objNtds = GETOBJECT("LDAP://" & strSchemaMaster)
SET objComputer = GETOBJECT(objNtds.Parent)
strSchemaMaster = objComputer.dNSHostName


' Domain Naming Master
SET objPartitions = GETOBJECT("LDAP://CN=Partitions," & _ 
    objRootDSE.GET("configurationNamingContext"))
strDomainNamingMaster = objPartitions.GET("fSMORoleOwner")
SET objNtds = GETOBJECT("LDAP://" & strDomainNamingMaster)
SET objComputer = GETOBJECT(objNtds.Parent)
strDomainNamingMaster = objComputer.dNSHostName


' PDC Emulator
SET objDomain = GETOBJECT _
    ("LDAP://" & objRootDSE.GET("defaultNamingContext"))
strPdcEmulator = objDomain.GET("fSMORoleOwner")
SET objNtds = GETOBJECT("LDAP://" & strPdcEmulator)
SET objComputer = GETOBJECT(objNtds.Parent)
strPdcEmulator = objComputer.dNSHostName


' RID Master
SET objRidManager = GETOBJECT("LDAP://CN=RID Manager$,CN=System," & _
    objRootDSE.GET("defaultNamingContext"))
strRidMaster = objRidManager.GET("fSMORoleOwner")
SET objNtds = GETOBJECT("LDAP://" & strRidMaster)
SET objComputer = GETOBJECT(objNtds.Parent)
strRidMaster = objComputer.dNSHostName


' Infrastructure Master
SET objInfrastructure = GETOBJECT("LDAP://CN=Infrastructure," & _
    objRootDSE.GET("defaultNamingContext"))
strInfrastructureMaster = objInfrastructure.GET("fSMORoleOwner")
SET objNtds = GETOBJECT("LDAP://" & strInfrastructureMaster)
SET objComputer = GETOBJECT(objNtds.Parent)
strInfrastructureMaster = objComputer.dNSHostName




WScript.Echo "Bosque de dominio maestro FSMO: " & strDomainNamingMaster & vbcrlf & _
    "Bosque del esquema maestro FSMO: " & strSchemaMaster & vbcrlf & _
    "Infrastuctura del dominio FSMO: " & strInfrastructureMaster & vbcrlf & _
    "Dominios RID Maestro FSMO: " & strRidMaster & vbcrlf & _
    "Dominios PDC Emulator FSMO: " & strPdcEmulator


Si desea descargar todos estos Scripts , dale acá