Page 1 of 1

[SOLVED] WAPT.write_audit_data_if_changed

Published: September 19, 2024 - 11:48 AM
by Vincent Moisan
Good morning,

I am a system administrator at a school.

To know the frequency of use of the deployed PCs, I created a package that reports the durations of user sessions (based on Windows session connections/disconnections/locks/unlocks).

However, for ease of querying, I would like to store this information in the Audit Data section.

To do this, I used the WAPT.write_audit_data_if_changed function, passing the results of my packet in JSON format as a parameter. The data is correctly stored in the audit data, but it is not interpreted correctly. That is to say, I do have something resembling JSON in the "value" line, but it is incorrectly formatted.
example:

Code: Select all

users connexions stats.pc-test =

"{\"report_date\":\"2024-09-18T13:57:46Z\",\"hostname\":\"PC-Test\",\"session_data\":[{\"history_days\":-1,\"total_minutes\":\"52\",\"start_date\":\"2024-09-17T13:57:31Z\",\"total_days\":\"0\",\"total_hours\":\"4\",\"total_seconds\":\"54\",\"date_history\":\"-1\"},{\"history_days\":-7,\"total_minutes\":\"56\",\"start_date\":\"2024-09-11T13:57:35Z\",\"total_days\":\"0\",\"total_hours\":\"20\",\"total_seconds\":\"3\",\"date_history\":\"-7\"},{\"history_days\":-15,\"total_minutes\":\"57\",\"start_date\":\"2024-09-03T13:57:38Z\",\"total_days\":\"1\",\"total_hours\":\"21\",\"total_seconds\":\"36\",\"date_history\":\"-15\"},{\"history_days\":-30,\"total_minutes\":\"50\",\"start_date\":\"2024-08-19T13:57:42Z\",\"total_days\":\"3\",\"total_hours\":\"20\",\"total_seconds\":\"13\",\"date_history\":\"-30\"}]}\r\n"
Date: 2024-09-18T11:57:46.985788
Could you guide me on what I'm doing wrong?

Sincerely

Re: WAPT.write_audit_data_if_changed

Published: September 19, 2024 - 12:40 PM
by sfonteneau
Hello,

if you provide the code for your package it will be easier to help you (plus the code might be useful).

Re: WAPT.write_audit_data_if_changed

Published: September 19, 2024 - 2:19 PM
by Vincent Moisan
Here is the code for my package:

Code: Select all

### -*- coding: utf-8 -*-
from setuphelpers import *

def install():
    filecopyto('Compteur_Session.ps1',makepath(programfiles32,'wapt'))
def write_audit_data_if_changed(self, section, key, value):
    """Write data only if different from last one"""
def audit():
    output = run(r'powershell.exe -NoProfile -NonInteractive -executionpolicy bypass -File "%s"' % makepath(programfiles32,'wapt','Compteur_Session.ps1') ,accept_returncodes=[1,0])
    print(output)
    WAPT.write_audit_data_if_changed('Users Connexions Stats','%s' % get_computername(), output)
    return "OK"

I have also attached my PowerShell script in txt format and then zipped it.

Re: WAPT.write_audit_data_if_changed

Published: September 20, 2024 - 12:54 PM
by sfonteneau
The output is not a dictionary but a JSON file

so if you make a

Code: Select all

WAPT.write_audit_data_if_changed('Users Connexions Stats','%s' % get_computername(),json.loads(output))

It should be better


Note for doing this kind of thing in Python:

Code: Select all

# -*- coding: utf-8 -*-
from setuphelpers import *
import wmi
from datetime import datetime

# Usable WAPT package functions: install(), uninstall(), session_setup(), audit(), update_package()
# Declaring global variables - Warnings: 1) WAPT context is only available in package functions; 2) Global variables are not persistent between calls

def install():
    # auditpol /list /subcategory:*
    # auditpol /get /category:*

    #SET
    run('AUDITPOL /SET /SUBCATEGORY:"Ouvrir la session" /SUCCESS:ENABLE /FAILURE:ENABLE')
    run('AUDITPOL /SET /SUBCATEGORY:"Fermer la session" /SUCCESS:ENABLE /FAILURE:ENABLE')

def audit():
    # Initialize WMI objects and query.
    wmi_o = wmi.WMI('.')
    wql = ("SELECT * FROM Win32_NTLogEvent WHERE Logfile="
           "'System' AND EventCode='7001' OR EventCode='7002'")
    # Query WMI object.
    wql_r = wmi_o.query(wql)
    wql_r.reverse()
    for event in wql_r:
        sid = list(event.InsertionStrings)[1]
        if not sid.startswith('S-1-5'):
            continue
        username = get_user_from_sid(sid)
        if username.strip() == "" or not username:
           continue

        if event.EventCode == 7001 :
            typeevent = 'User-Connect'
        else:
            typeevent = 'User-Disconnect'

        realdate = event.TimeGenerated.split('.')[0]
        humandate = datetime.strptime(realdate, '%Y%m%d%H%M%S')

        found = False
        for u in list(WAPT.read_audit_data_set(typeevent,username)):
            if u[0] == str(humandate):
                found = True
        if found:
            continue

        WAPT.write_audit_data(typeevent,username,value = str(humandate), keep_days=365,max_count=9999)

    return "OK"
It's a piece of code I started but never finished

Re: WAPT.write_audit_data_if_changed

Published: September 20, 2024 - 1:59 PM
by Vincent Moisan
Thanks for the reply, it works.

Re: WAPT.write_audit_data_if_changed

Published: September 26, 2024 - 11:13 AM
by dcardon
Hi Vincent,

thanks for the feedback. :-) I'm marking the topic as RESOLVED.

See you soon,

Denis