Solved

Batch script that checks all machines for shares. Need an addition.

Posted on 2010-08-25
22
483 Views
Last Modified: 2012-05-10
Hi,

Batch script that checks all machines for shares.
I need help to get the share and security permission details to the same html next to the path.

regards
Sharath
@Echo Off

SETLOCAL EnableDelayedExpansion



IF NOT EXIST C:\Computers.txt Goto ShowErr

FOR %%R IN (C:\Computers.txt) Do IF %%~zR EQU 0 Goto ShowErr

IF EXIST C:\SHAREinfo.csv DEL /F /Q C:\SHAREinfo.htm



FOR /F %%c IN ('Type Computers.txt') Do (

    Echo Processing: %%c

      PING -n 1 -w 1000 %%c|Find /I "TTL" >NUL

      IF NOT ErrorLevel 1 (

            SET Qry=wmic  /NODE:"%%c" share where type=0 get description,name,path  /format:HTABLE

            !Qry!  >>C:\SHAREinfo.htm

      )ELSE (Echo %%c: Not able to connect )

)      



Goto EndScript

:ShowErr

Echo "C:\Computers.txt" file does not exist or file is empty!

:EndScript

ENDLOCAL

:: Batch Script End

Open in new window

0
Comment
Question by:bsharath
  • 12
  • 7
  • 2
  • +1
22 Comments
 
LVL 26

Expert Comment

by:pony10us
ID: 33524086
Do you have the subinacl.exe from the resource kit?

http://ss64.com/nt/subinacl.html
0
 
LVL 11

Author Comment

by:bsharath
ID: 33524223
Yes i do have it....
0
 
LVL 26

Expert Comment

by:pony10us
ID: 33526008
I have been trying to get your code to work before I add the other portion and am not able to.

Line 12 confuses me. If I attempt to run just that command from the command line and then look at my environment variables I see a variable called Qry but the value is the entire rest of line 12.  

0
 
LVL 65

Expert Comment

by:RobSampson
ID: 33538939
0
 
LVL 11

Author Comment

by:bsharath
ID: 33538981
Thanks Rob exactly what i wanted but what are these 3
TRUSTEE      ACCESS TYPE      ACCESS MASK

I want the Security details and share details
For each machine can we have a blank line in the middle
0
 
LVL 11

Author Comment

by:bsharath
ID: 33538983
I get a few
WMI ERROR's also
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 33539308
TRUSTEE is the name of the account that has each level of access, as shown in the "Share Permissions" of the Share.
ACCESS TYPE is Allow or Deny, depending on which is checked
ACCESS MASK is the actualy access rights they have been allowed or disallowed

Rob.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33539312
Ok can we get the security details also.?
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 33539328
Do you mean NTFS permissions for that folder?
0
 
LVL 11

Author Comment

by:bsharath
ID: 33539387
Yes
0
 
LVL 11

Author Comment

by:bsharath
ID: 33556009
Hi Rob any views...
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 65

Expert Comment

by:RobSampson
ID: 33564668
Hi, maybe something like this is more like what you need.  It will output the share and ntfs permissions on the local computer only (easy to change though).  The output is also very messy, but I can change that....

Regards,

Rob.
Dim objAccessRights : Set objAccessRights = CreateObject("Scripting.Dictionary")

objAccessRights.Add 2032127, "FullControl"

objAccessRights.Add 1048576, "Synchronize"

objAccessRights.Add 524288, "TakeOwnership"

objAccessRights.Add 262144, "ChangePermissions"

objAccessRights.Add 197055, "Modify"

objAccessRights.Add 131241, "ReadAndExecute"

objAccessRights.Add 131209, "Read"

objAccessRights.Add 131072, "ReadPermissions"

objAccessRights.Add 65536, "Delete"

objAccessRights.Add 278, "Write"

objAccessRights.Add 256, "WriteAttributes"

objAccessRights.Add 128, "ReadAttributes"

objAccessRights.Add 64, "DeleteSubdirectoriesAndFiles"

objAccessRights.Add 32, "ExecuteFile"

objAccessRights.Add 16, "WriteExtendedAttributes"

objAccessRights.Add 8, "ReadExtendedAttributes"

objAccessRights.Add 4, "AppendData"

objAccessRights.Add 2, "CreateFiles"

objAccessRights.Add 1, "ReadData"



Const FullAccessMask  = 2032127

Const ModifyAccessMask  = 1245631

Const WriteAccessMask   = 118009

Const ROAccessMask  = 1179817



Dim objFSO, strOutputFile, objOutputFile, objWMIService

Set objFSO = CreateObject("Scripting.FileSystemObject")



strOutputFile = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "SharesAndNTFSPerms.txt"



Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)



strComputer = "."



EnumShares strComputer



objOutputFile.Close

Set objShell = CreateObject("WScript.Shell")

objShell.Run "notepad """ & strOutputFile & """", 1, False



Sub EnumShares(strComputer)



	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

	Dim colItems: Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalShareSecuritySetting")

	Dim objItem, bUnsecuredShare, bUnsecuredNTFS



	For Each objItem In colItems

		'WScript.Echo ""

		Dim colShareItems: Set colShareItems = objWMIService.ExecQuery("SELECT Path FROM Win32_Share WHERE Name='" & objItem.Name & "'")

		Dim objShare, strSharePath

		For Each objShare In colShareItems

			strSharePath = objShare.Path

		Next

		'WScript.Echo "OUTPUTTING ALL PERMISSIONS FOR SHARE: " & objItem.Name

		GetSharePermissions objItem, strSharePath, True

		GetFilePermissions strSharePath, objItem.Name, True

	Next

	

End Sub



' ********************Function GET FILE Permissions *************************************' 



Sub GetSharePermissions(objItem, strSharePath, bOutput)

	If bOutput = True Then objOutputFile.WriteLine VbCrLf & "Share Name:  " & objItem.Name

	intRtn = objItem.GetSecurityDescriptor(wmiSecurityDescriptor)

	colDACLs = wmiSecurityDescriptor.DACL



	For Each objACE In colDACLs

		Set objUserGroup = objACE.Trustee

		'WScript.Echo vbTab & "User/Group that has access:  " & UCase(objUserGroup.Name)

		username = UCase(objUserGroup.Name)

		Select Case objACE.AccessMask

			Case 1179817

				strPermission = "READ"

			Case 1245631

				strPermission = "CHANGE"

			Case 2032127

				strPermission = "FULL CONTROL"

		End Select

		If bOutput = True Then

			objOutputFile.WriteLine objItem.Name & " - SHARE: " & Left("Username: " & username & String(30, " "), 30) & "Permission:  " & strPermission

		Else

			WScript.Echo objItem.Name & " - SHARE: " & Left("Username: " & username & String(30, " "), 30) & "Permission:  " & strPermission

		End If

	Next

End Sub



Sub GetFilePermissions(Share_Path, Share_Name, bOutput)

	Set objNetwork = CreateObject("WScript.Network")

	REP_Share_Path = Replace(Share_Path, "\", "\\") 

	Set objFolderSecuritySettings = objWMIService.Get("Win32_LogicalFileSecuritySetting='" & REP_Share_Path & "'") 

	If Err.Number <> 0 Then

		'wscript.echo strComputer & "," & Share_Name & ",,,,--Cannot gather NTFS perms--"

		objOutputFile.WriteLine strComputer & "," & Share_Name & ",,,,--Cannot gather NTFS perms--"

		Err.clear

	Else

		'wscript.echo NOW & vbtab & "Connected to WMI Provider - Win32_LogicalFileSecuritySetting..."	

		intRetVal1 = objFolderSecuritySettings.GetSecurityDescriptor(wmiSecurityDescriptor)

		If Err <> 0 Then

			'wscript.echo "292" & strComputer & "," & Share_Name & ",,,,--Cannot gather NTFS perms--"

			objOutputFile.WriteLine "292" & strComputer & "," & Share_Name & ",,,,--Cannot gather NTFS perms--"

			Err.clear

		Else

			'wscript.echo NOW & vbtab & "GetSecurityDescriptor succeeded"

			DACL = wmiSecurityDescriptor.DACL

			For Each wmiAce In DACL

				Set Trustee = wmiAce.Trustee

				If Trustee.Name <> "" Then

					'

					FoundAccessMask = False

					CustomAccessMask = False

					While Not FoundAccessMask And Not CustomAccessMask

						If wmiAce.AccessMask = FullAccessMask Then

							AccessType = "Full Control"

							FoundAccessMask = True

						End If

						If wmiAce.AccessMask = ModifyAccessMask Then

							AccessType = "Modify"

							FoundAccessMask = True

						End If

						If wmiAce.AccessMask = WriteAccessMask Then

							AccessType = "Read/Write Control"

							FoundAccessMask = True

						End If

						If wmiAce.AccessMask = ROAccessMask Then

							AccessType = "Read Only"

							FoundAccessMask = True

						Else

							CustomAccessMask = True

						End If

					Wend

	

					If IsNull(Trustee.Domain) Then

						strDomain = objNetwork.ComputerName

					Else

						strDomain = Trustee.Domain

					End If

	

					If FoundAccessMask Then

						If bOutput = True Then

							objOutputFile.WriteLine Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & AccessType

						Else

							wscript.echo Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & AccessType						

						End If

					ElseIf CustomAccessMask = True Then

						strCustom = DisplayValues(wmiAce.AccessMask, objAccessRights)

						If strCustom <> "" Then

							If bOutput = True Then

								objOutputFile.WriteLine Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & "Custom: " & Replace(strCustom, VbCrLf, ", ")

							Else

								wscript.echo Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & "Custom: " & Replace(strCustom, VbCrLf, ",")

							End If

						End If

					End If

				End If

			Next

		End If

	End If

End Sub



Function DisplayValues(dblValues, objSecurityEnumeration)

 

  Dim dblValue

  Dim strReturn

  For Each dblValue in objSecurityEnumeration

    If dblValues >= dblValue Then

      If strReturn = "" Then

      	strReturn = objSecurityEnumeration(dblValue)

      Else

      	strReturn = strReturn & VbCrLf & objSecurityEnumeration(dblValue)

      End If

      dblValues = dblValues - dblValue

    End If

  Next

  DisplayValues = strReturn

End Function

Open in new window

0
 
LVL 11

Author Comment

by:bsharath
ID: 33565336
ya Rob something like this would be useful
But will need the report in one line for each machine and the script to query all machines in a txt file
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 33565486
One line for each machine?  I'm not sure how I could lay that out....each machine has multiple shares, and there could be any amount of different users for both share permissions and NTFS permissions of each share....

How would you want that laid out?

Rob.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33565496
Hmm ya you are right
What i meant by one line was Share and security data for each user in the same row.

You are the best just as best as possible.
0
 
LVL 65

Accepted Solution

by:
RobSampson earned 500 total points
ID: 33593569
OK, try this CSV format out.  It will also read from computers.txt now.

Regards,

Rob.
Dim objAccessRights : Set objAccessRights = CreateObject("Scripting.Dictionary")

objAccessRights.Add 2032127, "FullControl"

objAccessRights.Add 1048576, "Synchronize"

objAccessRights.Add 524288, "TakeOwnership"

objAccessRights.Add 262144, "ChangePermissions"

objAccessRights.Add 197055, "Modify"

objAccessRights.Add 131241, "ReadAndExecute"

objAccessRights.Add 131209, "Read"

objAccessRights.Add 131072, "ReadPermissions"

objAccessRights.Add 65536, "Delete"

objAccessRights.Add 278, "Write"

objAccessRights.Add 256, "WriteAttributes"

objAccessRights.Add 128, "ReadAttributes"

objAccessRights.Add 64, "DeleteSubdirectoriesAndFiles"

objAccessRights.Add 32, "ExecuteFile"

objAccessRights.Add 16, "WriteExtendedAttributes"

objAccessRights.Add 8, "ReadExtendedAttributes"

objAccessRights.Add 4, "AppendData"

objAccessRights.Add 2, "CreateFiles"

objAccessRights.Add 1, "ReadData"



Const FullAccessMask  = 2032127

Const ModifyAccessMask  = 1245631

Const WriteAccessMask   = 118009

Const ROAccessMask  = 1179817



Dim objFSO, strOutputFile, objOutputFile, objWMIService

Set objFSO = CreateObject("Scripting.FileSystemObject")

Const intForReading = 1



strInputFile = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "computers.txt"

strOutputFile = Replace(WScript.ScriptFullName, WScript.ScriptName, "") & "SharesAndNTFSPerms.csv"



Set objInputFile = objFSO.OpenTextFile(strInputFile, intForReading, False)

Set objOutputFile = objFSO.CreateTextFile(strOutputFile, True)

objOutputFile.WriteLine """SERVER"",""PERMISSION TYPE"",""SHARE NAME"",""SHARE PATH"",""TRUSTEE"",""PERMISSION"""



While Not objInputFile.AtEndOfStream

	strComputer = objInputFile.ReadLine

	If Ping(strComputer) = True Then

		EnumShares strComputer

	Else

		objOutputFile.WriteLine """" & strComputer & """,""OFFLINE"""

	End If

Wend



objInputFile.Close

objOutputFile.Close

Set objShell = CreateObject("WScript.Shell")

objShell.Run "excel """ & strOutputFile & """", 1, False



Sub EnumShares(strComputer)



	On Error Resume Next

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

	If Err.Number = 0 Then

		Dim colItems: Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalShareSecuritySetting")

		Dim objItem, bUnsecuredShare, bUnsecuredNTFS

	

		For Each objItem In colItems

			'WScript.Echo ""

			Dim colShareItems: Set colShareItems = objWMIService.ExecQuery("SELECT Path FROM Win32_Share WHERE Name='" & objItem.Name & "'")

			Dim objShare, strSharePath

			For Each objShare In colShareItems

				strSharePath = objShare.Path

			Next

			'WScript.Echo "OUTPUTTING ALL PERMISSIONS FOR SHARE: " & objItem.Name

			GetSharePermissions objItem, strSharePath, True

			GetFilePermissions strSharePath, objItem.Name, True

		Next

	Else

		objOutputFile.WriteLine """" & strComputer & """,""WMI ERROR"""

	End If

	

End Sub



' ********************Function GET FILE Permissions *************************************' 



Sub GetSharePermissions(objItem, strSharePath, bOutput)

	'If bOutput = True Then objOutputFile.WriteLine VbCrLf & "Share Name:  " & objItem.Name

	intRtn = objItem.GetSecurityDescriptor(wmiSecurityDescriptor)

	colDACLs = wmiSecurityDescriptor.DACL



	For Each objACE In colDACLs

		Set objUserGroup = objACE.Trustee

		'WScript.Echo vbTab & "User/Group that has access:  " & UCase(objUserGroup.Name)

		username = UCase(objUserGroup.Name)

		Select Case objACE.AccessMask

			Case 1179817

				strPermission = "READ"

			Case 1245631

				strPermission = "CHANGE"

			Case 2032127

				strPermission = "FULL CONTROL"

		End Select

		If bOutput = True Then

			objOutputFile.WriteLine """" & strComputer & """,""SHARE"",""" & objItem.Name & """,""" & strSharePath & """,""" & username & """,""" & strPermission & """"

		Else

			WScript.Echo objItem.Name & " - SHARE: " & Left("Username: " & username & String(30, " "), 30) & "Permission:  " & strPermission

		End If

	Next

End Sub



Sub GetFilePermissions(Share_Path, Share_Name, bOutput)

	Set objNetwork = CreateObject("WScript.Network")

	REP_Share_Path = Replace(Share_Path, "\", "\\") 

	Set objFolderSecuritySettings = objWMIService.Get("Win32_LogicalFileSecuritySetting='" & REP_Share_Path & "'") 

	If Err.Number <> 0 Then

		'wscript.echo strComputer & "," & Share_Name & ",,,,--Cannot gather NTFS perms--"

		objOutputFile.WriteLine """" & strComputer & """,""NTFS"",""" & Share_Name & """,""" & Share_Path & """,""ERROR"",""ERROR"""

		Err.clear

	Else

		'wscript.echo NOW & vbtab & "Connected to WMI Provider - Win32_LogicalFileSecuritySetting..."	

		intRetVal1 = objFolderSecuritySettings.GetSecurityDescriptor(wmiSecurityDescriptor)

		If Err <> 0 Then

			'wscript.echo "292" & strComputer & "," & Share_Name & ",,,,--Cannot gather NTFS perms--"

			objOutputFile.WriteLine """" & strComputer & """,""NTFS"",""" & Share_Name & """,""" & Share_Path & """,""ERROR"",""ERROR"""

			Err.clear

		Else

			'wscript.echo NOW & vbtab & "GetSecurityDescriptor succeeded"

			DACL = wmiSecurityDescriptor.DACL

			For Each wmiAce In DACL

				Set Trustee = wmiAce.Trustee

				If Trustee.Name <> "" Then

					'

					FoundAccessMask = False

					CustomAccessMask = False

					While Not FoundAccessMask And Not CustomAccessMask

						If wmiAce.AccessMask = FullAccessMask Then

							AccessType = "Full Control"

							FoundAccessMask = True

						End If

						If wmiAce.AccessMask = ModifyAccessMask Then

							AccessType = "Modify"

							FoundAccessMask = True

						End If

						If wmiAce.AccessMask = WriteAccessMask Then

							AccessType = "Read/Write Control"

							FoundAccessMask = True

						End If

						If wmiAce.AccessMask = ROAccessMask Then

							AccessType = "Read Only"

							FoundAccessMask = True

						Else

							CustomAccessMask = True

						End If

					Wend

	

					If IsNull(Trustee.Domain) Then

						strDomain = objNetwork.ComputerName

					Else

						strDomain = Trustee.Domain

					End If

	

					If FoundAccessMask Then

						If bOutput = True Then

							'objOutputFile.WriteLine Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & AccessType

							objOutputFile.WriteLine """" & strComputer & """,""NTFS"",""" & Share_Name & """,""" & Share_Path & """,""" & strDomain & "\" & Trustee.Name & ""","""  & AccessType & """"

						Else

							wscript.echo Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & AccessType						

						End If

					ElseIf CustomAccessMask = True Then

						strCustom = DisplayValues(wmiAce.AccessMask, objAccessRights)

						If strCustom <> "" Then

							If bOutput = True Then

								objOutputFile.WriteLine """" & strComputer & """,""NTFS"",""" & Share_Name & """,""" & Share_Path & """,""" & strDomain & "\" & Trustee.Name & ""","""  & Replace(strCustom, VbCrLf, ", ") & """"

							Else

								wscript.echo Share_Name & " - NTFS:  " & strDomain & "\" & Trustee.Name & ": "  & "Custom: " & Replace(strCustom, VbCrLf, ",")

							End If

						End If

					End If

				End If

			Next

		End If

	End If

End Sub



Function DisplayValues(dblValues, objSecurityEnumeration)

 

  Dim dblValue

  Dim strReturn

  For Each dblValue in objSecurityEnumeration

    If dblValues >= dblValue Then

      If strReturn = "" Then

      	strReturn = objSecurityEnumeration(dblValue)

      Else

      	strReturn = strReturn & VbCrLf & objSecurityEnumeration(dblValue)

      End If

      dblValues = dblValues - dblValue

    End If

  Next

  DisplayValues = strReturn

End Function



Function Ping(strComputer)

	Dim objShell, boolCode

	Set objShell = CreateObject("WScript.Shell")

	boolCode = objShell.Run("Ping -n 1 -w 300 " & strComputer, 0, True)

	If boolCode = 0 Then

		Ping = True

	Else

		Ping = False

	End If

End Function

Open in new window

0
 
LVL 11

Author Comment

by:bsharath
ID: 33603545
Thanks Rob
If the share and security have full control can we get a color to the row. So i can filter them to find them.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33605975
Rob there are times when 1 share has many users\groups added in share and security. Can i have then in one cell of each like
Share                              Security
Name;name,name           name,name,group

So i can minimize the rows it takes


0
 
LVL 11

Author Comment

by:bsharath
ID: 33609038
Hi Rob any luck on this today
0
 
LVL 65

Expert Comment

by:RobSampson
ID: 33609196
To find all the ones with Full Control, you can apply a sort to sort by column F.  The output is currently CSV, so coloring is not supported.
To be able to combine the users to one cell, we would have to merge each of the users and / or groups that have the same security, and put them together.  That would be a bit more difficult.....and it wouldn't be as easy to look for a specific user.  If you really want me to do that, I can try.

Rob.
0
 
LVL 9

Expert Comment

by:samiam41
ID: 33612610
If the great minds have a chance and are ready for a challenge, I appreciate your time on this:

http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_26454480.html
0
 
LVL 11

Author Comment

by:bsharath
ID: 33612621
Thanks a lot Rob for the help
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
This article will show, step by step, how to integrate R code into a R Sweave document
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

747 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now