#!/usr/bin/python3 import os import argparse import logging from functions import getSettings from includes.airwatchAPI import * from includes.GLPIAPI import * parser = argparse.ArgumentParser() parser.add_argument("-sn", "--serialnumber", dest="serialnumber", type=str) parser.add_argument("-u", "--staginguser", dest="staginguser", type=str) parser.add_argument("-c", "--configPath", dest="configpath", type=str) parser.add_argument("-f", "--force", dest="force", action="store_true") parser.add_argument("-s", "--silent", dest="silent", action="store_true") parser.add_argument("-v", "--verbose", dest="debug", action="store_true") args = parser.parse_args() # Récupération des informations du fichier de configuration if(args.configpath != None and args.configpath != ''): settings = getSettings(args.configpath) else: settings = getSettings("./conf/settings.conf") #=========== Configuration des logs ===========# logger = logging.getLogger(__name__) if(args.debug or settings["LOGS"]["Debug"]): debug = True logginglevel = logging.DEBUG else: logginglevel = logging.INFO logger.setLevel(logginglevel) formatter = logging.Formatter(fmt='%(asctime)s | %(levelname)s: %(message)s', datefmt='%Y/%m/%d %H:%M:%S') # handler pour log dans un fichier if(settings["LOGS"]["Enabled"]): if(settings["LOGS"].get("Path") and settings["LOGS"].get("Path") != ""): fileHandler = logging.FileHandler(f"{settings['LOGS'].get('Path')}stagingUserAssignation.log") else: fileHandler = logging.FileHandler('./logs/stagingUserAssignation.log') fileHandler.setLevel(logginglevel) fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) # handler pour log dans la console if(not args.silent): consoleHandler = logging.StreamHandler() consoleHandler.setLevel(logginglevel) consoleHandler.setFormatter(formatter) logger.addHandler(consoleHandler) #======== Paramètres du script ========# # Emplacement du verrou lockFile = './airwatchStagingUserAssignation.lock' debug=args.debug stagingUser = settings["AIRWATCH"]["StagingUser"] if(args.staginguser != None): stagingUser = args.staginguser # ====================================== # # Vérification de la présence du verrou avant de continuer if(os.path.isfile(lockFile) and not args.force): logger.debug('Lock file exists, exiting...') exit(0) else: open(lockFile, "w").close() # Initialisation de l'api Airwatch try: airwatch = AirwatchAPI(settings) # Recherche des appareils filtré sur l'utilisateur de staging devices = airwatch.GetDevices(stagingUser) logger.info("Airwatch server connection succeeded") except FileNotFoundError as F: logger.critical(f"Certificate file not found for CMSURL authentication : {F}") os.remove(lockFile) exit(1) except Exception as error: logger.critical(f"Connection to Airwatch server failed : {error}") os.remove(lockFile) exit(1) if(devices == None): logger.info(f"No device found with staging user ({stagingUser}), exiting...") os.remove(lockFile) exit(0) else: logger.info(f"{len(devices)} devices found with staging user ({stagingUser})") # Initialisation de l'api GLPI try: glpiapi = GLPIAPI(settings) logger.info("GLPI server connection succeeded") except requests.exceptions.ConnectionError as error: logger.critical(f"Connection to GLPI server failed : {error}") os.remove(lockFile) exit(1) for device in devices: if(device.EnrollmentStatus != 'Enrolled'): logger.error(f"Device with id {device.Id} not enrolled, should it be deleted ?") continue if(args.serialnumber != None and device.SerialNumber != args.serialnumber): continue if(debug): logger.debug(f"Serial Number = {device.SerialNumber}") deviceID, data, deviceCount = glpiapi.GetDevice(device) if(deviceCount == 1): # Récupération de l'utilisateur de l'appareil dans la fiche GLPI de l'appareil device_user = data["70"] logger.info(f"Found device {device.Id} in GLPI with id = {deviceID}") logger.debug(f"user on device in GLPI : {device_user}") # Vérification que l'appareil est associé à un utilisateur dans GLPI if(device_user != None): # Récupération de l'utilisateur sur Airwatch airwatchUser = airwatch.GetUser(device_user) if(airwatchUser == None): logger.error(f"User {device_user} not found in Airwatch") continue logger.info(f"Assigning device with id {device.Id} to user {device_user} (id={airwatchUser.Id}) in Airwatch") result = airwatch.SetDeviceUser(device, airwatchUser) else: logger.warning(f"Device with id {device.Id} is not assigned to any user in GLPI, skipping the device") elif(deviceCount > 1): logger.error(f"{count} devices matching airwatch device {device.FriendlyName} (Airwatch id={device.Id}) in GLPI trashbin (GLPI ids = {', '.join(deviceID)}), skipping this device...") else: deviceIDTrash, dataTrash, deviceCountTrash = glpiapi.GetDevice(device, trashbin=True) if(countTrash > 1): logger.error(f"{countTrash} devices matching airwatch device {device.FriendlyName} (Airwatch id={device.Id}) in GLPI trashbin (GLPI ids = {', '.join(deviceIDTrash)}), skipping this device...") elif(countTrash == 1): logger.warning(f"Device {device.FriendlyName} (Airwatch id={device.Id}) in GLPI trashbin (GLPI id={deviceIDTrash}), skipping...") else: logger.error(f"Device {device.FriendlyName} (Airwatch id={device.Id}) not found in GLPI.") # Suppression du verrou os.remove(lockFile) exit(0)