?
Solved

Script to find members in local system groups?

Posted on 2008-11-04
6
Medium Priority
?
1,111 Views
Last Modified: 2010-08-05
Hello,

I need a script to run against our servers around 200 Windows 2003 servers to find out what members are part of the local builtin account groups.  I need to find out all members of the RDP group, Local admin group, power users, etc...  A vbs or cmd script would work!

Please let me know if you need more information.

I appreciate the feedback!
0
Comment
Question by:mystikal1000
5 Comments
 

Expert Comment

by:OllarConsulting
ID: 22880388
Try this one... I just found it:

''==================================
''  Enumerate Active Directory Group Members
''  Author:            Shane Boudreaux
''  Start Date:            5/22/07
''  Last Modified:      5/22/07
''==================================

''==================================
'' GLOBAL DECLARES & CONSTANTS
''==================================
On Error Resume Next
Const ForAppending = 8
Const DOMAIN = "LDAP://DC=YourDomain,DC=com"
Const GROUPHEADER = "GROUP:"
Const GROUPFOOTER = "====================="

Dim groupName

'' prompt user for FULL group name
groupName = inputbox("Enter Full Group Name")

'' check if output file exists; create if doesn''t exist
fileExists "c:members.txt"

'' find the group and output members to text file
findGroup groupName

wscript.echo "DONE!"
'' display results text file
openFile

''========================
Private Sub findGroup(grp)

      Const ADS_SCOPE_SUBTREE = 2

      Set objConnection = CreateObject("ADODB.Connection")
      Set objCommand =   CreateObject("ADODB.Command")
      objConnection.Provider = "ADsDSOObject"
      objConnection.Open "Active Directory Provider"
      Set objCommand.ActiveConnection = objConnection

      objCommand.Properties("Page Size") = 5000
      objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE

      objCommand.CommandText = "SELECT ''distinguishedName'' FROM ''" & DOMAIN & "'' WHERE objectCategory=''group'' " & _
            "AND Name=''" & grp & "*''"

      Set objRecordSet = objCommand.Execute

      objRecordSet.MoveFirst
      Do Until objRecordSet.EOF
                group = objRecordSet.Fields("distinguishedName").Value
                        getMembers group
                objRecordSet.MoveNext
      Loop
End Sub
''========================

''========================
Private Sub getMembers(grp)
      Set objGroup = GetObject ("LDAP://" & grp)
      objGroup.GetInfo
      arrMemberOf = objGroup.GetEx("member")
      text = GROUPHEADER & vbcrlf & vbtab & grp & vbcrlf & GROUPFOOTER & vbcrlf & "MEMBERS:" & vbcrlf & GROUPFOOTER & vbcrlf
      For Each strMember in arrMemberOf
            ''Dim temp
            ''temp = pwdExpire(strMember)
            ''strMember = strMember & vbcrlf & temp
            text = text & strMember & vbcrlf
      Next
      AppendToFile text
End Sub
''========================

''========================
Private Sub AppendToFile(text)
      Set objFSO = CreateObject("Scripting.FileSystemObject")
      Set objFile = objFSO.OpenTextFile("C:members.txt", ForAppending)
      If text <> "" Then
            objFile.WriteLine text
      Else
            objFile.WriteLine "No Members OR Incorrect Input"
      End If
      objFile.Close
End Sub
''========================

''========================
Private Sub openFile()
      Const WIN_STYLE = 4
      Set objShell = WScript.CreateObject("WScript.Shell")
      objShell.Run "notepad.exe c:members.txt", WIN_STYLE
End Sub
''========================

''================================
Private Sub fileExists(file)
      '' NOTE: param file must be full path and file name!
      Set objFSO = CreateObject("Scripting.FileSystemObject")

      If objFSO.FileExists(file) Then
    Exit Sub
      Else      '' Create File if DOESN''t Exist
    Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFile = objFSO.CreateTextFile(file)
      End If
End Sub
''================================

''===============================
Private Function pwdExpire(user)
      Const SEC_IN_DAY = 86400
      Const ADS_UF_DONT_EXPIRE_PASSWD = &h10000
      Dim retVal
 
      Set objUserLDAP = GetObject("LDAP://" & user)
      intCurrentValue = objUserLDAP.Get("userAccountControl")
 
      If intCurrentValue and ADS_UF_DONT_EXPIRE_PASSWD Then
    retVal = vbTab & "Password does NOT expire."
      Else
    dtmValue = objUserLDAP.PasswordLastChanged
    retVal = vbTab & "The password was last changed on " & _
        DateValue(dtmValue) & " at " & TimeValue(dtmValue) & VbCrLf & _
            vbTab & "The difference between when the password was last set" &  _
                "and today is " & int(now - dtmValue) & " days"
    intTimeInterval = int(now - dtmValue)
 
    Set objDomainNT = GetObject("WinNT://its")
    intMaxPwdAge = objDomainNT.Get("MaxPasswordAge")
    If intMaxPwdAge < 0 Then
        retVal = retVal & vbcrlf & vbtab & vbtab & "The Maximum Password Age is set to 0 in the " & _
            "domain. Therefore, the password does not expire."
    Else
        intMaxPwdAge = (intMaxPwdAge/SEC_IN_DAY)
        retVal = retVal & vbcrlf & vbtab & vbtab & "The maximum password age is " & intMaxPwdAge & " days"
        If intTimeInterval >= intMaxPwdAge Then
          retVal = retVal & vbcrlf & vbtab & vbtab & "The password has expired."
        Else
          retVal = retVal & vbcrlf & vbtab & vbtab & "The password will expire on " & _
              DateValue(dtmValue + intMaxPwdAge) & " (" & _
                  int((dtmValue + intMaxPwdAge) - now) & " days from today" & _
                      ")."
        End If
    End If
      End If
      pwdExpire = retVal
End Function
''===============================
0
 
LVL 14

Accepted Solution

by:
rejoinder earned 1000 total points
ID: 22880918
Let me know if this is what you are looking for - if it is, it can be expanded to read a file containing computer names.
Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
wscript.echo strComputer
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery ("Select * from Win32_Group  Where LocalAccount = True")
For Each objGroup in colItems
    wscript.echo vbTab & objGroup.Name
    Set objGroup = GetObject("WinNT://" & strComputer & "/" & objGroup.Name)
    For Each objUser in objGroup.Members
        Wscript.Echo vbTab & vbTab & objUser.Name
    Next
Next

Open in new window

0
 
LVL 7

Expert Comment

by:firemanf29
ID: 22882294
Create a share on a server that everyone has write access to.
Create a bat/cmd file as attached.  Modify \\server\share to be the path to the share you created above.
Add this bat file to the domain login script and it will be updated every time a user logs in.


@echo off
REM Delete Old group members ships files
if exist \\server\share\%computername%-administrators.txt del \\server\share\%computername%-administrators.txt 
if exist \\server\share\%computername%-powerusers.txt del \\server\share\%computername%-powerusers.txt 
if exist \\server\share\%computername%-rdpusers.txt del \\server\share\%computername%-dpusers.txt 
REM Create new membership files.
dsquery group -name "Administrators"|dsget group -members >>\\server\share\%computername%-administrators.txt
dsquery group -name "Power Users"|dsget group -members >>\\server\share\%computername%-powerusers.txt
dsquery group -name "Remote Desktop Users"|dsget group -members >>\\server\share\%computername%-rdpusers.txt

Open in new window

0
 
LVL 7

Assisted Solution

by:firemanf29
firemanf29 earned 1000 total points
ID: 22882299
Ooops had a typo:

@echo off
REM Delete Old group members ships files
if exist \\server\share\%computername%-administrators.txt del \\server\share\%computername%-administrators.txt 
if exist \\server\share\%computername%-powerusers.txt del \\server\share\%computername%-powerusers.txt 
if exist \\server\share\%computername%-rdpusers.txt del \\server\share\%computername%-rdpusers.txt 
REM Create new membership files.
dsquery group -name "Administrators"|dsget group -members >>\\server\share\%computername%-administrators.txt
dsquery group -name "Power Users"|dsget group -members >>\\server\share\%computername%-powerusers.txt
dsquery group -name "Remote Desktop Users"|dsget group -members >>\\server\share\%computername%-rdpusers.txt 

Open in new window

0
 
LVL 1

Expert Comment

by:Steynsk
ID: 22915643
Maybe this is the thing you look for:


'\\\\\\\\\\\\\\\\\\\\\\\\\\
'\\
'\\    Filter AD groups, select a AD group and make a list of its users
'\\    Frans Erich  16-02-06
'\\
'\\		 Sub :  CheckForUser and GetUserAccount taken from "ADuser" script from Ralph E Montgomery 
'\\		 Function :  SelectBox taken from script from T. Lavedas
'\\    
'\\    Script only works in a domain environment
'\\
'\\\\\\\\\\\\\\\\\\\\\\\
'On Error Resume Next
Dim objGroup, objUser, WshShell, strMessage, strDomain, strUserMail, strRootDSE, strGetUserName, Ouser, fso
Dim objNet, major, minor, ver, strMail, strLogonName, strValue, strDisplayDescription, strDisplayDepartment, strDN
Dim strSearch, strMostRecentIP, aOpt(), intOpt, oGroup, sGroup, txtFile, objComputer
Dim objRootDSE, strTemp, strADsConfPath, strFormat, strFile, i, objConnection, objCommand, objRecordSet, objectRecordSet
Dim strKey, strKeyValue, rval, strBCC, oMailApp, olMailItm, olMailItem, intSize, strDelegateCount
 
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objNet = CreateObject("WScript.Network")
Set objRootDSE = GetObject("LDAP://rootDSE")
strADsConfPath = "LDAP://" & objRootDSE.Get("configurationNamingContext")
strRootDSE = objRootDSE.Get("defaultNamingContext")
strDomain = UCase(objNet.UserDomain)
strSearch = LCase(InputBox("Provide a optional filter value."))
ListGroups( strDomain )
intOpt = 1
'input validation
sGroup = SelectBox("Select a group", aOpt)
If sGroup = "Selecteer een groep" Then
	strMessage ="You did not make selection!."
	Cancelled()
End If
	
' Change the value of variable "strFormat"  beneath to "Outlook" to generate a new mail containing all email addresses of the mebers in the BCC box.
strFormat = "Excel"
 
Set oGroup = GetObject("WinNT://" & strDomain & "/" & sGroup & ",group")
if sgroup <> "Aborted" then
     if sgroup <> "Selecteer een groep" then
            if strFormat = "Excel" then
                 strTemp = WshShell.ExpandEnvironmentStrings("%temp%")
                 strFile = strTemp & "\Ledenlijst " & sgroup & ".csv"
                Set fso = CreateObject("Scripting.FileSystemObject")
              If fso.FileExists(strFile) Then
               fso.DeleteFile(strFile)
              End If 
               Set txtFile = fso.CreateTextFile(strFile)
               i = 0
               For Each oUser In oGroup.Members
               i = i + 1
               strGetUserName=""
               strDN=""
               strMail=""
               strGetUserName= UCase(oUser.Name)
               if mid(strGetUserName,3,1)<>"-" then
        	   CheckForUser()
               	   GetUserAccount(strDN)
               else
               	   strMail = "computer account"
               	   strDisplayDepartment = "computer account"
        	   end if
               txtFile.write (oUser.Name & " ; " & strDisplayDepartment & " ; " & strMail & vbCrLf)
               Next
               txtfile.close
               Set txtfile = nothing
               Set fso = nothing
               strKey = "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\Excel.exe\path"
               If KeyExists(strKey) = True Then
                    strKeyValue = WshShell.RegRead(strKey)
                    rval = WshShell.Run(chr(34) & strKeyValue & "excel.exe" & chr(34) & " " & chr(34) & strFile & chr(34) ,1,TRUE) 
               else
                    rval = WshShell.Run("notepad.exe" & " " & strFile,1,TRUE)               
               end if
          else
               For Each oUser In oGroup.Members
               i = i + 1
               strGetUserName=""
               strDN=""
               strMail=""
               strGetUserName= UCase(oUser.Name)
               if mid(strGetUserName,3,1)<>"-" then
        	   CheckForUser()        	   
               	   GetUserAccount(strDN)
               end if
               strBCC = strBCC & strMail &"; " 
               Next
               Set oMailApp = CreateObject("Outlook.Application")
               Set olMailItm = oMailApp.CreateItem(olMailItem)
               olMailItm.BCC = strBCC
               olMailItm.Display
          end if
     end if 
end if
 
Sub CheckForUser()
     Set objConnection = CreateObject("ADODB.Connection")
     objConnection.Provider = ("ADsDSOObject")
     objConnection.Open
     Set objCommand = CreateObject("ADODB.Command")
     objCommand.ActiveConnection = objConnection
     objCommand.CommandText = _
     "<LDAP://" & strRootDSE & ">;(&(objectCategory=user)" & _
     "(samAccountName=" & strGetUserName & "));distinguishedName,sAMAccountName,name;subtree"
     Set objRecordSet = objCommand.Execute
     strDN = objRecordset.Fields("distinguishedName") 
     Set objectRecordSet = Nothing
     objConnection.close
     Set objConnection = Nothing
End Sub
 
Sub GetUserAccount(strDN)
    On Error Resume Next
    If InStr(1,strDN,"/") Then strDN=Replace(strDN,"/","\/")
    Set objUser = GetObject("LDAP://" & strDN & "")
    Set objAdS = GetObject("LDAP://" & strRootDSE & "")
 
    With objUser
        '.GetInfo
        strMail =        .Get("mail")
        strLogonName =   .Get("sAMAccountName")
        strUserMail =    .Get("mail")
        strDescription = .GetEx("description")
        strDepartment =  .GetEx("department")
 
        strDisplayDepartment=""
        For Each strValue in strDepartment
         strDisplayDepartment = strDisplayDepartment & strValue
        Next
    
        For Each strValue in strDescription
         strDisplayDescription = strDisplayDescription & strValue
        Next
  
    End With
    
End Sub
 
Sub ListGroups( strDomain )
    Set objComputer = GetObject("WinNT://" & strDomain )
    objComputer.Filter = Array( "Group" )
    For Each objGroup In objComputer
    gt = objGroup.groupType
    if (InStr(LCase(objGroup.Name),strSearch) and (gt = &h02)) or (InStr(LCase(objGroup.Name),strSearch) and (gt = &h01)) or (InStr(LCase(objGroup.Name),strSearch) and (gt = &h08))  then
         ReDim Preserve aOpt(intOpt+ 1)
          aOpt(intOpt) = objGroup.Name
          intOpt = intOpt + 1
     end if
    Next
    If intOpt = 0 then
    strMessage ="Uw zoekopdracht heeft geen resultaat opgeleverd."
	Cancelled()
	end if
End Sub
 
Function SelectBox(sTitle, aOptions)
  Dim oIE, s, item
  set oIE = CreateObject("InternetExplorer.Application")
  With oIE
    .FullScreen = True
    .ToolBar   = False : .RegisterAsDropTarget = False
    .StatusBar = False : .Navigate("about:blank")
    Do Until .ReadyState = 4 : WScript.Sleep 100 : Loop
    .width= 400 : .height=200
    With .document
      with .parentWindow.screen
        oIE.left = (.availWidth  - oIE.width ) \ 2
        oIE.top  = (.availheight - oIE.height) \ 2
      End With
      s = "<html><head><title>" & sTitle _
        & "</title></head><script language=vbs>bWait=true<" & "/script>" _
        & "<body bgColor=Silver><center>" _
	& "<b>" & sTitle & "<b><p>" _
        & "<select id=entries size=1 style='width:325px'>" _
        & "  <option selected>" & sTitle & "</option>"
      For each item in aOptions
        s = s & "  <option>" & item & "</option>"
      Next
      s = s & "  </select><p>" _
        & "<button id=but0 onclick='bWait=false'>OK</button>" _
        & "<br><br><span style=" & chr(34)& "font-size: 8pt" & chr(34)& "><A HREF=" & chr(34)& "mailto:scripting@erich.nu" & chr(34)& ">build by Frans Erich</A></span>" _
        & "</center></body></html>"
      .open
      .Write(s)
      .close
      Do until .ReadyState ="complete" : Wscript.Sleep 50 : Loop
      With .body
        .scroll="no"
        .style.borderStyle = "outset"
        .style.borderWidth = "3px"
      End With
      .all.entries.focus
      oIE.Visible = True
      CreateObject("Wscript.Shell").AppActivate sTitle
      On Error Resume Next
      Do While .ParentWindow.bWait
        WScript.Sleep 100
        if oIE.Visible Then SelectBox = "Aborted"
        if Err.Number <> 0 Then Exit Function
      Loop
      On Error Goto 0
      With .ParentWindow.entries
        SelectBox = .options(.selectedIndex).text
      End With
    End With
    .Visible = False
  End With
End Function
 
 
Function KeyExists(sKeyPath)
     keyExists= false: if (sKeyPath="") then exit function
     on error resume next
     createobject("wscript.shell").regRead sKeyPath
     select case err
     case 0: keyExists= true
     case &h80070002: dim sErrMsg
     sErrMsg= replace(err.description, sKeyPath, "")
     err.clear
     createobject("wscript.shell").regRead "HKEY_ERROR\"
     keyExists= not (sErrMsg=replace(err.description, "HKEY_ERROR\", ""))
     case else: keyExists= false
     end select
     on error goto 0
End function
Sub Cancelled()
    strTitle = "Einde script"
    MsgBox strMessage,vbOkOnly,strTitle
    WScript.quit
End Sub 'Cancelled

Open in new window

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Learn about cloud computing and its benefits for small business owners.
ADCs have gained traction within the last decade, largely due to increased demand for legacy load balancing appliances to handle more advanced application delivery requirements and improve application performance.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question