Archive for January 2013

VBScript to get Active Directory User Logon Information, Disable and Move

vb

What does this VBScript script do?

  • Checks all accounts to determine what needs to be disabled.
  • If LastLogonTimeStamp is Null and object is older than specified date, it is disabled and moved.
  • If account has been used, but not within duration specified, it is disabled and moved.
  • If account is already disabled it is left where it is.

Please adjust the variables according to your AD and copy into a Notepad file with an extension of .vbs and run

  • ADVBScript_Script.vbs

‘===========================================================================
‘ Checks all accounts to determine what needs to be disabled.
‘ If LastLogonTimeStamp is Null and object is older than specified date, it is disabled and moved.
‘ If account has been used, but not within duration specified, it is disabled and moved.
‘ If account is already disabled it is left where it is.
‘ Created 23/7/09 by Grant Brunton
‘===========================================================================

‘===========================================================================
‘ BEGIN USER VARIABLES
‘===========================================================================

‘ * Change this to your domain *
‘DSEroot=”DC=domain,DC=local”

‘ Flag to enable the disabling and moving of unused accounts
‘ 1 – Will Disable and move accounts
‘ 0 – Will create ouput log only
bDisable=0

‘ Number of days before an account is deemed inactive
‘ Accounts that haven’t been logged in for this amount of days are selected
iLogonDays=30

‘ LDAP Location of OUs to search for accounts
‘ LDAP location format eg: “OU=Users,OU=Test”
strSearchOU=”OU=Users”

‘ Search depth to find users
‘ Use “OneLevel” for the specified OU only or “Subtree” to search all child OUs as well.
strSearchDepth=”OneLevel”

‘ Location of new OU to move disabled user accounts to
‘ eg: “OU=Disabled Users,OU=Test”
strNewOU=”OU=_Disabled”

‘ Log file path (include trailing \ )
‘ Use either full directory path or relational to script directory
strLogPath=”.\logs\”

‘ Error log file name prefix (tab delimited text file. Name will be appended with date and .err extension)
strErrorLog=”DisabledAccounts_”

‘ Output log file name prefix (tab delimited text file. Name will be appended with date and .log extension)
strOutputLog=”DisabledAccounts_”

‘===========================================================================
‘ END USER VARIABLES
‘===========================================================================

‘===========================================================================
‘ MAIN CODE BEGINS
‘===========================================================================
sDate = Year(Now()) & Right(“0” & Month(Now()), 2) & Right(“0” & Day(Now()), 2)
Set oFSO=CreateObject(“Scripting.FileSystemObject”)
If Not oFSO.FolderExists(strLogPath) Then CreateFolder(strLogPath)
Set output=oFSO.CreateTextFile(strLogPath & strOutputLog & sDate & “.log”)
Set errlog=oFSO.CreateTextFile(strLogPath & strErrorLog & sDate & “.err”)
output.WriteLine “Sam Account Name” &vbTab& “LDAP Path” &vbTab& “Last Logon Date” &vbTab& “Date Created” &vbTab& “Home Directory”
errlog.WriteLine “Sam Account Name” &vbTab& “LDAP Path” &vbTab& “Problem” &vbTab& “Error”

Set rootDSE = GetObject(“LDAP://rootDSE”)
Set objConnection = CreateObject(“ADODB.Connection”)
objConnection.Open “Provider=ADsDSOObject;”
Set ObjCommand = CreateObject(“ADODB.Command”)
ObjCommand.ActiveConnection = objConnection
ObjCommand.Properties(“Page Size”) = 10
DSEroot=rootDSE.Get(“DefaultNamingContext”)

Set objNewOU = GetObject(“LDAP://” & strNewOU & “,” & DSEroot)
ObjCommand.CommandText = “<ldap: “=”” &=”” strsearchou=”” “,”=”” dseroot=””>;(&(objectClass=User)(objectcategory=Person));adspath;” & strSearchDepth

msgbox “<ldap: “=”” &=”” strsearchou=”” “,”=”” dseroot=””>;(&(objectClass=User)(objectcategory=Person));adspath;” & strSearchDepth

Set objRecordset = ObjCommand.Execute

On Error Resume Next

While Not objRecordset.EOF
LastLogon = Null
intLogonTime = Null

Set objUser=GetObject(objRecordset.fields(“adspath”))

If DateDiff(“d”,objUser.WhenCreated,Now) > iLogonDays Then
Set objLogon=objUser.Get(“lastlogontimestamp”)
If Err.Number &lt;&gt; 0 Then
WriteError objUser, “Get LastLogon Failed”
DisableAccount objUser, “Never”
Else
intLogonTime = objLogon.HighPart * (2^32) + objLogon.LowPart
intLogonTime = intLogonTime / (60 * 10000000)
intLogonTime = intLogonTime / 1440
LastLogon=intLogonTime+#1/1/1601#

If DateDiff(“d”,LastLogon,Now) > iLogonDays Then
DisableAccount objUser, LastLogon
End If
End If
End If
WriteError objUser, “Unknown Error”
objRecordset.MoveNext
Wend
‘===========================================================================
‘ MAIN CODE ENDS
‘===========================================================================

‘===========================================================================
‘ SUBROUTINES
‘===========================================================================
Sub CreateFolder( strPath )
If Not oFSO.FolderExists( oFSO.GetParentFolderName(strPath) ) Then Call CreateFolder( oFSO.GetParentFolderName(strPath) )
oFSO.CreateFolder( strPath )
End Sub

Sub DisableAccount( objUser, lastLogon )
On Error Resume Next
If bDisable <> 0 Then
If objUser.accountdisabled=False Then
objUser.accountdisabled=True
objUser.SetInfo
WriteError objUser, “Disable Account Failed”
objNewOU.MoveHere objUser.adspath, “CN=”&amp;objUser.CN
WriteError objUser, “Account Move Failed”
Else
Err.Raise 1,,”Account already disabled. User not moved.”
WriteError objUser, “Disable Account Failed”
End If
End If
output.WriteLine objUser.samaccountname &vbTab& objUser.adspath &vbTab& lastLogon &vbTab& objUser.whencreated &vbTab& objUser.homedirectory
End Sub

Sub WriteError( objUser, strProblem )
If Err.Number &lt;&gt; 0 Then
errlog.WriteLine objUser.samaccountname &vbTab& objUser.adspath &vbTab& strProblem &vbTab& Replace(Err.Description,vbCrlf,””)
Err.Clear
End If
End Sub

‘===========================================================================
‘ END SUBROUTINES
‘===========================================================================

Powershell Script to get Active Directory User Logon Information

PowerShell

To get the last logon Date/Time of Users in AD

$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher
$ADSearch.PageSize = 100
$ADSearch.SearchScope = “subtree”
$ADSearch.SearchRoot = “LDAP://$Domain”
$ADSearch.Filter = “(objectClass=user)”
$ADSearch.PropertiesToLoad.Add(“distinguishedName”)
$ADSearch.PropertiesToLoad.Add(“sAMAccountName”)
$ADSearch.PropertiesToLoad.Add(“lastLogonTimeStamp”)
$userObjects = $ADSearch.FindAll()

foreach ($user in $userObjects)
{
$dn = $user.Properties.Item(“distinguishedName”)
$sam = $user.Properties.Item(“sAMAccountName”)
$logon = $user.Properties.Item(“lastLogonTimeStamp”)
if($logon.Count -eq 0)
{
$lastLogon = “Never”
}
else
{
$lastLogon = [DateTime]$logon[0]
$lastLogon = $lastLogon.AddYears(1600)
}

“””$dn””,$sam,$lastLogon”
}

Script explained by David Hoelzer

Many Thanks for this excellent explanation

Scripting Video

 

Configure SNMP on VMware

What is SNMP?

Simple Network Management Protocol (SNMP) is an “Internet-standard protocol for managing devices on IP networks.” Devices that typically support SNMP include routers, switches, servers, workstations, printers, modem racks, and more.” It is used mostly in network management systems to monitor network-attached devices for conditions that warrant administrative attention. SNMP is a component of the Internet Protocol Suite as defined by the Internet Engineering Task Force (IETF). It consists of a set of standards for network management, including an application layer protocol, a database schema, and a set of data objects.

SNMP exposes management data in the form of variables on the managed systems, which describe the system configuration. These variables can then be queried (and sometimes set) by managing application

SNMP

SNMP Agents

vCenter Server and ESXi systems include different SNMP agents.

  • vCenter Server SNMP agent

The SNMP agent included with vCenter Server can send traps when the vCenter Server system is started or when an alarm is triggered on vCenter Server. The vCenter Server SNMP agent functions only as a trap emitter and does not support other SNMP operations (for example, GET).

You can manage the vCenter Server agent with the vSphere Client or the vSphere Web Client but not with the vCLI command.

  • Host-based embedded SNMP agent

ESXi 4.0 and later includes an SNMP agent embedded in the host daemon (hostd) that can send traps and receive polling requests such as GET requests.
You can manage SNMP on ESXi hosts with the vicfg-snmp vCLI command or with the ESXCLI command in 5.1

  • Net-SNMP-based agent

Versions of ESX released before ESX/ESXi 4.0 include a Net-SNMP-based agent. You can continue to use this Net-SNMP-based agent in ESX 4.x with MIBs supplied by your hardware vendor and other third-party management applications. However, to use the VMware MIB files, you must use the host-based embedded SNMP agent.

 Configure SNMP Settings on a vCenter Server

You can configure up to four receivers to receive SNMP traps from vCenter Server. For each receiver, specify a host name, port, and community.

  • If necessary, select Administration > vCenter Server Settings to display the vCenter Server Settings dialog box.
  • If the vCenter Server system is part of a connected group, select the server you want to configure from the Current vCenter Server drop-down menu.
  • In the settings list, select SNMP.
  • In Receiver URL, enter the host name or IP address of the SNMP receiver.
  • In the field next to the Receiver URL field, enter the port number of the receiver.
  • The port number must be a value between 1 and 65535.
  • In Community, enter the community identifier.

snmp

Configure SNMP for ESXi

ESXi includes an SNMP agent that can

  • Send notifications (traps and informs)
  • Receive GET, GETBULK, and GETNEXT requests

In ESXi 5.1 and later releases, the SNMP agent adds support for version 3 of the SNMP protocol, offering increased security and improved functionality, including the ability to send informs. You can use esxcli commands to enable and configure the SNMP agent. You configure the agent differently depending on whether you want to use SNMP v1/v2c or SNMP v3.

As an alternative to configuring SNMP manually using esxcli commands, you can use host profiles to configure SNMP for an ESXi host.

Procedure

  • Configure SNMP Communities.

Configure the SNMP Agent. You have the following 2 choices:

  • Configuring the SNMP Agent to Send Traps
  • Configuring the SNMP Agent for Polling

Instructions for Sending Traps

  • Configure at least one community for the agent

An SNMP community defines a group of devices and management systems. Only devices and management systems that are members of the same community can exchange SNMP messages. A device or management system can be a member of multiple communities. In the example below you can see Public and Internal

  • Log into vMA
  • Type vifp addserver
  • Type vifptarget -s
  • Type vicfg-snmp -c public,Internal for each Host that you have.

snmp1

  • Each time you specify a community with this command, the settings that you specify overwrite the previous configuration.
  • Next configure the SNMP Agent to Send Traps

You can use the SNMP agent embedded in ESXi to send virtual machine and environmental traps to management systems. To configure the agent to send traps, you must specify a target (receiver) address, the community, and an optional port. If you do not specify a port, the SNMP agent sends traps to UDP port 162 on the target management system by default

Each time you specify a target with this command, the settings you specify overwrite all previously specified settings. To specify multiple targets, separate them with a comma.
You can change the port that the SNMP agent sends data to on the target using the -t option. That port is UDP 162 by default

  • Enable the SNMP agent if it is not yet running.
  • vicfg-snmp -E
  • (Optional) Send a test trap to verify that the agent is configured correctly.
  • vicfg-snmp <conn_options> –test

Instructions for Polling

  • Configure at least one community for the agent

An SNMP community defines a group of devices and management systems. Only devices and management systems that are members of the same community can exchange SNMP messages. A device or management system can be a member of multiple communities.

  • Type vicfg-snmp -c public, internal
  • Each time you specify a community with this command, the settings that you specify overwrite the previous configuration
  • (Optional) Specify a port for listening for polling requests
  • vicfg-snmp <conn_options> -p 162
  • (Optional) If the SNMP agent is not enabled, enable it
  • vicfg-snmp -E
  • Run vicfg-snmp -T to validate the configuration.

The following example shows how the commands are run in sequence.

  • vicfg-snmp <conn_options> –c public –t example.com@162/private -E
  • next validate your config by doing these things
  • vicfg-snmp <conn_options> -T
  • walk –v1 –c public esx-host

SNMP Diagnostics

  • Type esxcli system snmp test to prompt the SNMP agent to send a test warmStart trap.
  • Type esxcli system snmp get to display the current configuration of the SNMP agent.

Configure SNMP Management Client Software

After you have configured a vCenter Server system or an ESXi host to send traps, you must configure your management client software to receive and interpret those traps.

To configure your management client software

  • Specify the communities for the managed device
  • Configure the port settings
  • Load the VMware MIB files. See the documentation for your management system for specific instructions for these steps.

Instructions

  • Download the VMware MIB files from the VMware Web site: http://communities.vmware.com/community/developer/managementapi.
  • In your management software, specify the vCenter Server or ESXi host as an SNMP-based managed device.
  • If you are using SNMP v1 or v2c, set up appropriate community names in the management software.
  • These names must correspond to the communities set for the SNMP agent on the vCenter Server system or ESXi host.
  • If you are using SNMP v3, configure users and authentication and privacy protocols to match those configured on the ESXi host.
  • If you configured the SNMP agent to send traps to a port on the management system other than the default UDP port 162, configure the management client software to listen on the port you configured.
  • Load the VMware MIBs into the management software so you can view the symbolic names for the vCenter Server or host variables.
  • To prevent lookup errors, load these MIB files in the following order before loading other MIB files:

VMWARE-ROOT-MIB.mib
VMWARE-TC-MIB.mib
VMWARE-PRODUCTS-MIB.mib

  • The management software can now receive and interpret traps from vCenter Server or ESXi hosts.

ESXCLI in vSphere 5 for managing SNMP

You can also now use ESXCLI commands to set up and manage SNMP as per below screenprints

snmp esxcli