117 lines
4.6 KiB
Python
117 lines
4.6 KiB
Python
import msal
|
|
import requests
|
|
import pandas as pd
|
|
from datetime import datetime
|
|
|
|
# Konfigurationsvariablen
|
|
client_id = '90571c9b-d407-4d2a-aadd-4a523ff85296'
|
|
client_secret = 'ryp8Q~qr6LBOUL2G333a.mf-vg5V..ONl7qJTdza'
|
|
tenant_id = '9e449aaa-285c-4572-a132-58db027026d0'
|
|
api_server_endpoint = "http://api.stines.de:8001/office/post"
|
|
# headers = 'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'
|
|
|
|
# Die URL für das Token
|
|
authority = f'https://login.microsoftonline.com/{tenant_id}'
|
|
|
|
# Der Scope für die Microsoft Graph API
|
|
scope = ['https://graph.microsoft.com/.default']
|
|
|
|
# MSAL-Instanz erstellen
|
|
app = msal.ConfidentialClientApplication(
|
|
client_id,
|
|
authority=authority,
|
|
client_credential=client_secret,
|
|
)
|
|
|
|
# Token erhalten
|
|
result = None
|
|
result = app.acquire_token_silent(scope, account=None)
|
|
|
|
if not result:
|
|
print("Kein Caching vorhanden, holen Sie ein neues Token.")
|
|
result = app.acquire_token_for_client(scopes=scope)
|
|
print(result)
|
|
|
|
if "access_token" in result:
|
|
# Token erfolgreich erhalten
|
|
access_token = result['access_token']
|
|
|
|
print(access_token)
|
|
|
|
# API-Endpunkt für aktive Office-Pakete
|
|
endpoint = "https://graph.microsoft.com/v1.0/users?$select=userPrincipalName,assignedLicenses,signInActivity"
|
|
|
|
|
|
headers = {
|
|
'Authorization': f'Bearer {access_token}',
|
|
'Content-Type': 'application/json'
|
|
}
|
|
|
|
response = requests.get(endpoint, headers=headers)
|
|
|
|
if response.status_code == 200:
|
|
# Die Antwort als JSON behandeln
|
|
data = response.json()
|
|
|
|
# Extrahieren der Benutzerdaten aus dem JSON
|
|
users = data.get('value', [])
|
|
|
|
# Die `skuId` und `lastNonInteractiveSignInDateTime` extrahieren und hinzufügen
|
|
user_list = []
|
|
for user in users:
|
|
if 'assignedLicenses' in user:
|
|
for license in user['assignedLicenses']:
|
|
if 'skuId' in license:
|
|
user_copy = user.copy()
|
|
user_copy['skuId'] = license['skuId']
|
|
if user_copy.get('signInActivity'):
|
|
sign_in_time = user_copy['signInActivity'].get('lastNonInteractiveSignInDateTime')
|
|
if sign_in_time:
|
|
user_copy['lastNonInteractiveSignInDateTime'] = datetime.strptime(sign_in_time,'%Y-%m-%dT%H:%M:%SZ').strftime('%Y-%m-%d %H:%M:%S')
|
|
else:
|
|
user_copy['lastNonInteractiveSignInDateTime'] = None
|
|
else:
|
|
user_copy['lastNonInteractiveSignInDateTime'] = None
|
|
user_list.append(user_copy)
|
|
|
|
# Filtern der Benutzer, die eine `skuId` haben
|
|
users_with_skuId = [user for user in user_list if user['skuId']]
|
|
|
|
# Konvertieren der Benutzerdaten in ein DataFrame
|
|
df = pd.DataFrame(users_with_skuId)
|
|
|
|
# Pandas Anzeigeoptionen anpassen
|
|
pd.set_option('display.max_columns', None)
|
|
pd.set_option('display.max_rows', None)
|
|
pd.set_option('display.max_colwidth', None)
|
|
pd.set_option('display.width', 1000)
|
|
|
|
# Alles nach dem @ im "User Principal Name" entfernen
|
|
if 'userPrincipalName' in df.columns:
|
|
df['userPrincipalName'] = df['userPrincipalName'].str.split('@').str[0]
|
|
|
|
# Nur die gewünschten Spalten auswählen und an die API-Server übergeben
|
|
selected_columns = df[["userPrincipalName", "skuId", "lastNonInteractiveSignInDateTime"]]
|
|
reporting_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
|
|
|
for index, row in selected_columns.iterrows():
|
|
payload = {
|
|
"itemkey": row["skuId"],
|
|
"username": row["userPrincipalName"],
|
|
"reportingdate": reporting_date,
|
|
"lastaccess": row["lastNonInteractiveSignInDateTime"]
|
|
}
|
|
api_response = requests.post(api_server_endpoint, json=payload, headers= {'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'})
|
|
if api_response.status_code == 200:
|
|
print(f"Erfolgreich gesendet: {payload}")
|
|
else:
|
|
print(f"Fehler beim Senden von {payload}: {api_response.status_code} - {api_response.text}")
|
|
|
|
else:
|
|
print(f"Fehler beim Abrufen der Daten: {response.status_code}")
|
|
print(f"Antwort: {response.text}")
|
|
else:
|
|
print("Fehler beim Abrufen des Tokens")
|
|
print(result.get("error"))
|
|
print(result.get("error_description"))
|
|
print(result.get("correlation_id")) |