четверг, 7 августа 2008 г.

Добавление объекта(ов) AD в группу(ы)

есть такая необходимость добавлять объекты определенного назначения или типа.. в группы...
например добавить все компьютеры начинающиеся на 22IVC в группы начинающиеся или содержащие IVC:

ну вот по такому случаю накидал небольшой скрипт :)

1) это для добавления объектов "Компьютеры" в группы

'-===================================================
const kErrorSuccess = 0
const KErrorFailure = 1
const ActionListObject = 1
const ActionAddObject = 2

main

sub main

dim strBaseDNObj
dim iScopeObj
dim strBaseDNGroup
dim iScopeGroup
dim strGroupMask
dim strObjMask
dim iRetval
dim iAction

strObjMask=""
StrGroupMask=""

iRetval = ParseCommandLine(iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask)

if iRetval = kErrorSuccess then

if strBaseDNObj="" then
set rootDSE = GetObject("LDAP://RootDSE")
strBaseDNObj = rootDSE.get("DefaultNamingContext")
end if

if strBaseDNGroup="" then
set rootDSE = GetObject("LDAP://RootDSE")
strBaseDNGroup = rootDSE.get("DefaultNamingContext")
end if


if iScopeObj = "" then
iScopeObj = 2
end if

if iScopeGroup = "" then
iScopeGroup = 2
end if

AddObjectToGroup iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask

end if

end sub


' Get Object List by Mask
sub AddObjectToGroup(iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask)

set con = CreateObject("ADODB.Connection")
con.Provider = "ADSDsoObject"
con.open("Active Directory Provider")
'Find Objects
set command_ = CreateObject("ADODB.Command")
command_.ActiveConnection = con
command_.CommandText = "select name, distinguishedName from 'LDAP://" & StrBaseDNObj & _
"' where ObjectCategory='computer' and name='"&strObjMask&"'"

command_.Properties("searchscope") = IScopeObj

set rc = CreateObject("ADODB.Recordset")
set rc = command_.execute

'Find Group
set command02 = CreateObject("ADODB.Command")
command02.ActiveConnection = con
command02.Commandtext = "select name, distinguishedName from 'LDAP://" & StrBaseDNGroup & _
"' where ObjectCategory='Group' and name='"&strGroupMask&"'"

command02.Properties("searchscope") = IScopeGroup

set rc02 = CreateObject("ADODB.Recordset")
set rc02 = command02.execute

while not (rc02.EOF)
set Group_ = GetObject("LDAP://" & rc02.Fields("distinguishedName").Value)
WScript.Echo "Group "& group_.name
WScript.Echo "-----------------------------------------------"
while not (rc.EOF)
set User_ = GetObject("LDAP://" & rc.Fields("distinguishedName").Value)
if Group_.ismember(User_.AdsPath)=false then
WScript.Echo user_.name & " isn't member of " & Group_.name
if iAction=ActionAddObject then
Group_.add(User_.AdsPath)
group_.SetInfo
end if
else WScript.Echo user_.name & " member of " & Group_.name
end if
rc.movenext()
wEnd
rc.MoveFirst()
rc02.movenext()
WScript.Echo ""
wEnd
end sub


'
' Parse the command line into it's components
'
function ParseCommandLine(iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask)

on error resume next

dim iIndex
iAction = ActionListObject
iIndex = 0

set oArgs = wscript.Arguments

while iIndex <> oArgs.Count
select case oArgs(iIndex)
case "-b1"
iIndex = iIndex + 1
strBaseDNObj = oArgs(iIndex)
case "-t1"
iIndex = iIndex + 1
iScopeObj = oArgs(iIndex)
case "-b2"
iIndex = iIndex + 1
strBaseDNGroup = oArgs(iIndex)
case "-t2"
iIndex = iIndex + 1
iScopeGroup = oArgs(iIndex)
case "-g"
iIndex = iIndex + 1
strGroupmask = oArgs(iIndex)
case "-m"
iIndex = iIndex + 1
strObjMask = oArgs(iIndex)
case "-a"
iAction = ActionAddObject
case "-?"
Usage(true)
exit function

case else
Usage(true)
exit function

end select

iIndex = iIndex + 1

wend

if Err = kErrorSuccess then

ParseCommandLine = kErrorSuccess

else

wscript.echo "Unable to parse command line, error 0x" & _
Hex(Err.Number) & ". " & Err.Description

ParseCommandLine = kErrorFailure

end if

end function



sub Usage(bExit)

wscript.echo "Usage: CompMaskAdd.vbs [-b1 base search dn] [-t1 search scope]"
wscript.echo " [-b2 base search dn] [-t2 search scope]"
wscript.echo " [-g group mask] [-m computer object mask]"
wscript.echo " [-a]"
wscript.echo ""
wscript.echo "Arguments:"
wscript.echo " -b1 - DN of base search for object. Default - default naming context"
wscript.echo " -t1 - search scope for object. 0 - base, 1 - one level, 2 - subtree. default - 2"
wscript.echo " -b2 - DN of base search for group. Default - default naming context"
wscript.echo " -t2 - search scope for group. 0 - base, 1 - one level, 2 - subtree. default - 2"
wscript.echo " -g - Mask of group. default - """
wscript.echo " -m - mask of computer. default - """
wscript.echo " -a - make change to group. if not specified list group and members"
wscript.echo " -? - display command usage"
wscript.echo ""

if bExit then
wscript.quit(1)
end if

end sub

'-==============================================

2) этот для добавления пользователей в группы

'-==============================================
const kErrorSuccess = 0
const KErrorFailure = 1
const ActionListObject = 1
const ActionAddObject = 2

main

sub main

dim strBaseDNObj
dim iScopeObj
dim strBaseDNGroup
dim iScopeGroup
dim strGroupMask
dim strObjMask
dim iRetval
dim iAction

strObjMask=""
StrGroupMask=""

iRetval = ParseCommandLine(iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask)

if iRetval = kErrorSuccess then

if strBaseDNObj="" then
set rootDSE = GetObject("LDAP://RootDSE")
strBaseDNObj = rootDSE.get("DefaultNamingContext")
end if

if strBaseDNGroup="" then
set rootDSE = GetObject("LDAP://RootDSE")
strBaseDNGroup = rootDSE.get("DefaultNamingContext")
end if


if iScopeObj = "" then
iScopeObj = 2
end if

if iScopeGroup = "" then
iScopeGroup = 2
end if

AddObjectToGroup iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask

end if

end sub


' Get Object List by Mask
sub AddObjectToGroup(iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask)

set con = CreateObject("ADODB.Connection")
con.Provider = "ADSDsoObject"
con.open("Active Directory Provider")
'Find Objects
set command_ = CreateObject("ADODB.Command")
command_.ActiveConnection = con
command_.CommandText = "select name, distinguishedName from 'LDAP://" & StrBaseDNObj & _
"' where ObjectCategory='User' and name='"&strObjMask&"'"

command_.Properties("searchscope") = IScopeObj

set rc = CreateObject("ADODB.Recordset")
set rc = command_.execute

'Find Group
set command02 = CreateObject("ADODB.Command")
command02.ActiveConnection = con
command02.Commandtext = "select name, distinguishedName from 'LDAP://" & StrBaseDNGroup & _
"' where ObjectCategory='Group' and name='"&strGroupMask&"'"

command02.Properties("searchscope") = IScopeGroup

set rc02 = CreateObject("ADODB.Recordset")
set rc02 = command02.execute

while not (rc02.EOF)
set Group_ = GetObject("LDAP://" & rc02.Fields("distinguishedName").Value)
WScript.Echo "Group "& group_.name
WScript.Echo "-----------------------------------------------"
while not (rc.EOF)
set User_ = GetObject("LDAP://" & rc.Fields("distinguishedName").Value)
if Group_.ismember(User_.AdsPath)=false then
WScript.Echo user_.name & " isn't member of " & Group_.name
if iAction=ActionAddObject then
Group_.add(User_.AdsPath)
group_.SetInfo
end if
else WScript.Echo user_.name & " member of " & Group_.name
end if
rc.movenext()
wEnd
rc.MoveFirst()
rc02.movenext()
WScript.Echo ""
wEnd
end sub


'
' Parse the command line into it's components
'
function ParseCommandLine(iAction, strBaseDNObj, iScopeObj, strBaseDNGroup, iScopeGroup, strGroupmask, strObjMask)

on error resume next

dim iIndex
iAction = ActionListObject
iIndex = 0

set oArgs = wscript.Arguments

while iIndex <> oArgs.Count
select case oArgs(iIndex)
case "-b1"
iIndex = iIndex + 1
strBaseDNObj = oArgs(iIndex)
case "-t1"
iIndex = iIndex + 1
iScopeObj = oArgs(iIndex)
case "-b2"
iIndex = iIndex + 1
strBaseDNGroup = oArgs(iIndex)
case "-t2"
iIndex = iIndex + 1
iScopeGroup = oArgs(iIndex)
case "-g"
iIndex = iIndex + 1
strGroupmask = oArgs(iIndex)
case "-m"
iIndex = iIndex + 1
strObjMask = oArgs(iIndex)
case "-a"
iAction = ActionAddObject
case "-?"
Usage(true)
exit function

case else
Usage(true)
exit function

end select

iIndex = iIndex + 1

wend

if Err = kErrorSuccess then

ParseCommandLine = kErrorSuccess

else

wscript.echo "Unable to parse command line, error 0x" & _
Hex(Err.Number) & ". " & Err.Description

ParseCommandLine = kErrorFailure

end if

end function



sub Usage(bExit)

wscript.echo "Usage: CompMaskAdd.vbs [-b1 base search dn] [-t1 search scope]"
wscript.echo " [-b2 base search dn] [-t2 search scope]"
wscript.echo " [-g group mask] [-m computer object mask]"
wscript.echo " [-a]"
wscript.echo ""
wscript.echo "Arguments:"
wscript.echo " -b1 - DN of base search for object. Default - default naming context"
wscript.echo " -t1 - search scope for object. 0 - base, 1 - one level, 2 - subtree. default - 2"
wscript.echo " -b2 - DN of base search for group. Default - default naming context"
wscript.echo " -t2 - search scope for group. 0 - base, 1 - one level, 2 - subtree. default - 2"
wscript.echo " -g - Mask of group. default - """
wscript.echo " -m - mask of computer. default - """
wscript.echo " -a - make change to group. if not specified list group and members"
wscript.echo " -? - display command usage"
wscript.echo ""

if bExit then
wscript.quit(1)
end if

end sub

'-==============================================

запускается все cscript'ом

-b1 - базовый DN с которого ищем компьютеры/пользователей
-b2 - базовый DN с которого ищем группы
-t1 и t2 - область поиска.. 0 - база (тоесть в этом контейнере).. 1- один уровень.. 2 - по дереву...
-g -маска группы
-m - маска компа/пользователя
-a - осуществить добавление пользователей/компов в группы , если не указан.. то просто вывести на экран найденных пользователей/компов и групп...

примеры использования..

возьмем пример с компами... сохраним первый скрипт в файл AddCompToGroupWithMask.vbs
запускаем : cscript AddCompToGroupWithMask.vbs -m "22IVC*" -g "*IVC*" -a
это добавление всех объектов компов начинающихся с 22IVC в группы содержащие в названии IVC.. по всему контексту именования по умолчанию (DefaulNamingContext.. можно узнать с помощью скрипта в предыдущем сообщении)...

можно например выполнить cscript AddCompToGroupWithMask.vbs -m "*" -g "*" -a (добавление всех компов.. во все группы... :))



Комментариев нет: