Note: You are currently viewing documentation for Moodle 2.0. Up-to-date documentation for the latest stable version is available here: SIMS2AD access manager.vbs.

SIMS2AD access manager.vbs

From MoodleDocs
'On Error Resume Next

'/////////////////////////////////////////////////////////////////////////////
'//                                                                         //
'// NOTICE OF COPYRIGHT                                                     //
'//                                                                         //
'// SIMS2AD - Script to administer active directory accounts from SIMS.net  //
'//                                                                         //
'// Copyright (C) 2008 onwards  Ian Tasker  http://www.uctc.e-sussex.sch.uk //
'//                                                                         //
'// This program is free software; you can redistribute it and/or modify    //
'// it under the terms of the GNU General Public License as published by    //
'// the Free Software Foundation; either version 2 of the License, or       //
'// (at your option) any later version.                                     //
'//                                                                         //
'// This program is distributed in the hope that it will be useful,         //
'// but WITHOUT ANY WARRANTY; without even the implied warranty of          //
'// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           //
'// GNU General Public License for more details:                            //
'//                                                                         //
'//          http://www.gnu.org/copyleft/gpl.html                           //
'//                                                                         //
'/////////////////////////////////////////////////////////////////////////////

'+------------------------------------------------------------------------+
'| SIMS-AD Access Manager Script Configuration                            |
'+------------------------------------------------------------------------+

'The script will configure students access to the college network
'depending on settings stored in User Defined Fields within SIMS.net

'The students account must have the employeeID set as the UPN


'+------------------------------------------------------------------------+
'| Connection Setting for SIMS SQL Server                                 |
'+------------------------------------------------------------------------+
const SIMS_USER = ""
const SIMS_PASS = ""
const SIMS_SERVER = "xx.xx.xx.xx,1427\[Instance Name]"
const SIMS_DB = "sims"

'+------------------------------------------------------------------------+
'| DO NOT EDIT ANYTHING BELOW THIS POINT                                  |
'+------------------------------------------------------------------------+

Const adOpenStatic     = 3
Const adLockOptimistic = 3
Const adUseClient      = 3
Const adBookMarkFirst  = 1

Const ADS_PROPERTY_UPDATE = 2
Const ADS_SCOPE_SUBTREE = 2
Const ADS_UF_ACCOUNTDISABLE = 2
Const ADS_PROPERTY_APPEND = 3

Const STUDENT_FORNAME = 1
Const STUDENT_SURNAME = 2
Const STUDENT_UPN = 0
Const STUDENT_TYPE = 3
Const STUDENT_DESCRIPTION = 4

'+------------------------------------------------------------------------+
'| Globals                                                      			   |
'+------------------------------------------------------------------------+

Dim SIMS_Connection
Dim objSIMSConnection 'SIMS database connection
Dim objSIMSRecordSet  'SIMS database connection
Dim objADConnection   'AD connection
Dim objADCommand      'AD command
Dim objADRecordSet    'AD RecordSet
Dim objADObject		  'AD Object
Dim objADClass		  'AD Class
Dim objADChild		  'AD Class
Dim objADAttribute
Dim strCommandType    'The execution type
Dim strSQL	      	  'SQL Query
Dim ArrStudents
Dim count
Dim flgChangedGroups


Const FullAccess = 4
Const NoAccess = 5
Const LessonOnlyE4Group = 0
Const LessonOnlyL4Group = 1
Const Lesson_Evening_OnlyE4Group = 2
Const Lesson_Evening_OnlyL4Group = 3

Const ADGroupName = 0
Const SIMSLookupText = 1
Const LogMessage = 2
Const InternetBannedGroup = 5

dim arrGroups(5,2)

ArrGroups(0,0) = "SIMS2AD_LessonOnly_E4"
ArrGroups(0,1) = "Lesson Only - E4 TT"
ArrGroups(0,2) = "Computer access restricted to Lessons Only, students lunch is E4"

ArrGroups(1,0) = "SIMS2AD_LessonOnly_L4"
ArrGroups(1,1) = "Lesson Only - L4 TT"
ArrGroups(1,2) = "Computer access restricted to Lessons Only, students lunch is L4"

ArrGroups(2,0) = "SIMS2AD_Lesson_Evening_Only_E4"
ArrGroups(2,1) = "Lessons & Evening Only - E4 TT"
ArrGroups(2,2) = "Computer access restricted to Lessons & Evening Access (6-8 PM) Only, students lunch is E4"

ArrGroups(3,0) = "SIMS2AD_Lesson_Evening_Only_L4"
ArrGroups(3,1) = "Lessons & Evening Only - L4 TT"
ArrGroups(3,2) = "Computer access restricted to Lessons & Evening Access (6-8 PM) Only, students lunch is L4"

ArrGroups(4,0) = "Full Access"
ArrGroups(4,1) = "Full Access"
ArrGroups(4,2) = "Computer Access Allowed"

ArrGroups(5,0) = "No Access"
ArrGroups(5,1) = "No Access"
ArrGroups(5,2) = "Computer Access Denied"

ArrGroups(5,0) = "Banned"
ArrGroups(5,1) = "Banned"
ArrGroups(5,2) = "Intenet Access Banned"

'---------LogToFile Configuration---------
'NOTE: Copy the configuration section To
'the beginning of an existing script. The
'values specified here must be set before
'calling the LogToFile sub.

'You can disable logging globally by
'setting the bEnableLogging option to false.
bEnableLogging = True

'Setting this to true will time stamp Each
'message that is logged to the log file
'with the current date and time.
bIncludeDateStamp = True

'This will set the log file name to the
'current date and time. You can use this
'option to create incremental log files.
bPrependDateStampInLogFileName = False

'Specify the log file location here. Path
'must contain a trailing backslash. If you
'would like to log to the same location as
'the currently running script, set this
'value to "relative" or uncomment out the
'line below.
'sLogFileLocation = "C:\LogFiles\"
sLogFileLocation = "relative"

'Specify the log file name here.
sLogFileName = "logtofiletest.txt"

'You can set whether or not you would like
'the script to append to an existing file,
'or if you would like it to overwrite
'existing copies. To overwrite set the
'sOverWriteORAppend variable to "overwrite"
sOverWriteORAppend = "append"

'Here you can set the maximum number of
'lines you like to record. If the maximum
'is reached the beginning of the log file
'will be pruned. Setting this to a value
'of 0 will disable this function.
vLogMaximumLines = 0

'This is just like limiting the log file
'to a number of lines but limits by the
'total size of the log file. This value
'is in bytes. Setting this to 0 will
'disable this function.
vLogMaximumSize = 0
'-------END LogToFile Configuration-------
'+------------------------------------------------------------------------+
'| Create Objects                                                                      |
'+------------------------------------------------------------------------+
Set objRoot = GetObject("LDAP://rootDSE")
Set objDomain = GetObject("LDAP://" & objRoot.Get("defaultNamingContext"))


Set objSIMSConnection = CreateObject("ADODB.Connection")
Set objSIMSRecordset = CreateObject("ADODB.Recordset")

Set objADConnection = CreateObject("ADODB.Connection")
Set objADCommand =   CreateObject("ADODB.Command")

Set objSysInfo = CreateObject("ADSystemInfo")

'+------------------------------------------------------------------------+
'| Set SQL Query Strings                                                       |
'+------------------------------------------------------------------------+
strSQL = "SELECT * FROM dbo.vbs_admanager"
SIMS_Connection  = "DRIVER={SQL Server};SERVER=" &  SIMS_SERVER &  ";UID=" & SIMS_USER & ";PWD=" &  SIMS_PASS & ";" & "DATABASE=" & SIMS_DB &";"

'+------------------------------------------------------------------------+
'| Set Other AD Related Items                                             |
'+------------------------------------------------------------------------+

Set objADRoot = GetObject("LDAP://rootDSE")
Set objADConnection = CreateObject("ADODB.Connection")
Set objADCommand = CreateObject("ADODB.Command")

objADConnection.Provider = "ADsDSOObject"
objADConnection.Open "Active Directory Provider"

Set objADCommand.ActiveConnection = objADConnection

objADCommand.Properties("Timeout") = 90       '60 is OK
objADCommand.Properties("Cache Results") = False
objADCommand.Properties("Page Size") = 1000
objADCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

'+------------------------------------------------------------------------+
'| Get Information from SIMS SQL Server                         |
'+------------------------------------------------------------------------+

objSIMSConnection.Open SIMS_Connection
objSIMSRecordset.CursorLocation = adUseClient
objSIMSRecordset.Open strSQL, objSIMSConnection, adOpenStatic, adLockOptimistic

ArrStudents = objSIMSRecordset.GetRows(, , Array("unique_pupil_no","forename","surname","type","description"))

objSIMSRecordset.Close


For count = 0 to ubound(ArrStudents,2)

	objADCommand.CommandText = _
   "SELECT distinguishedName FROM 'LDAP://" & objRoot.Get("defaultNamingContext") & "' WHERE objectCategory='user' " & _
       "AND employeeID='" & ArrStudents(STUDENT_UPN,count) &"'"
	Set objADRecordSet = objADCommand.Execute

	objADRecordSet.MoveFirst

	Set objUser = GetObject("LDAP://"& objADRecordSet.Fields("distinguishedName").Value)

	Do Until objADRecordSet.EOF

		if ArrStudents(STUDENT_TYPE,count) = "Network Access" then
			if ArrStudents(STUDENT_DESCRIPTION,count)= arrGroups(FullAccess,SIMSLookupText) then
				call AddGroup(arrGroups(FullAccess,0),objADRecordSet.Fields("distinguishedName"))
				if objUser.AccountDisabled = True then
					objUser.AccountDisabled = False
					objUser.SetInfo

					LogToFile(objADUser.displayName & ": " & left(objADUser.sAMAccountName,2) & " : " & arrGroups(NoAccess,LogMessage))
					Set comDLL=CreateObject("IADsTools.DCFunctions")
					Result=comDLL.ReplicaSync("SERVER4",objRoot.Get("defaultNamingContext"),"SERVER-5")
					If result=0 then
						LogToFile("SUCCESSFUL: Call to force AD replication.")
					else
						LogToFile("FAILED: Call to force AD replication.")
					end if
				end if
			elseif ArrStudents(STUDENT_DESCRIPTION,count)= arrGroups(LessonOnlyE4Group,SIMSLookupText) then
				'call AddGroup(arrGroups(LessonOnlyE4Group,ADGroupName),objADRecordSet.Fields("distinguishedName"))
			elseif ArrStudents(STUDENT_DESCRIPTION,count)= arrGroups(LessonOnlyL4Group,SIMSLookupText) then
				'call AddGroup(arrGroups(LessonOnlyL4Group,ADGroupName),objADRecordSet.Fields("distinguishedName"))
			elseif ArrStudents(STUDENT_DESCRIPTION,count)= arrGroups(Lesson_Evening_OnlyE4Group,SIMSLookupText) then
				'call AddGroup(arrGroups(Lesson_Evening_OnlyE4Group,ADGroupName),objADRecordSet.Fields("distinguishedName"))
			elseif ArrStudents(STUDENT_DESCRIPTION,count)= arrGroups(Lesson_Evening_OnlyL4Group,SIMSLookupText) then
				'call AddGroup(arrGroups(Lesson_Evening_OnlyL4Group,ADGroupName),objADRecordSet.Fields("distinguishedName"))
			elseif ArrStudents(STUDENT_DESCRIPTION,count)= "No Access" then
				if objUser.AccountDisabled = False then
					objUser.AccountDisabled = True
					objUser.SetInfo

					Set comDLL=CreateObject("IADsTools.DCFunctions")
					Result=comDLL.ReplicaSync("SERVER4",objRoot.Get("defaultNamingContext"),"SERVER-5")
					If result=0 then
						LogToFile("SUCCESSFUL: Call to force AD replication.")
					else
						LogToFile("FAILED: Call to force AD replication.")
					end if
				end if
			end if

		elseif ArrStudents(STUDENT_TYPE,count) = "Internet Access" then

			if ArrStudents(STUDENT_DESCRIPTION,count) = "Enabled" then
				Set objGroup = GetObject("LDAP://CN="& arrGroups(InternetBannedGroup,ADGroupName) & ",CN=Users," & objRoot.Get("defaultNamingContext"))
				If objGroup.IsMember("LDAP://" & objADRecordSet.Fields("distinguishedName").Value) Then
					objGroup.remove(objUser.ADsPath)
					LogToFile(objUser.displayName & ": " & left(objUser.sAMAccountName,2) & " : Internet Access Enabled.")
				End If

			elseif ArrStudents(STUDENT_DESCRIPTION,count) = "Disabled" then

				Set objGroup = GetObject("LDAP://CN="& arrGroups(InternetBannedGroup,ADGroupName) & ",CN=Users," & objRoot.Get("defaultNamingContext"))
				If Not objGroup.IsMember("LDAP://" & objADRecordSet.Fields("distinguishedName").Value) Then
					objGroup.add(objUser.ADsPath)
					LogToFile(objUser.displayName & ": " & left(objUser.sAMAccountName,2) & " : Internet Access Disabled.")
				End If

			end if
		end if
		objADRecordSet.MoveNext
	Loop
next

msgbox "done"


function AddGroup(strGroup,strAdUser)
	flgChangedGroups = 0
	Set objADUser = GetObject("LDAP://" & strAdUser)
	for i = 0 to ubound(arrGroups)
		if not arrGroups(i,ADGroupName) = ArrGroups(4,0) and not arrGroups(i,ADGroupName) = ArrGroups(5,0) then
			if strGroup = ArrGroups(4,0) then
				if not strGroup = arrGroups(i,ADGroupName) then
					Set objADGroup = GetObject("LDAP://CN="& arrGroups(i,ADGroupName) & ",CN=Users," & objRoot.Get("defaultNamingContext"))
					If objADGroup.IsMember("LDAP://" & strAdUser) Then
						objADGroup.remove(objADUser.ADsPath)
						flgChangedGroups = flgChangedGroups +1
					end if
				else
					If flgChangedGroups > 0 then
						LogToFile(objADUser.displayName & ": " & left(objADUser.sAMAccountName,2) & " : " & arrGroups(i,LogMessage))
					end if
				end if
			else
				if not arrGroups(i,ADGroupName) = ArrGroups(4,0) or arrGroups(i,ADGroupName) = ArrGroups(4,0) then
					Set objADGroup = GetObject("LDAP://CN="& arrGroups(i,ADGroupName) & ",CN=Users," & objRoot.Get("defaultNamingContext"))
					If objADGroup.IsMember("LDAP://" & strAdUser) Then
						if not strGroup = arrGroups(i,ADGroupName) then
							objADGroup.remove(objADUser.ADsPath)
							flgChangedGroups = flgChangedGroups +1
						end if
					Else
						if strGroup = arrGroups(i,ADGroupName) then
							objADGroup.add(objADUser.ADsPath)
							flgChangedGroups = flgChangedGroups +1
							LogToFile(objADUser.displayName & ": " & left(objADUser.sAMAccountName,2) & " : " & arrGroups(i,LogMessage))
						end if
					end if
				end if
			End If
		end if
	Next
end function




Sub LogToFile(Message)
    'LogToFile.vbs 10-18-07
    'This script is provided under the Creative Commons license located
    'at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
    'be used for commercial purposes with out the expressed written consent
    'of NateRice.com

    If bEnableLogging = False Then Exit Sub

    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    Set oLogFSO = CreateObject("Scripting.FileSystemObject")

    If sLogFileLocation = "relative" Then
        Set oLogShell = CreateObject("Wscript.Shell")
        sLogFileLocation = oLogShell.CurrentDirectory & "\"
        Set oLogShell = Nothing
    End If

    If bPrependDateStampInLogFileName Then
        sNow = Replace(Replace(Now(),"/","-"),":",".")
        sLogFileName = sNow & " - " & sLogFileName
        bPrependDateStampInLogFileName = False
    End If

    sLogFile = sLogFileLocation & sLogFileName

    If sOverWriteORAppend = "overwrite" Then
        Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
        sOverWriteORAppend = "append"
    Else
        Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForAppending, True)
    End If

    If bIncludeDateStamp Then
        Message = Now & "   " & Message
    End If

    oLogFile.WriteLine(Message)
    oLogFile.Close

    If vLogMaximumLines > 0 Then
      Set oReadLogFile = oLogFSO.OpenTextFile(sLogFile, ForReading, True)
      sFileContents = oReadLogFile.ReadAll
      aFileContents = Split(sFileContents, vbCRLF)
      If Ubound(aFileContents) > vLogMaximumLines Then
        sFileContents = Replace(sFileContents, aFileContents(0) & _
        vbCRLF, "", 1, Len(aFileContents(0) & vbCRLF))
        Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
        oLogFile.Write(sFileContents)
        oLogFile.Close
      End If
      oReadLogFile.Close
    End If

    If vLogMaximumSize > 0 Then
      Set oReadLogFile = oLogFSO.OpenTextFile(sLogFile, ForReading, True)
      sFileContents = oReadLogFile.ReadAll
      oReadLogFile.Close
      sFileContents = RightB(sFileContents, (vLogMaximumSize*2))
      Set oLogFile = oLogFSO.OpenTextFile(sLogFile, ForWriting, True)
      oLogFile.Write(sFileContents)
      oLogFIle.Close
    End If

    oLogFSO = Null
End Sub