473,397 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Convery WMI script into .NET (using VB.NET 2005)

Problem:
I need to backup and clear the security event log. I have this working via
a vbsscript 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.

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 addes (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
Jun 27 '08 #1
1 1088
Hi,

You may be better of with

microsoft.public.dotnet.framework.wmi

in future for this type of thing.

I can't help with the .NET side, as I don't use it, but a couple of
things jump out at me from your post.

1. If the user is the "where the button" type, why are they allowed
anywhere NEAR a security log. They'd need full admin rights for a start,
and you've just lost your audit trail.

2. If the old version was working, and they just need a "button", why
can't they just have shortcut to click on?

3. If it's for lots of users, why not just have a button on an intranet
page where they click, and based on valid user authentication, this
would start a new process in a new security context that would clear the
log.

4. Why not just have a scheduled job to backup the log and then clear it?

JohnBates wrote:
Problem:
I need to backup and clear the security event log. I have this working via
a vbsscript 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.

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 addes (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

--
Gerry Hickman (London UK)
Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Paul Winkler | last post by:
This is driving me up the wall... any help would be MUCH appreciated. I have a module that I've whittled down into a 65-line script in an attempt to isolate the cause of the problem. (Real...
1
by: neha | last post by:
hi, i m trying to integrate python with apache on linux.For this i m using mod_python. I dont see any problem with the versions of python,apache and mod_python i m using. the versions i m using...
33
by: patrick_woflian | last post by:
hey guys, im just writing a basic calculation at the moment, before building on it for an A-Level piece of work. i can add/divide etc... two numbers together yet i am having a major problem with...
2
by: Ted O'Connor | last post by:
I am trying to script the DROP(IF EXISTS) and CREATE for all of my tables, views, stored procs, and functions to individual SQL text files (one per object). This was trivially done in SQL 2000...
11
by: billmiami2 | last post by:
I recently generated a script using SQL Server 2005 for a local database that is configured as SQL Server 2000. Nevertheless, the script used the new structures and syntax (i.e., sys.objects vs....
2
by: M Bourgon | last post by:
I'm trying to automate an auto-export of a table on a daily basis, using BCP. I'm using native format for the BCP because the text in one of the fields can encompass pretty much any ASCII...
3
by: traceable1 | last post by:
Is there a way I can set up a SQL script to run when the instance starts up? SQL Server 2005 SP2 thanks!
1
by: =?Utf-8?B?Sm9obkJhdGVz?= | last post by:
Problem: I need to backup and clear the security event log. I have this working via a vbsscript which I will post below. However while I can use this script manually it is not user friendly and...
1
by: swethak | last post by:
hi, i have a code to disply the calendar and add events to that. It works fine.But my requirement is to i have to disply a weekly and daily calendar.Any body plz suggest that what modifications i...
13
by: ramprakashjava | last post by:
hi, i hav "java.lang.NullPointerException" error while Deleting table records using checkbox in jsp here i enclosed files help quickly plzzz.. ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.