How do I use a script to pass credentials to connect to Active Directory (AD)?

A. Normally, when you bind to AD, it uses your current credentials to determine the access level you have. You can, however, pass credentials by opening a Directory Services object instead and passing a username and password string. The following script, which you can download hereasks for a username and password, then uses them to connect to AD. It then reads an object from AD.

On Error Resume Next
Const ADS_SECURE_AUTHENTICATION = 1
Const ADS_USE_ENCRYPTION = 2


Dim uid, pwd, ldapPath

ldapPath = "LDAP://CN=Clark Kent,OU=Justice League,DC=savilltech,dc=com"

WScript.StdOut.Write "User name (with domain prefix): " 
uid = WScript.StdIn.ReadLine

WScript.StdOut.Write "Please enter your password:" 
pwd = WScript.StdIn.ReadLine


Dim LDAP 'As IADsOpenDSObject 
Set LDAP = GetObject("LDAP:") 
Set obj = LDAP.OpenDSObject(ldapPath, uid, pwd, _
ADS_USE_ENCRYPTION OR ADS_SECURE_AUTHENTICATION)

if err.number0 then 
    wscript.echo "Error connecting to AD " & err.number, err.description
    err.Clear
    Wscript.Quit(0)
end if

wscript.echo "SAM Account name is " & obj.sAMAccountName

The important line is the LDAP.OpenDSObject, which uses the username and password entered, as the following code shows:

D:\projects\VBScripts>cscript authtoad.vbs

User name (with domain prefix): savilltech\bruce
Please enter your password:password
SAM Account name is clark

You don't have to prompt for username or password; you can just set them as string variables or even hard code them, as the following example shows:

uid = "savilltech\bruce"
pwd = "password"

Dim LDAP 'As IADsOpenDSObject 
Set LDAP = GetObject("LDAP:") 
Set obj = LDAP.OpenDSObject(ldapPath, uid, pwd, _
    ADS_USE_ENCRYPTION OR ADS_SECURE_AUTHENTICATION)
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish