Fires of Heaven Guild Message Board  

Go Back   Fires of Heaven Guild Message Board > General forums > Development
User Name
Password
Or, use your gamerDNA username: (more...)
ForumSpy Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

Reply
 
LinkBack Thread Tools Search this Thread Rate Thread Display Modes
Old 04-15-2008, 10:00 PM   #1 (permalink)
Jaytee Bushwacker
FoH Member with a rod in his pants
 
Jaytee Bushwacker's Avatar
 
Join Date: Jan 2002
Location: Forest, MS
Posts: 248
+0 Internets
Help converting WMI VBScript to VB.NET 2005

Problem:
I need to backup and clear the security event log. I have this working via
a vbscript which I will post below. However while I can use this script
manually it is not user friendly and my end users who have to perform the
backup and clear chore weekly are the "where is the button" types.

I have written a vb.net 2005 gui as a front end that can launch my script
and run it ok but the problem is since it is a script running in a shell
object I have no way to return status to my vb.net program saying it succeded or failed or even to know when the shell exits. I could have the script write a status file but that is clumsy and there is a better way to do it.

So I decided to look into writing performing the steps via vb.net code. I
can successfully create a WMI connection and (on the local machine) I can
even list out all log files by code shown below. What I cannot do is execute
the BackupEventLog method via WMI. I get access denied, which I have
researched and I feel the reason is that the WMI connection does not have the
privileges enabled for backup and security. If you look at the vbs script
below you will see where it adds (Backup, security) into the moniker for the
object and I believe allows the execution of the method.

I did find out there that you are supposed to use the ".EnablePrivileges =
True" option but I also found that .NET 1.1 messed that option up. Someone
please help!

CREATE CONNECTION CODE:
===================BEGIN
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

With myConnectionOptions
.Impersonation = Management.ImpersonationLevel.Impersonate

'* Use next line for XP
.Authentication = System.Management.AuthenticationLevel.Packet
.EnablePrivileges = True

'Cannot specify username/password for local connections
'.Username = Me.txtUsername.Text
'.Password = Me.txtPassword.Text
End With

'* "." is the string for a local connection
Dim myServerName As String = Me.txtServer.Text

myManagementScope = New System.Management.ManagementScope("\\" &
myServerName & "\root\cimv2", myConnectionOptions)

'* connect to WMI namespace
myManagementScope.Connect()
If myManagementScope.IsConnected = False Then
rtbStatus.AppendText("Could not connect to WMI namespace on " &
myServerName & ControlChars.Cr)
Else
rtbStatus.AppendText("Connected to WMI namespace on " &
myServerName & ControlChars.Cr)
End If
End Sub
===================END

LIST ALL LOG FILES CODE:
===================BEGIN
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
Dim logfileSearcher As System.Management.ManagementObjectSearcher
Dim logfiles As System.Management.ManagementObjectCollection
Dim logfile As System.Management.ManagementObject

logfileSearcher = New
System.Management.ManagementObjectSearcher(myManag ementScope.Path.ToString,
"Select * from win32_NTEventLogFile")

'* execute query
logfiles = logfileSearcher.Get()

Try

For Each logfile In logfiles

rtbStatus.AppendText("Found logfile " &
logfile.GetPropertyValue("FileName").ToString & " which is the " &
logfile.GetPropertyValue("LogfileName").ToString & " event log" &
ControlChars.Cr)

'INSERT BACKUP CODE HERE (SHOWN BELOW)

Next

Catch ex As Exception
rtbStatus.AppendText("Error Encountered: " & ex.ToString &
ControlChars.Cr)
End Try
End Sub
===================END


FAILING BACKUP METHOD INVOCATION
===================BEGIN
Dim inParams As Management.ManagementBaseObject =
logfile.GetMethodParameters("BackupEventLog")

inParams("ArchiveFileName") = "c:\testing.evt"

Dim outParams As Management.ManagementBaseObject =
logfile.InvokeMethod("BackupEventLog", inParams, Nothing)
===================END


WORKING VBS SCRIPT
===================BEGIN
'Arguments
fileName = WScript.Arguments.Item(0)
logType = WScript.Arguments.Item(1)
fullPathName = filename & ".evt"

'NOTE: for this to work on a normal user account they must have following
rights
'Manage Auditing and Secuirty
'Generate Security Audits

strComputer = "."
Set objWMIService = GetObject("winmgmts:" &
"{impersonationLevel=impersonate,(Backup,security)} !\\" & strComputer &
"\root\cimv2")
Set colLogFiles = objWMIService.ExecQuery ("SELECT * FROM
Win32_NTEventLogFile WHERE LogFileName='" & logType & "'")


For Each objLogfile in colLogFiles
errBackupLog = objLogFile.BackupEventLog(fullPathName)

If errBackupLog = 0 Then
Wscript.Echo "The Security event log was backed up."
objLogFile.ClearEventLog()
End If
If errBackupLog = 8 Then
Wscript.Echo "Privilege missing!"
End If
If errBackupLog = 21 Then
Wscript.Echo "Invalid Parameter in call"
End If

If errBackupLog = 183 Then
Wscript.Echo "The archive file already exists."
End If
Next
===================END
__________________
Jaytee Bushwacker is offline   Reply With Quote
Old 04-16-2008, 07:14 AM   #2 (permalink)
Niceshot23
Registered User
 
Join Date: Oct 2004
Posts: 112
+0 Internets
I understand you trying to do it in vb.net and all ... but, why are you not just creating batch files on your server to do this and having scheduler run it daily?
Niceshot23 is offline   Reply With Quote
Old 04-16-2008, 10:05 PM   #3 (permalink)
Jaytee Bushwacker
FoH Member with a rod in his pants
 
Jaytee Bushwacker's Avatar
 
Join Date: Jan 2002
Location: Forest, MS
Posts: 248
+0 Internets
that actually isn't an unreasonable suggestion but it does limit you to actually setting it up on each specific box and if you ever want to change anything you have to do it everywhere manually.

I figured out how to make it work in .NET today after a lot of searching and trying and asking on forums. Essentially you don't need to do the impersonation option and you need to set the options.enablepermissions to true. From what I can gather (and I may be wrong) when you open a wmi connection and use impersonate it attempts to run on the remote machine with the user credentials you launched your process with on whatever machine you physically at. It really doesn't seem to like that.

If you just skip specifying the options.impersonate property it works fine as long as you then specify appropriate credentials through the options property. So far I have it working so that I can connect to any computer on the network I specify and can backup and clear the log. With a little bit of work I hope to make it so that I can even specify a UNC path to backup to.

If I manage to make that work I can now launch one process at the server and go out and get every machines security log on the network instead of walking around to 30+ stations that have between 1 and 9 computers each.

If you are interested I'll share it once I have it working like I want.
__________________
Jaytee Bushwacker is offline   Reply With Quote
Old 04-17-2008, 08:10 AM   #4 (permalink)
Niceshot23
Registered User
 
Join Date: Oct 2004
Posts: 112
+0 Internets
i was never impressed by impersinate feature ... it created a lot of headache's ... especially when it worked on some machines and didn't on others ... i'd advise against it ... but if you can find another means ... then go for it
Niceshot23 is offline   Reply With Quote
Old 04-17-2008, 02:40 PM   #5 (permalink)
Rhuobhe
all hail Rhuobhe Manslayer
 
Rhuobhe's Avatar
 
Join Date: Jul 2007
Location: Miami, FL
Posts: 357
The IT guy for one of the departments in my company uses vb for everything including mapping drives and printers instead of using batch files like everyone else.

Pain in the butt
Rhuobhe is offline   Reply With Quote
Old 04-20-2008, 10:50 PM   #6 (permalink)
Jaytee Bushwacker
FoH Member with a rod in his pants
 
Jaytee Bushwacker's Avatar
 
Join Date: Jan 2002
Location: Forest, MS
Posts: 248
+0 Internets
Here is the code I use in my app to create a thread and do the backup/clear operations. It took a couple days but I finally have it working pretty well for the local connection, I can make it work for remotes but I'm trying to decide how I want to design my connection function to accept a username/password.



Code:
Private Sub cmdWMIArchive_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdWMIArchive.Click Dim saveFileName As String = Me.archiveDrive & "" & Me.archiveRootDirectory & "" & Me.txtSaveFile.Text Dim computer As String = Me.txtComputerName.Text Dim args(1) As Object args(0) = saveFileName args(1) = computer Me.rtbStatus.Clear() 'BackupAndClearLog(args) Dim threadA As New Thread(New ParameterizedThreadStart(AddressOf backupClearLog)) threadA.Start(args) End Sub Sub backupClearLog(ByVal args As Object) Dim scope As New System.Management.ManagementScope Dim logSearcher As New System.Management.ManagementObjectSearcher Dim logfiles As System.Management.ManagementObjectCollection Dim logfile As System.Management.ManagementObject Dim inParams As System.Management.ManagementBaseObject Dim outParams As System.Management.ManagementBaseObject Dim result As UInt32 Dim backupFile As String = args(0) Dim computer As String = args(1) Dim updateArgs(1) As Object Try 'My attempt at creating a dll with WMI functions 'it just executes the following manual way code myWMI.openConnection(scope, computer) 'The Manual way 'scope.Options.EnablePrivileges = True 'scope.Path.Path = "\\.\root\cimv2" 'scope.Connect() 'I'm calling a sub that updates a richtextbox control on my UI with connection status Me.Invoke(New connectedToDelegate(AddressOf connectedTo), scope) logSearcher.Query.QueryString = "Select * from win32_NTEventLogFile WHERE LogFileName='security'" logfiles = logSearcher.Get() For Each logfile In logfiles 'Can't update UI from a thread directly next few lines do it via invoke 'rtbStatus.AppendText(logfile.Item("Name") & ControlChars.Cr) updateArgs(0) = False updateArgs(1) = logfile.Item("Name") & ControlChars.Cr Me.Invoke(New updateStatusDelegate(AddressOf updateStatus), updateArgs) 'This block actually does the backup inParams = logfile.GetMethodParameters("BackupEventLog") inParams.Item("ArchiveFileName") = backupFile outParams = logfile.InvokeMethod("BackupEventLog", inParams, Nothing) result = outParams.Item("returnValue") 'Can't update UI from a thread directly next few lines do it via invoke 'Me.rtbStatus.AppendText("BackupEventLog " & myWMI.exitCodeMessage(outParams.Item("returnValue"), "win32_NTEventLogFile") & ControlChars.Cr) updateArgs(0) = False updateArgs(1) = "BackupEventLog " & myWMI.exitCodeMessage(outParams.Item("returnValue"), "win32_NTEventLogFile") & ControlChars.Cr Me.Invoke(New updateStatusDelegate(AddressOf updateStatus), updateArgs) 'If backup was successful result will be 0 - only then do we clear If result = 0 Then 'Have to do the same thing as backup to clear the log just call the ClearEventLog method 'There are no parameters for the clear method but if we don't reinit inParams it will hose up inParams = logfile.GetMethodParameters("ClearEventLog") outParams = logfile.InvokeMethod("ClearEventLog", inParams, Nothing) 'Can't update UI from a thread directly next few lines do it via invoke 'Me.rtbStatus.AppendText("ClearEventLog " & myWMI.exitCodeMessage(outParams.Item("returnValue"), "win32_NTEventLogFile") & ControlChars.Cr) updateArgs(0) = False updateArgs(1) = "BackupEventLog " & myWMI.exitCodeMessage(outParams.Item("returnValue"), "win32_NTEventLogFile") & ControlChars.Cr Me.Invoke(New updateStatusDelegate(AddressOf updateStatus), updateArgs) End If Next Catch ex As Exception 'Can't update UI from a thread directly next few lines do it via invoke 'Me.rtbStatus.AppendText(ex.Message & ControlChars.Cr) updateArgs(0) = False updateArgs(1) = ex.Message & ControlChars.Cr Me.Invoke(New updateStatusDelegate(AddressOf updateStatus), updateArgs) End Try End Sub
__________________
Jaytee Bushwacker is offline   Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are On
Pingbacks are On
Refbacks are On
uberguilds network



All times are GMT -7. The time now is 01:37 AM.


Powered by vBulletin® Version 3.6.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.0.0 RC6