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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?Sm9obkJhdGVz?=

    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 ".EnablePrivile ges =
    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(B yVal sender As System.Object, ByVal e As
    System.EventArg s) Handles Button1.Click

    With myConnectionOpt ions
    .Impersonation = Management.Impe rsonationLevel. Impersonate

    '* Use next line for XP
    .Authentication = System.Manageme nt.Authenticati onLevel.Packet
    .EnablePrivileg es = 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.Te xt

    myManagementSco pe = New System.Manageme nt.ManagementSc ope("\\" &
    myServerName & "\root\cimv 2", myConnectionOpt ions)

    '* connect to WMI namespace
    myManagementSco pe.Connect()
    If myManagementSco pe.IsConnected = False Then
    rtbStatus.Appen dText("Could not connect to WMI namespace on " &
    myServerName & ControlChars.Cr )
    Else
    rtbStatus.Appen dText("Connecte d to WMI namespace on " &
    myServerName & ControlChars.Cr )
    End If
    End Sub
    =============== ====END

    LIST ALL LOG FILES CODE:
    =============== ====BEGIN
    Private Sub Button3_Click(B yVal sender As System.Object, ByVal e As
    System.EventArg s) Handles Button3.Click
    Dim logfileSearcher As System.Manageme nt.ManagementOb jectSearcher
    Dim logfiles As System.Manageme nt.ManagementOb jectCollection
    Dim logfile As System.Manageme nt.ManagementOb ject

    logfileSearcher = New
    System.Manageme nt.ManagementOb jectSearcher(my ManagementScope .Path.ToString,
    "Select * from win32_NTEventLo gFile")

    '* execute query
    logfiles = logfileSearcher .Get()

    Try

    For Each logfile In logfiles

    rtbStatus.Appen dText("Found logfile " &
    logfile.GetProp ertyValue("File Name").ToString & " which is the " &
    logfile.GetProp ertyValue("Logf ileName").ToStr ing & " event log" &
    ControlChars.Cr )

    'INSERT BACKUP CODE HERE (SHOWN BELOW)

    Next

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


    FAILING BACKUP METHOD INVOCATION
    =============== ====BEGIN
    Dim inParams As Management.Mana gementBaseObjec t =
    logfile.GetMeth odParameters("B ackupEventLog")

    inParams("Archi veFileName") = "c:\testing.evt "

    Dim outParams As Management.Mana gementBaseObjec t =
    logfile.InvokeM ethod("BackupEv entLog", inParams, Nothing)
    =============== ====END


    WORKING VBS SCRIPT
    =============== ====BEGIN
    'Arguments
    fileName = WScript.Argumen ts.Item(0)
    logType = WScript.Argumen ts.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("winm gmts:" &
    "{impersonation Level=impersona te,(Backup,secu rity)}!\\" & strComputer &
    "\root\cimv 2")
    Set colLogFiles = objWMIService.E xecQuery ("SELECT * FROM
    Win32_NTEventLo gFile WHERE LogFileName='" & logType & "'")


    For Each objLogfile in colLogFiles
    errBackupLog = objLogFile.Back upEventLog(full PathName)

    If errBackupLog = 0 Then
    Wscript.Echo "The Security event log was backed up."
    objLogFile.Clea rEventLog()
    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

    #2
    Re: Convery WMI script into .NET (using VB.NET 2005)

    Hi,

    You may be better of with

    microsoft.publi c.dotnet.framew ork.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 ".EnablePrivile ges =
    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(B yVal sender As System.Object, ByVal e As
    System.EventArg s) Handles Button1.Click
    >
    With myConnectionOpt ions
    .Impersonation = Management.Impe rsonationLevel. Impersonate
    >
    '* Use next line for XP
    .Authentication = System.Manageme nt.Authenticati onLevel.Packet
    .EnablePrivileg es = 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.Te xt
    >
    myManagementSco pe = New System.Manageme nt.ManagementSc ope("\\" &
    myServerName & "\root\cimv 2", myConnectionOpt ions)
    >
    '* connect to WMI namespace
    myManagementSco pe.Connect()
    If myManagementSco pe.IsConnected = False Then
    rtbStatus.Appen dText("Could not connect to WMI namespace on " &
    myServerName & ControlChars.Cr )
    Else
    rtbStatus.Appen dText("Connecte d to WMI namespace on " &
    myServerName & ControlChars.Cr )
    End If
    End Sub
    =============== ====END
    >
    LIST ALL LOG FILES CODE:
    =============== ====BEGIN
    Private Sub Button3_Click(B yVal sender As System.Object, ByVal e As
    System.EventArg s) Handles Button3.Click
    Dim logfileSearcher As System.Manageme nt.ManagementOb jectSearcher
    Dim logfiles As System.Manageme nt.ManagementOb jectCollection
    Dim logfile As System.Manageme nt.ManagementOb ject
    >
    logfileSearcher = New
    System.Manageme nt.ManagementOb jectSearcher(my ManagementScope .Path.ToString,
    "Select * from win32_NTEventLo gFile")
    >
    '* execute query
    logfiles = logfileSearcher .Get()
    >
    Try
    >
    For Each logfile In logfiles
    >
    rtbStatus.Appen dText("Found logfile " &
    logfile.GetProp ertyValue("File Name").ToString & " which is the " &
    logfile.GetProp ertyValue("Logf ileName").ToStr ing & " event log" &
    ControlChars.Cr )
    >
    'INSERT BACKUP CODE HERE (SHOWN BELOW)
    >
    Next
    >
    Catch ex As Exception
    rtbStatus.Appen dText("Error Encountered: " & ex.ToString &
    ControlChars.Cr )
    End Try
    End Sub
    =============== ====END
    >
    >
    FAILING BACKUP METHOD INVOCATION
    =============== ====BEGIN
    Dim inParams As Management.Mana gementBaseObjec t =
    logfile.GetMeth odParameters("B ackupEventLog")
    >
    inParams("Archi veFileName") = "c:\testing.evt "
    >
    Dim outParams As Management.Mana gementBaseObjec t =
    logfile.InvokeM ethod("BackupEv entLog", inParams, Nothing)
    =============== ====END
    >
    >
    WORKING VBS SCRIPT
    =============== ====BEGIN
    'Arguments
    fileName = WScript.Argumen ts.Item(0)
    logType = WScript.Argumen ts.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("winm gmts:" &
    "{impersonation Level=impersona te,(Backup,secu rity)}!\\" & strComputer &
    "\root\cimv 2")
    Set colLogFiles = objWMIService.E xecQuery ("SELECT * FROM
    Win32_NTEventLo gFile WHERE LogFileName='" & logType & "'")
    >
    >
    For Each objLogfile in colLogFiles
    errBackupLog = objLogFile.Back upEventLog(full PathName)
    >
    If errBackupLog = 0 Then
    Wscript.Echo "The Security event log was backed up."
    objLogFile.Clea rEventLog()
    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)

    Comment

    Working...