[SOLVED] WAPT.write_audit_data_if_changed

Share your tips or issues concerning the WAPT Console or WAPT Agent here
Forum Rules
Community Forum Rules
* English support on www.reddit.com/r/wapt
* French community support is available on this forum
* Please prefix the topic title with [RESOLVED] if it is resolved.
* Please do not edit a topic that is tagged [RESOLVED]. Open a new topic referencing the old one.
* Specify the installed WAPT version, full version, and build number (2.2.1.11957 / 2.2.2.12337 / etc.) as well as the Enterprise/Discovery edition.
* Versions 1.8.2 and earlier are no longer supported. The only questions accepted regarding version 1.8.2 are related to upgrading to a supported version (2.1, 2.2, etc.).
* Specify the server OS (Linux/Windows) and version (Debian Buster/Bullseye - CentOS 7 - Windows Server 2012/2016/2019).
* Specify the OS of the administration/package creation machine and the machine with the problematic agent, if applicable (Windows 7/10/11/Debian 11/etc.).
* Avoid asking multiple questions when opening a topic, otherwise it may be ignored. If there are multiple topics, open separate topics, preferably one after the other and not all at the same time (i.e., do not spam the forum).
* Include code snippets, screenshots, and other images directly in the post. Links to Pastebin, Bitly, and other third-party sites will be systematically removed.
* As with any community forum, support is provided voluntarily by members. If you require commercial support, you can contact Tranquil IT's sales department at 02.40.97.57.55
Locked
vincent.moisan
Messages: 20
Registration: January 24, 2023 - 11:44

September 19, 2024 - 11:48

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
User avatar
sfonteneau
WAPT Expert
Messages: 2318
Registered: July 10, 2014 - 11:52 PM
Contact :

September 19, 2024 - 12:40

Hello,

if you provide the code for your package it will be easier to help you (plus the code might be useful).
vincent.moisan
Messages: 20
Registration: January 24, 2023 - 11:44

September 19, 2024 - 2:19 PM

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.
Attachments
Session_Counter.zip
PowerShell zipper script
(1.39 KB) Downloaded 346 times
User avatar
sfonteneau
WAPT Expert
Messages: 2318
Registered: July 10, 2014 - 11:52 PM
Contact :

September 20, 2024 - 12:54

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
vincent.moisan
Messages: 20
Registration: January 24, 2023 - 11:44

September 20, 2024 - 1:59 PM

Thanks for the reply, it works.
User avatar
dcardon
WAPT Expert
Messages: 1929
Registration: June 18, 2014 - 09:58
Location: Saint Sébastien sur Loire
Contact :

September 26, 2024 - 11:13

Hi Vincent,

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

See you soon,

Denis
Denis Cardon - Tranquil IT
Share your experiences on WAPT! Send us your blog and article URLs in the "Your Opinion of the forum, and we'll feature them on the WAPT
Locked