6. Utiliser l’API du Serveur WAPT

6.1. API Overview

Note

This documentation does not describe all available APIs. It focuses on the most useful ones.

Currently, it is only possible to use Python code to interact with the an API.

Most of the available APIs can be found in the server.py file located at /opt/wapt/waptserver/server.py on Debian.

Additional APIs are available in other files such as enterprise.py, repositories.py, wads.py, etc.

Avertissement

Since version 2.5, most API URLs are protected with SSL client certificates. Therefore, it is no longer possible to use HTML requests like: https://admin:MYPASSWORD@srvwapt.mydomain.lan/api/v1/hosts.

6.2. Using the APIs

6.2.1. Requirement:

1- Create a WAPT user and assign the ACL « launch requests » (It is recommended to create a new user for requests because the password is included in the request).

In the waptconsole : Go to Tools > Manage Wapt users and rights.

New account > F2 name like reporting.

Change User password on Wapt server (an key appear on the right on your reporting user in the red on the picture below).

Click on « Run Reports » ACL ( in green in the picture below).

Create reporting user

Create reporting user.

2- Depending on the request, it may be necessary to add ACLs on the reporting user. This can be see in the request file You can see this in the request in the api source file.

For Example: On server.py file, you can read this at the begin of the API's resquest groups.

  Example:
  @app.route('/api/v3/groups')
  @app.route('/api/v1/groups')
  @requires_auth(['admin','view']) Requires either the "admin" or "view" ACL (Access Control List) permissions. Having either one or both of these permissions is sufficient to access this endpoint.

6.2.2. Operating procedure:

There are two primary method to do an api request, the Command-Line Method and the Script-Based Method.

Any Wapt agent can launch an API.


6.2.2.1. Command-Line Method

The Command-Line Method involves executing API requests directly from the command line interface (CLI) using tools like cmd on Windows or bash on Unix-based systems. This method is quick and efficient for simple or one-off requests.

Example: On a CLI or bash

wapt-get server-request "/api/v1/hosts" -c waptconsole

6.2.2.2. Script-Based Method

The Script-Based Method requires creating a Python script (.py file) to define and execute the API request. This method is more flexible and powerful, allowing for complex logic, error handling, and data processing.

  1. Connect to a WAPT Windows agent.

  2. Create a directory named waptdev at the root of your disk, like, c:\waptdev\API_request.

  3. Create a .py file in this directory to edit the request, like, api-1.py.

  4. Copy the python script below and personalize the password for your user « reporting » and the desired API.

  5. Run the file with the following command: « C:\Program Files (x86)\wapt\wapt-get.exe » c:\waptdev\API_request\api-1.py.

  6. The output can be displayed in CSV format: cat api-1.csv.

The python script

import json
import waptlicences
import csv
import sys
sys.path.append('/opt/wapt')

from common import Wapt
WAPT = Wapt()
ini_wapt_path = WAPT.config_filename

user = "reporting"
password = "[Enter the password for user reporting]"

def run_report():
    auth_context = waptlicences.waptserver_login(ini_wapt_path, user=user, password=password)
    try:
        res = waptlicences.waptserver_request(ini_wapt_path, action='[enter the desired api like /api/v1/hosts]', auth_context=auth_context)
        if res['http_status'] == 200:
            data = json.loads(res['content'])['result']

            # Debugging: Print the raw data received from the API
            print("Raw data from API:", json.dumps(data, indent=2))

            # Check if data is not empty
            if not data:
                print("No data received from the API.")
                return []

            # Check if the first element of data is a list
            if isinstance(data[0], list):
                for row in data:
                    # Assuming row is a list of strings
                    for i, value in enumerate(row):
                        if isinstance(value, list):
                            row[i] = '|'.join(value)

                with open('test.csv', 'w', newline='', encoding='utf-8') as csvfile:
                    fieldnames = data[0]
                    writer = csv.writer(csvfile, delimiter=';')
                    writer.writerow(fieldnames)
                    writer.writerows(data[1:])  # Write the rest of the data
            else:
                print("Unexpected data format. First element is not a list.")
                return []

            return data
        else:
            raise Exception('Request failed with status %s : %s' % (res['http_status'], res['content']))
    finally:
        waptlicences.waptserver_logout(ini_wapt_path)

# Call the function and print the returned data
data = run_report()
print(repr(data))

6.3. Some examples of api requests


6.3.1. API V1

6.3.1.1. /api/v1/hosts

Récupérer les données enregistrées d’un ou de plusieurs postes.

wapt-get server-request "/api/v1/hosts" -c waptconsole

Listez tous les postes. Les paramètres disponibles sont :

  • reachable ;

  • computer_fqdn ==> computer_name ;

  • connected_ips ;

  • mac_addresses.

Exemple :

wapt-get server-request "/api/v1/hosts?columns=reachable,computer_fqdn,connected_ips,mac_addresses&limit=10000" -c waptconsole

6.3.1.2. /api/v1/groups

Get all dependencies that are directly assigned to a machine package.

wapt-get server-request "api/v1/groups" -c waptconsole

6.3.1.3. /api/v1/host_data


dmi field

Récupérez toutes les informations DMI d’un poste :

wapt-get server-request "api/v1/host_data?uuid=[UUID OF THE COMPUTER]&field=[DMI FIELD DESIRED]" -c waptconsole

Example for the dmi field « os_name » :

wapt-get server-request "api/v1/host_data?uuid=CDAB699D-CA52-98B6-3AC2-749E66B04841&field=os_name" -c waptconsole

installed_packages

L’option installed_packages va lister tous les paquets installés sur un poste en particulier.

Exemple :

wapt-get server-request "api/v1/host_data?uuid=CDAB699D-CA52-98B6-3AC2-749E66B04841&field=installed_packages" -c waptconsole

installed_softwares

L’option installed_softwares va lister tous les logiciels installés sur un poste en particulier.

Exemple :

wapt-get server-request "api/v1/host_data?uuid=CDAB699D-CA52-98B6-3AC2-749E66B04841&field=installed_softwares" -c waptconsole

wsusupdates

L’option wsusupdates va lister toutes les mises à jour installés sur un poste en particulier.

Exemple :

wapt-get server-request "api/v1/host_data?uuid=CDAB699D-CA52-98B6-3AC2-749E66B04841&field=wsusupdates" -c waptconsole

6.3.1.4. /api/v1/usage_statistics

Récupère les statistiques d’usage du Serveur WAPT.

wapt-get server-request "api/v1/usage_statistics" -c waptconsole

Note

Cette API est utile si vous avez plusieurs Serveurs WAPT et si vous voulez savoir combien de postes il y a.

6.3.2. API V2

6.3.2.1. /api/v2/waptagent_version

Affiche la version du waptagent.exe sur le serveur.

wapt-get server-request "/api/v2/waptagent_version" -c waptconsole

6.3.3. API V3

6.3.3.1. /api/v3/packages

Liste les paquets sur le dépôt privé, il récupère le fichier control sur les paquets WAPT.

wapt-get server-request "/api/v3/packages" -c waptconsole

6.3.3.2. /api/v3/known_packages

Liste tous les paquets avec l’information signed_on.

wapt-get server-request "/api/v3/known_packages" -c waptconsole

6.3.3.3. /api/v3/trigger_cancel_task

Annule une tâche en cours.

wapt-get server-request "/api/v3/trigger_cancel_task" -c waptconsole

6.3.3.4. /api/v3/get_ad_ou

Liste les OU vues par les postes et affichées dans la Console WAPT.

wapt-get server-request "/api/v3/get_ad_ou" -c waptconsole

6.3.3.5. /api/v3/get_ad_sites

Liste les sites Active Directory.

wapt-get server-request "/api/v3/get_ad_sites" -c waptconsole

6.3.3.6. /api/v3/hosts_for_package

Liste les hôtes avec un packaging spécifique installé.

wapt-get server-request "/api/v3/hosts_for_package?package=[name of your package like tis-paint]" -c waptconsole

6.3.3.7. /api/v3/ping

Ping va récupérer les informations générales d’un Serveur WAPT.

Exemple :

wapt-get server-request /api/v3/ping -c waptconsole

6.3.3.8. /api/v3/reporting_exec

Voici un script python qui exécute une requête avec un identifiant spécifique à partir de l’onglet Rapports de la console WAPT. Dans ce script, l’utilisateur « reporting » doit avoir l’ACL « Run reports ». Ce script fonctionne sur toutes les plateformes (agents windows, linux et mac).

import os
import json
import logging
import waptlicences
import requests
import sys
sys.path.append('/opt/wapt')
from common import get_requests_client_cert_session
from common import Wapt



WAPT = Wapt()
ini_wapt_path = WAPT.config_filename
w = Wapt(config_filename=ini_wapt_path)

# WAPT Conf
wapt_url = w.waptserver.server_url

user = "reporting"
password = "password"


def run_report():

    t = waptlicences.waptserver_login(ini_wapt_path,user,password)
    session = get_requests_client_cert_session(wapt_url,
    cert=(t['client_certificate'],t['client_private_key'],t['client_private_key_password']),
    verify=w.waptserver.verify_cert
    )
    if not 'session' in t['session_cookies']:
      session_cookies = [u for u in t['session_cookies'] if u['Domain'] == WAPT.waptserver.server_url.split('://')[-1]][0]
    else:
      session_cookies = t['session_cookies']['session']
      session_cookies['Name'] = 'session'

    session.cookies.set(session_cookies['Name'], session_cookies['Value'], domain=session_cookies['Domain'])
    t= None


    url = f'{wapt_url}/api/v3/reporting_exec?id=19'
    response = session.get(url)
    data = response.json()

    return data['result']



print(run_report())

Danger

Les API ci-après suivent la méthode POST.


6.3.3.9. /api/v3/change_password

Change le mot de passe du compte admin [ce compte uniquement]. La requête doit être un dictionnaire python {}. Les clés doivent être :

  • user;

  • old_password;

  • new_password.

Exemple :

wapt-get server-request /api/v3/change_password --method=POST --data="{'user':'USER','password':'old_password',''new_password':'new_password'}"

6.3.3.10. /api/v3/packages_delete

Supprime un paquet d’une version précise. La requête doit être une liste []. Elle peut prendre plusieurs paquets séparés par des virgules ,.

Exemple :

wapt-get server-request /api/v3/packages_delete --method=POST --data="['ht-wapt-debian-gui_2.6.0.16977-2_0fce3ca2b61ebdbdc9b4b065cfe87176_PROD.wapt']" -c waptconsole

6.3.3.11. /api/v3/trigger_wakeonlan

Si les postes ont le WakeOnLan d’activé, cette API est utile.

La syntaxe est : --data-raw : un dictionnaire avec pour clé les uuid et pour valeur l’uuid du poste.

Exemple :

wapt-get server-request /api/v3/trigger_wakeonlan --method=POST --data="{'uuids':['C74B68E2-CB63-BC4D-B6DB-74110DD4E535']}" -c waptconsole