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

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
Brijeshk9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Glen KnightCommented:
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
DBAduck - Ben MillerPrincipal ConsultantCommented:
You may also use WMI to monitor the folder and just wait for the event in WMI.
0
Brijeshk9Author Commented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

DBAduck - Ben MillerPrincipal ConsultantCommented:
Here is a good place for you to start.

http://msdn.microsoft.com/en-us/library/ms141130.aspx
0
DBAduck - Ben MillerPrincipal ConsultantCommented:
0
Brijeshk9Author Commented:
As of now I didn’t get any satisfactory answer of my questions..?
0
jostranderCommented:
Is it a large number of files?  

Do they all require a specific ACL, like only allow Domain Admins, GroupABC, etc?
0
Brijeshk9Author Commented:
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
jostranderCommented:
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
Brijeshk9Author Commented:
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
jostranderCommented:
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
jostranderCommented:
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
Brijeshk9Author Commented:
Please make it :email on every change..

0
jostranderCommented:
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
Brijeshk9Author Commented:
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
Brijeshk9Author Commented:
Although I have changed the smtp address, same error I was getting for previous script also..?
0
jostranderCommented:
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
Brijeshk9Author Commented:
yes, i have already tried with internal SMTP, but again getting same error in Application event Log with ID: 1 & source :WSH.?
0
Brijeshk9Author Commented:
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
jostranderCommented:
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
jostranderCommented:

'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
jostranderCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Brijeshk9Author Commented:
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
Brijeshk9Author Commented:
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
jostranderCommented:
Do you have the audit settings enabled for every file and subfolder?
0
jostranderCommented:
It was working before, wasn't it?
0
Brijeshk9Author Commented:
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
jostranderCommented:
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
Brijeshk9Author Commented:
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
jostranderCommented:
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
Brijeshk9Author Commented:
Thanks a lot.
0
Brijeshk9Author Commented:
Thanks for all you support.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.