?
Solved

Script to monitor ACL/permission changes/modification on files/folders on server

Posted on 2010-03-26
32
Medium Priority
?
927 Views
Last Modified: 2013-03-06
I need to monitor some imp files & Dir , so that I can get alert- if any permission is modified for any files /dir on my server, is there any script which can continuously check for the ACL modification on server..?

Also confirm if it is possible through any monitoring tool(freeware ) like nimbus/nimsoft etc
0
Comment
Question by:Brijeshk9
  • 15
  • 13
  • 3
  • +1
32 Comments
 
LVL 74

Expert Comment

by:Glen Knight
ID: 28708078
I think that would put quite an overhead in the system?

You could enable file and folder auditing as per: http://technet.microsoft.com/en-us/library/cc784387(WS.10).aspx this would raise an event in the security log if the settings were changed.
0
 
LVL 25

Expert Comment

by:DBAduck - Ben Miller
ID: 28708910
You may also use WMI to monitor the folder and just wait for the event in WMI.
0
 

Author Comment

by:Brijeshk9
ID: 28742211
Thanks, that I have already tried but it is not generating the detail like what permission was changed by which user..?
Is it possible in Microsoft windows or by using any wmi..?
0
Take Control of Web Hosting For Your Clients

As a web developer or IT admin, successfully managing multiple client accounts can be challenging. In this webinar we will look at the tools provided by Media Temple and Plesk to make managing your clients’ hosting easier.

 
LVL 25

Expert Comment

by:DBAduck - Ben Miller
ID: 28744932
Here is a good place for you to start.

http://msdn.microsoft.com/en-us/library/ms141130.aspx
0
 
LVL 25

Expert Comment

by:DBAduck - Ben Miller
ID: 28745006
0
 

Author Comment

by:Brijeshk9
ID: 30494515
As of now I didn’t get any satisfactory answer of my questions..?
0
 
LVL 12

Expert Comment

by:jostrander
ID: 30554836
Is it a large number of files?  

Do they all require a specific ACL, like only allow Domain Admins, GroupABC, etc?
0
 

Author Comment

by:Brijeshk9
ID: 30600258
I want to  monitor particular files/folders on my server, if it is for single file/folder-that will also work for me.
and alert should be like which permission has been added/changed by which user.
0
 
LVL 12

Expert Comment

by:jostrander
ID: 30657961
I may have gone overboard this time...but it's fun!  There were some parts I probably could have done easier, but I wanted this to work on multiple platforms.  

Prerequisites:
1) Audit Object Access (Success) must be enabled in the Local Security policy of the server
2) Auditing must be enabled in the Advanced Security settings for the Folder/File to be monitored
3) SMTP server must be enabled (if you want emails)
4)...can't think now

It's working well for me on several hosts (remote too).  Please try it out and let me know how it works for you.  I'm sure I've missed something, but my brain is a bit fried at the moment.

Thanks,
Joe
'Joe Ostrander
'Monitor folder/file permissions
'04.13.2010


'Force CSCRIPT
Set WshShell=CreateObject("Wscript.Shell")
If instr(lcase(wscript.fullname),"wscript") then
	wshshell.run "cmd /k cscript //nologo " & chr(34) & wscript.scriptfullname & Chr(34),1,false
	wscript.quit
End If


Dim strObject

intPollSeconds=10
strTargetInstanceType="Audit Success"	
strLogFile="SECURITY"

'--------------------------------------------------------------------
'	User Variables
'--------------------------------------------------------------------
'Server to monitor, use "." for local
strServer = "myserver1" 

'Event code to monitor... Win7 use 4670, XP/2003 use 560
strEventCode="560"


strEmailSMTPserver="yoursmtpserver"
strEmailTo="you@there.com" 
strEmailFrom="""Folder Monitor"" <someone@somewhere.com>"
strEmailSubject="Security: Permissions changed" 

'Minimum time to wait before sending email (in seconds)
'When the time since last email has reached this AND
'a NEW event is triggered, an email will be sent with
'recent changes.  This is to prevent flooding your inbox
'when multiple events happen in succession (like a recursive setting)
intEmailWait=120

'Folder or File to monitor
strObject="c:\temp"


'--------------------------------------------------------------------


if strServer<>"." then strObject="\\" & strServer & "\" & replace(strObject,":","$")

blah="\|/-"


Set fso=CreateObject("Scripting.FileSystemObject")
Set oDict=CreateObject("Scripting.Dictionary")

'Record the ACL of each file/folder to dictionary
RecordACLs "files"
If fso.FolderExists(strObject) then RecordACLs "folders"

wscript.echo vbCr & "                                           " & vbCr & _
	"Monitoring " & strObject & "..."

Set objWMIService = GetObject("winmgmts:" _ 
        & "{impersonationLevel=impersonate,(Security)}!\\" & strServer & "\root\cimv2") 

strQuery="Select * from __InstanceCreationEvent WITHIN " & intPollSeconds &_
	" where TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.Type='" & strTargetInstanceType & "' AND " & _
	"TargetInstance.Logfile='" & strLogFile & "' AND TargetInstance.EventCode='" & strEventCode & "'"

Set colMonitoredEvents = objWMIService.ExecNotificationQuery(strQuery) 



Do 
	txt=""
	
	Set objEvent = colMonitoredEvents.NextEvent()
	Set objTargetInst = objEvent.TargetInstance
	
	strTimeWritten= objTargetInst.Properties_("TimeWritten") & ""
	
	Set objSWbemDateTime = CreateObject("WbemScripting.SWbemDateTime")
	objSWbemDateTime.Value=strTimeWritten
	strDate=objSWbemDateTime.GetVarDate(True)	'True=Use OS Timezone
	
	
	strComputerName = objTargetInst.Properties_("ComputerName") & ""
	strType = objTargetInst.Properties_("Type") & ""
	strEventCode = objTargetInst.Properties_("EventCode") & ""
	strMessage= objTargetInst.Properties_("Message") & ""
	strUser = objTargetInst.Properties_("User") & ""
	If strUser<> "" then strUser="User:  " & strUser

	arrMsg=split(strMessage,vbCrLf)
	For each line in arrMsg
		If Instr(line,"Object Name:") then
			tmp=split(line,"Object Name:")(1)
			myFile=Trim(tmp)
			myFile=lcase(replace(myFile,vbTab,""))
			
			If strServer <> "." then myFile="\\" & strServer & "\" & replace(myFile,":","$")
		End If
	Next
	
	'See if the file is one we're monitoring and ACL changed
	filetest=CheckFile(myFile)
	
	If filetest<>"" then
		txt= "--------------------------------------------------------" & vbCrLf & _
			"Permissions modified by " & strUser & vbCrLf & _
			"Time written:  " & strDate & vbCrLf & _
			"Object:  " & myFile & vbCrLf & _
			"Computer:  " & strComputerName & vbCrLf & _
			"Changes:  " & vbCrLf & filetest & vbCrLf
		wscript.echo txt
		emailText=emailText & txt
		txt=""
	End If
	
	CurrentTime=Timer()
	If CurrentTime-LastEmailTime>intEmailWait then
		If emailText<>"" then
			SendMail emailText
			LastEmailTime=Timer()
			emailText=""
		End If
	End If
	

	Set objEvent = Nothing
	Set objTargetInst = Nothing
	strTimeWritten= ""
	strDate=""
	strComputerName = ""
	strType = ""
	strEventCode = ""
	strMessage=""
	strUser = ""
	
Loop

Function CheckFile(myFile)
	chk=""
	For each key in oDict.Keys
		If lcase(key)=lcase(myFile) then
			'See if ACL changed
			currentACL=GetACL(myFile)
			'wscript.echo "current:    " & currentACL
			'wscript.echo "dictionary: " & oDict(myFile)
			
			If ucase(currentACL)<>ucase(oDict(myFile)) then
				'wscript.echo "yes, changed"
				
				'Find what changed
				chk=CompareACL(currentACL,oDict(myFile))
				
				'update dictionary
				oDict(myFile)=currentACL
			Else
				'wscript.echo "no change"
				chk=""
			End If
		End If
	Next
	CheckFile=chk
End Function

Sub SendMail(txt)
	ON ERROR RESUME NEXT

	if txt <> "" Then

		CONST cdoSendUsingPort = 2 
		CONST cdoAnonymous = 0 
		set msg = CreateObject("CDO.Message") 
		set config = CreateObject("CDO.Configuration") 
		set msg.Configuration = config 

		With msg 
				.to = strEmailTo
				.from = strEmailFrom 
				.subject = strEmailSubject
				.textbody = txt 
		End with 
 
		prefix = "http://schemas.microsoft.com/cdo/configuration/" 
 
		With config.fields 
				.item(prefix & "sendusing") = cdoSendUsingPort 
				.item(prefix & "smtpserver") = strEmailSMTPserver 
				.item(prefix & "smtpauthenticate") = cdoAnonymous 
				.update 
		End With 

		msg.send 

		if err.number <> 0 then
			WshShell.LogEvent 1,"Error Sending Your Message" & vbCrLf & vbCrLf & _
				"Email to:  " & strEmailTo & vbCrLf & _
				"Email From:  " & strEmailFrom & vbCrLf & _
				"Email Subject:  " & strEmailSubject & vbCrLf & _
				"Email SMTP Server:  " & strEmailSMTPserver & vbCrLf & _
				"Email Body:  " & txt 
			
		End If
	End If

End Sub



Sub RecordACLs(mode)
	Select Case mode
		Case "files"
			myCMD="cmd /c dir /s /b " & Chr(34) & strObject & Chr(34)
		Case "folders"
			myCMD="cmd /c dir /ad /s /b " & Chr(34) & strObject & Chr(34)
	End Select
	
	Set oExec=WshShell.Exec(myCMD)
	
	While Not oExec.StdOut.AtEndOfStream
		count=count+1
		if count=5 then count=1
		
		wscript.stdout.write vbCr & "                                           " & vbCr & _
			"Recording ACL Information for " & mode & "..."
		wscript.stdout.write mid(blah,count,1)
		line=oExec.StdOut.ReadLine
		If line <> "" then GetACL line
	Wend

End Sub

Function GetACL(myFile)
	myFile=lcase(myFile)
	
	myLen=len(myFile)
	test=""
	Set oExec_cacls=WshShell.Exec("cacls " & Chr(34) & myFile & Chr(34))
	While Not oExec_cacls.StdOut.AtEndOfStream
		line_acl=oExec_cacls.StdOut.ReadLine
		if len(line_acl)>myLen then
			acl=acl & Trim(mid(line_acl,myLen+2)) & "|"
		end if
	Wend
	If oDict.Exists(myFile) then
		'compare mode...
		'wscript.echo "checking:  " & myFile
		test=acl
	Else
		oDict.Add myFile,acl
	End If
	acl=""
	GetACL=test
End Function


Function CompareACL(newacl,oldacl)
	arrNew=split(newacl,"|")
	arrOld=split(oldacl,"|")
	
	'Compare old to new - find removals
	For each itmOld in arrOld
		IsRemoval=True
		For each itmNew in arrNew
			if itmOld=itmNew then 
				IsRemoval=False
			end if
		Next
		If IsRemoval=True then removals=removals & vbTab & "Removed:  " & itmOld & vbCrLf
	Next
	
	'Compare new to old - find additions
	For each itmNew in arrNew
		IsAddition=True
		For each itmOld in arrOld
			if itmNew=itmOld then 
				IsAddition=False
			end if
		Next
		If IsAddition=True then additions=additions & vbTab & "Added:    " & itmNew & vbCrLf
	Next
	


	CompareACL=removals & additions

End Function

Open in new window

0
 

Author Comment

by:Brijeshk9
ID: 30709423
Thanks a lot, it is really a great script!
I am able to record all required information but facing problem while sending mail.?is it possible to record all the output in a text file and that should be sent in a mail(recorded data should come in mail’s body)

Thanks for all your help on this!
0
 
LVL 12

Expert Comment

by:jostrander
ID: 30723391
Sure, I can add the results as a text file attachment to the email.  Just to make sure I'm not misunderstanding though:

Were there any other problems with the emailing?  Was it just that not all events were emailed?  Not sure if you noticed, but it is currently set to only email on an event and only if the time since last email is more than 120 seconds.  If this is a problem, I can change it to email on all events, but then you may get a flood of emails depending on the number of changes made.  Currently, if the time is > 120 and 10 changes happen, you may get an email with the 1st change.  The other 9 will be emailed on the next change.

Thanks,
Joe

0
 
LVL 12

Expert Comment

by:jostrander
ID: 30727282
I made a separate version that logs to a CSV file but does not email.  I could write a script that monitors the CSV file for changes.  This could be set to run on a schedule.  If the logfile has changed recently, it would send an email.  I could have it either send the whole file, or just part of the file... like changes within the last day or hour or whatever you like.  We could even have separate logfiles for each day.

My only concern so far has been avoiding an email flood if the monitored folder has hundreds of files and a recursive permission change happens.  
I'm not sure how many files are in the folder you monitor, so maybe this isn't even an issue. If there aren't many files in there, I can just make it email on every change.

Hope I'm making sense here, please let me know how you'd like to proceed.

Thanks,
Joe

0
 

Author Comment

by:Brijeshk9
ID: 30737276
Please make it :email on every change..

0
 
LVL 12

Expert Comment

by:jostrander
ID: 30739658
Sure thing, please try this one:
'Joe Ostrander
'Monitor folder/file permissions
'04.13.2010


'Force CSCRIPT
Set WshShell=CreateObject("Wscript.Shell")
If instr(lcase(wscript.fullname),"wscript") then
	wshshell.run "cmd /k cscript //nologo " & chr(34) & wscript.scriptfullname & Chr(34),1,false
	wscript.quit
End If


Dim strObject

intPollSeconds=10
strTargetInstanceType="Audit Success"	
strLogFile="SECURITY"

'--------------------------------------------------------------------
'	User Variables
'--------------------------------------------------------------------
'Server to monitor, use "." for local
strServer = "myserver1" 

'Event code to monitor... Win7 use 4670, XP/2003 use 560
strEventCode="560"


strEmailSMTPserver="yoursmtpserver"
strEmailTo="you@there.com" 
strEmailFrom="""Folder Monitor"" <someone@somewhere.com>"
strEmailSubject="Security: Permissions changed" 

'Folder or File to monitor
strObject="c:\temp"


'--------------------------------------------------------------------


if strServer<>"." then strObject="\\" & strServer & "\" & replace(strObject,":","$")

blah="\|/-"


Set fso=CreateObject("Scripting.FileSystemObject")
Set oDict=CreateObject("Scripting.Dictionary")

'Record the ACL of each file/folder to dictionary
RecordACLs "files"
If fso.FolderExists(strObject) then RecordACLs "folders"

wscript.echo vbCr & "                                           " & vbCr & _
	"Monitoring " & strObject & "..."

Set objWMIService = GetObject("winmgmts:" _ 
        & "{impersonationLevel=impersonate,(Security)}!\\" & strServer & "\root\cimv2") 

strQuery="Select * from __InstanceCreationEvent WITHIN " & intPollSeconds &_
	" where TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.Type='" & strTargetInstanceType & "' AND " & _
	"TargetInstance.Logfile='" & strLogFile & "' AND TargetInstance.EventCode='" & strEventCode & "'"

Set colMonitoredEvents = objWMIService.ExecNotificationQuery(strQuery) 



Do 
	txt=""
	
	Set objEvent = colMonitoredEvents.NextEvent()
	Set objTargetInst = objEvent.TargetInstance
	
	strTimeWritten= objTargetInst.Properties_("TimeWritten") & ""
	
	Set objSWbemDateTime = CreateObject("WbemScripting.SWbemDateTime")
	objSWbemDateTime.Value=strTimeWritten
	strDate=objSWbemDateTime.GetVarDate(True)	'True=Use OS Timezone
	
	
	strComputerName = objTargetInst.Properties_("ComputerName") & ""
	strType = objTargetInst.Properties_("Type") & ""
	strEventCode = objTargetInst.Properties_("EventCode") & ""
	strMessage= objTargetInst.Properties_("Message") & ""
	strUser = objTargetInst.Properties_("User") & ""
	If strUser<> "" then strUser="User:  " & strUser

	arrMsg=split(strMessage,vbCrLf)
	For each line in arrMsg
		If Instr(line,"Object Name:") then
			tmp=split(line,"Object Name:")(1)
			myFile=Trim(tmp)
			myFile=lcase(replace(myFile,vbTab,""))
			
			If strServer <> "." then myFile="\\" & strServer & "\" & replace(myFile,":","$")
		End If
	Next
	
	'See if the file is one we're monitoring and ACL changed
	filetest=CheckFile(myFile)
	
	If filetest<>"" then
		txt= "--------------------------------------------------------" & vbCrLf & _
			"Permissions modified by " & strUser & vbCrLf & _
			"Time written:  " & strDate & vbCrLf & _
			"Object:  " & myFile & vbCrLf & _
			"Computer:  " & strComputerName & vbCrLf & _
			"Changes:  " & vbCrLf & filetest & vbCrLf
		wscript.echo txt
		emailText=emailText & txt
		txt=""
	End If
	

	If emailText<>"" then
		SendMail emailText
		emailText=""
	End If


	Set objEvent = Nothing
	Set objTargetInst = Nothing
	strTimeWritten= ""
	strDate=""
	strComputerName = ""
	strType = ""
	strEventCode = ""
	strMessage=""
	strUser = ""
	
Loop

Function CheckFile(myFile)
	chk=""
	For each key in oDict.Keys
		If lcase(key)=lcase(myFile) then
			'See if ACL changed
			currentACL=GetACL(myFile)
			'wscript.echo "current:    " & currentACL
			'wscript.echo "dictionary: " & oDict(myFile)
			
			If ucase(currentACL)<>ucase(oDict(myFile)) then
				'wscript.echo "yes, changed"
				
				'Find what changed
				chk=CompareACL(currentACL,oDict(myFile))
				
				'update dictionary
				oDict(myFile)=currentACL
			Else
				'wscript.echo "no change"
				chk=""
			End If
		End If
	Next
	CheckFile=chk
End Function

Sub SendMail(txt)
	ON ERROR RESUME NEXT

	if txt <> "" Then

		CONST cdoSendUsingPort = 2 
		CONST cdoAnonymous = 0 
		set msg = CreateObject("CDO.Message") 
		set config = CreateObject("CDO.Configuration") 
		set msg.Configuration = config 

		With msg 
				.to = strEmailTo
				.from = strEmailFrom 
				.subject = strEmailSubject
				.textbody = txt 
		End with 
 
		prefix = "http://schemas.microsoft.com/cdo/configuration/" 
 
		With config.fields 
				.item(prefix & "sendusing") = cdoSendUsingPort 
				.item(prefix & "smtpserver") = strEmailSMTPserver 
				.item(prefix & "smtpauthenticate") = cdoAnonymous 
				.update 
		End With 

		msg.send 

		if err.number <> 0 then
			WshShell.LogEvent 1,"Error Sending Your Message" & vbCrLf & vbCrLf & _
				"Email to:  " & strEmailTo & vbCrLf & _
				"Email From:  " & strEmailFrom & vbCrLf & _
				"Email Subject:  " & strEmailSubject & vbCrLf & _
				"Email SMTP Server:  " & strEmailSMTPserver & vbCrLf & _
				"Email Body:  " & txt 
			
		End If
	End If

End Sub



Sub RecordACLs(mode)
	Select Case mode
		Case "files"
			myCMD="cmd /c dir /s /b " & Chr(34) & strObject & Chr(34)
		Case "folders"
			myCMD="cmd /c dir /ad /s /b " & Chr(34) & strObject & Chr(34)
	End Select
	
	Set oExec=WshShell.Exec(myCMD)
	
	While Not oExec.StdOut.AtEndOfStream
		count=count+1
		if count=5 then count=1
		
		wscript.stdout.write vbCr & "                                           " & vbCr & _
			"Recording ACL Information for " & mode & "..."
		wscript.stdout.write mid(blah,count,1)
		line=oExec.StdOut.ReadLine
		If line <> "" then GetACL line
	Wend

End Sub

Function GetACL(myFile)
	myFile=lcase(myFile)
	
	myLen=len(myFile)
	test=""
	Set oExec_cacls=WshShell.Exec("cacls " & Chr(34) & myFile & Chr(34))
	While Not oExec_cacls.StdOut.AtEndOfStream
		line_acl=oExec_cacls.StdOut.ReadLine
		if len(line_acl)>myLen then
			acl=acl & Trim(mid(line_acl,myLen+2)) & "|"
		end if
	Wend
	If oDict.Exists(myFile) then
		'compare mode...
		'wscript.echo "checking:  " & myFile
		test=acl
	Else
		oDict.Add myFile,acl
	End If
	acl=""
	GetACL=test
End Function


Function CompareACL(newacl,oldacl)
	arrNew=split(newacl,"|")
	arrOld=split(oldacl,"|")
	
	'Compare old to new - find removals
	For each itmOld in arrOld
		IsRemoval=True
		For each itmNew in arrNew
			if itmOld=itmNew then 
				IsRemoval=False
			end if
		Next
		If IsRemoval=True then removals=removals & vbTab & "Removed:  " & itmOld & vbCrLf
	Next
	
	'Compare new to old - find additions
	For each itmNew in arrNew
		IsAddition=True
		For each itmOld in arrOld
			if itmNew=itmOld then 
				IsAddition=False
			end if
		Next
		If IsAddition=True then additions=additions & vbTab & "Added:    " & itmNew & vbCrLf
	Next
	


	CompareACL=removals & additions

End Function

Open in new window

0
 

Author Comment

by:Brijeshk9
ID: 30783810
Getting Error event in Application Log..with Source :WSH & event ID :1

Event Type:      Error
Event Source:      WSH
Event Category:      None
Event ID:      1
Date:            4/15/2010
Time:            9:39:55 AM
User:            N/A
Computer:      HOME
Description:
Error Sending Your Message

Email to:  vicky@gmail.com
Email From:  "Folder Monitor"vicky@gmail.com
Email Subject:  Security: Permissions changed
Email SMTP Server:  smtp.gmail.com
Email Body:  --------------------------------------------------------
Permissions modified by User:  vangtech\vicky.singh
Time written:  4/15/2010 9:39:24 AM
Object:  \\Home\c$\test\new folder
Computer:  Home
Changes:  
      Added:    vangtech\Nicky.Gupta:(OI)(CI)F



For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
0
 

Author Comment

by:Brijeshk9
ID: 30783919
Although I have changed the smtp address, same error I was getting for previous script also..?
0
 
LVL 12

Expert Comment

by:jostrander
ID: 30828900
Oh, that's what I was trying to find out earlier.  I didn't realize you weren't getting any emails.

If you have an internal SMTP server, I'd recommend using that.  Otherwise, if you are going to use an _external_ SMTP server like gmail's, you will need to use authentication as well as make sure you are not behind a firewall that prevents access to smtp.gmail.com port 465.

Here is a sample script that you can use to see if emailing via gmail smtp is possible in your environment:

'send email with GMAIL

Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM

strSmtpPort=465
strSmtpServer="smtp.gmail.com"

strUsername=InputBox("Username:", "Send E-mail","vicky@gmail.com")
If strUsername = "" Then wscript.quit

strPassword=InputBox("Password:", "Send E-mail")
If strPassword = "" Then wscript.quit

strTo = InputBox("To:  ", "Send E-mail", "vicky@gmail.com")
If strTo = "" Then wscript.quit

strFrom = InputBox("From:  ", "Send E-mail", "vicky@gmail.com")
If strFrom = "" Then wscript.quit

strSubject = InputBox("Subject:  ", "Send E-mail")
If strSubject = "" Then wscript.quit

strText = InputBox("Text:  ", "Send E-mail")
If strText = "" Then wscript.quit


Set objEmail = CreateObject("CDO.Message")

With objEmail
	.From = strFrom
	.To = strTo
	.Subject = strSubject
	.Textbody = strText
	.Sender=strFrom
	
	
	With .Configuration.Fields
		.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSmtpServer
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = strSmtpPort
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
		.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = strUserName
		.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = strPassword
		.Update
	End With
	
	.Send
End With

Open in new window

0
 

Author Comment

by:Brijeshk9
ID: 30890716
yes, i have already tried with internal SMTP, but again getting same error in Application event Log with ID: 1 & source :WSH.?
0
 

Author Comment

by:Brijeshk9
ID: 30891516
well it was really a great help from you..if mail is not possible..can we have an event or text file which can have the detail for all these acl changes.. then i wll look for any solution by which i can send that text file or event log in mails (and detail will be in mail's body)...!

Thanks 4 all ur help on this.
0
 
LVL 12

Expert Comment

by:jostrander
ID: 30922134
It's possible that your internal mail server requires authentication.  Here's another test script that should attempt sending using a username/password.  Please see if this works and let me know the results.

While I wait to hear the results, I'll work on some modifications to the script.

Thank you, Joe
0
 
LVL 12

Expert Comment

by:jostrander
ID: 30922173

'send email with authentication

Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM

strSmtpPort=25
strSmtpServer="yourservername"

strUsername=InputBox("Email Username:", "Send E-mail")
If strUsername = "" Then wscript.quit

strPassword=InputBox("Email Password:", "Send E-mail")
If strPassword = "" Then wscript.quit

strTo = InputBox("To:  ", "Send E-mail", "someone@somewhere.com")
If strTo = "" Then wscript.quit

strFrom = InputBox("From:  ", "Send E-mail", "someone@somewhere.com")
If strFrom = "" Then wscript.quit

strSubject = InputBox("Subject:  ", "Send E-mail")
If strSubject = "" Then wscript.quit

strText = InputBox("Text:  ", "Send E-mail")
If strText = "" Then wscript.quit


Set objEmail = CreateObject("CDO.Message")

With objEmail
	.From = strFrom
	.To = strTo
	.Subject = strSubject
	.Textbody = strText
	.Sender=strFrom
	
	
	With .Configuration.Fields
		.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSmtpServer
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = strSmtpPort
		.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
		.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = strUserName
		.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = strPassword
		.Update
	End With
	
	.Send
End With

Open in new window

0
 
LVL 12

Accepted Solution

by:
jostrander earned 2000 total points
ID: 30930245
Here is a version of the monitor vbs that will only output to the cmd window and a logfile ("c:\results.txt").

If the test in my previous post works, we can have a second script monitor the results.txt and send mail (I have a sample I'm working on now).  
If the smtp approach doesn't work, we can explore other methods of emailing it.  For this, I'd need to know what type of mail client you use.
'Joe Ostrander
'Monitor folder/file permissions
'04.13.2010


'Force CSCRIPT
Set WshShell=CreateObject("Wscript.Shell")
If instr(lcase(wscript.fullname),"wscript") then
	wshshell.run "cmd /k cscript //nologo " & chr(34) & wscript.scriptfullname & Chr(34),1,false
	wscript.quit
End If

CONST FOR_APPENDING=8

Dim strObject
Dim strLogFile

intPollSeconds=10
strTargetInstanceType="Audit Success"	
strEventLog="SECURITY"

'--------------------------------------------------------------------
'	User Variables
'--------------------------------------------------------------------
'Server to monitor, use "." for local
strServer = "myserver1" 

'Event code to monitor... Win7 use 4670, XP/2003 use 560
strEventCode="560"

'Folder or File to monitor
strObject="c:\temp"

'File to log results to
strLogFile="c:\results.txt"

'--------------------------------------------------------------------


if strServer<>"." then strObject="\\" & strServer & "\" & replace(strObject,":","$")

blah="\|/-"


Set fso=CreateObject("Scripting.FileSystemObject")
Set oDict=CreateObject("Scripting.Dictionary")

'Record the ACL of each file/folder to dictionary
RecordACLs "files"
If fso.FolderExists(strObject) then RecordACLs "folders"

wscript.echo vbCr & "                                           " & vbCr & _
	"Monitoring " & strObject & "..."

Set objWMIService = GetObject("winmgmts:" _ 
        & "{impersonationLevel=impersonate,(Security)}!\\" & strServer & "\root\cimv2") 

strQuery="Select * from __InstanceCreationEvent WITHIN " & intPollSeconds &_
	" where TargetInstance ISA 'Win32_NTLogEvent' AND TargetInstance.Type='" & strTargetInstanceType & "' AND " & _
	"TargetInstance.Logfile='" & strEventLog & "' AND TargetInstance.EventCode='" & strEventCode & "'"

Set colMonitoredEvents = objWMIService.ExecNotificationQuery(strQuery) 



Do 
	txt=""
	
	Set objEvent = colMonitoredEvents.NextEvent()
	Set objTargetInst = objEvent.TargetInstance
	
	strTimeWritten= objTargetInst.Properties_("TimeWritten") & ""
	
	Set objSWbemDateTime = CreateObject("WbemScripting.SWbemDateTime")
	objSWbemDateTime.Value=strTimeWritten
	strDate=objSWbemDateTime.GetVarDate(True)	'True=Use OS Timezone
	
	
	strComputerName = objTargetInst.Properties_("ComputerName") & ""
	strType = objTargetInst.Properties_("Type") & ""
	strEventCode = objTargetInst.Properties_("EventCode") & ""
	strMessage= objTargetInst.Properties_("Message") & ""
	strUser = objTargetInst.Properties_("User") & ""
	If strUser<> "" then strUser="User:  " & strUser

	arrMsg=split(strMessage,vbCrLf)
	For each line in arrMsg
		If Instr(line,"Object Name:") then
			tmp=split(line,"Object Name:")(1)
			myFile=Trim(tmp)
			myFile=lcase(replace(myFile,vbTab,""))
			
			If strServer <> "." then myFile="\\" & strServer & "\" & replace(myFile,":","$")
		End If
	Next
	
	'See if the file is one we're monitoring and ACL changed
	filetest=CheckFile(myFile)
	
	If filetest<>"" then
		txt=""
		txt= "--------------------------------------------------------" & vbCrLf & _
			"Permissions modified by " & strUser & vbCrLf & _
			"Time written:  " & strDate & vbCrLf & _
			"Object:  " & myFile & vbCrLf & _
			"Computer:  " & strComputerName & vbCrLf & _
			"Changes:  " & vbCrLf & filetest & vbCrLf
		wscript.echo txt
		WriteLog txt
	End If
	
	

	Set objEvent = Nothing
	Set objTargetInst = Nothing
	strTimeWritten= ""
	strDate=""
	strComputerName = ""
	strType = ""
	strEventCode = ""
	strMessage=""
	strUser = ""
	
Loop

Function CheckFile(myFile)
	chk=""
	For each key in oDict.Keys
		If lcase(key)=lcase(myFile) then
			'See if ACL changed
			currentACL=GetACL(myFile)
			'wscript.echo "current:    " & currentACL
			'wscript.echo "dictionary: " & oDict(myFile)
			
			If ucase(currentACL)<>ucase(oDict(myFile)) then
				'wscript.echo "yes, changed"
				
				'Find what changed
				chk=CompareACL(currentACL,oDict(myFile))
				
				'update dictionary
				oDict(myFile)=currentACL
			Else
				'wscript.echo "no change"
				chk=""
			End If
		End If
	Next
	CheckFile=chk
End Function




Sub RecordACLs(mode)
	Select Case mode
		Case "files"
			myCMD="cmd /c dir /s /b " & Chr(34) & strObject & Chr(34)
		Case "folders"
			myCMD="cmd /c dir /ad /s /b " & Chr(34) & strObject & Chr(34)
	End Select
	
	Set oExec=WshShell.Exec(myCMD)
	
	While Not oExec.StdOut.AtEndOfStream
		count=count+1
		if count=5 then count=1
		
		wscript.stdout.write vbCr & "                                           " & vbCr & _
			"Recording ACL Information for " & mode & "..."
		wscript.stdout.write mid(blah,count,1)
		line=oExec.StdOut.ReadLine
		If line <> "" then GetACL line
	Wend

End Sub

Function GetACL(myFile)
	myFile=lcase(myFile)
	
	myLen=len(myFile)
	test=""
	Set oExec_cacls=WshShell.Exec("cacls " & Chr(34) & myFile & Chr(34))
	While Not oExec_cacls.StdOut.AtEndOfStream
		line_acl=oExec_cacls.StdOut.ReadLine
		if len(line_acl)>myLen then
			acl=acl & Trim(mid(line_acl,myLen+2)) & "|"
		end if
	Wend
	If oDict.Exists(myFile) then
		'compare mode...
		'wscript.echo "checking:  " & myFile
		test=acl
	Else
		oDict.Add myFile,acl
	End If
	acl=""
	GetACL=test
End Function


Function CompareACL(newacl,oldacl)
	arrNew=split(newacl,"|")
	arrOld=split(oldacl,"|")
	
	'Compare old to new - find removals
	For each itmOld in arrOld
		IsRemoval=True
		For each itmNew in arrNew
			if itmOld=itmNew then 
				IsRemoval=False
			end if
		Next
		If IsRemoval=True then removals=removals & vbTab & "Removed:  " & itmOld & vbCrLf
	Next
	
	'Compare new to old - find additions
	For each itmNew in arrNew
		IsAddition=True
		For each itmOld in arrOld
			if itmNew=itmOld then 
				IsAddition=False
			end if
		Next
		If IsAddition=True then additions=additions & vbTab & "Added:    " & itmNew & vbCrLf
	Next
	


	CompareACL=removals & additions

End Function

Sub WriteLog(txt)
	Set oFile=fso.OpenTextFile(strLogFile,FOR_APPENDING,true)
	oFile.WriteLine txt
	oFile.Close
End Sub

Open in new window

0
 

Author Comment

by:Brijeshk9
ID: 30975878
Actually SMTP is not allowed to run on any individual server in my Office Environment,m using outlook on my PC.& i just need to put exchange address in outlook configuration.

let me check the script..will update you accordingly.

Thanks
0
 

Author Comment

by:Brijeshk9
ID: 31261822
As you have mentioned in line:31:
'Folder or File to monitor
strObject="c:\temp"

Not able to monitor multiple files in a folder-working for single file only..?getting data in results.txt  for single file only
0
 
LVL 12

Expert Comment

by:jostrander
ID: 31272036
Do you have the audit settings enabled for every file and subfolder?
0
 
LVL 12

Expert Comment

by:jostrander
ID: 31275981
It was working before, wasn't it?
0
 

Author Comment

by:Brijeshk9
ID: 31289743
yes, the very first script was crating alert for permission changes for all the files in a folder..but current script is only creating output for single file .
0
 
LVL 12

Expert Comment

by:jostrander
ID: 31301603
The latest one is still working for me.  Does the old one give you results still?  

I wonder if your audit settings changed or something.  Do you see any Event #560 (or 4670 in win7) in your Event Viewer --> Security Log?
0
 

Author Comment

by:Brijeshk9
ID: 31339691
Sorry ..my mistake.. actually its working now.. recording data for all the changes..Great Help..
Let me check it if I am able to sent this data in mails body..like one mail for daily basis.

Thanks for the Great Help.!!!
0
 
LVL 12

Expert Comment

by:jostrander
ID: 31373264
If SMTP is still disallowed in your environment, maybe you cold use Outlook.  If you're interested in trying that, here's a vbs sample:
TextBody="This is my text body."
Subject="Test Message"
EmailTo="you@somewhere.com"
EmailFrom="you@somewhere.com"


'Create an Outlook object
Dim Outlook 'As New Outlook.Application
Set Outlook = CreateObject("Outlook.Application")

'Create e new message
Dim Message 'As Outlook.MailItem
Set Message = Outlook.CreateItem(olMailItem)

With Message
	'You can display the message To debug And see state
	'Remove or Comment out .Display to hide
	.Display
	
	.Subject = Subject
	.Body = TextBody
	
	'Set destination email address
	.Recipients.Add (EmailTo)
	
	'Set sender address If specified.
	Const olOriginator = 0
	If Len(EmailFrom) > 0 Then .Recipients.Add(EmailFrom).Type = olOriginator
	
	'Send the message
	.Send
End With

Open in new window

0
 

Author Closing Comment

by:Brijeshk9
ID: 32217121
Thanks a lot.
0
 

Author Comment

by:Brijeshk9
ID: 32217176
Thanks for all you support.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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

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.
With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
The video provides a quick and easy steps to migrate MBOX file to well known Outlook PST and Office 365. Besides this, it also supports and migrates more than 20 email clients of MBOX which include AppleMail, Opera, Thunderbird and SeaMonkey effortl…
The video will let you know the exact process to import OST/PST files to the cloud based Office 365 mailboxes. Using Kernel Import PST to Office 365 tool, one can quickly import numerous OST/PST files to Office 365. Besides this, the tool also comes…
Suggested Courses

601 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