import subprocess import csv from datetime import datetime from Controller import create_service import requests import socket import time import random # create_service.addservice("REPORTS-EX") def request_post(function,variable): url = (f"http://api.stines.de:8001/{function}") response = requests.post(url,json = variable,headers={'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'}) return response def request_get(function,variable): url = (f"http://api.stines.de:8001/{function}") response = requests.get(url,headers={'access_token':'^YWUbG7yX*V!tV^KBSd*2c&vdN3wV9a2i7f3hfGFMBYFxi6#mMiJGiaA5KEHE%B*miK%qb7rQ67gmcYP@gqmux8'}) return response def exchange(ip,name): exchange_commands = "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn; Get-Mailbox | Select-Object PSComputerName, RunspaceId, PSShowComputerName, Database, UseDatabaseRetentionDefaults, RetainDeletedItemsUntilBackup, IsHierarchyReady, IsHierarchySyncEnabled,RetentionPolicy, ExchangeGuid, AdminDisplayVersion, ExchangeUserAccountControl, IsMailboxEnabled,ProhibitSendQuota, ProhibitSendReceiveQuota, RecoverableItemsQuota, RecoverableItemsWarningQuota,CalendarLoggingQuota, IsResource, IsLinked, IsShared, IsRootPublicFolderMailbox, LinkedMasterAccount, ResetPasswordOnNextLogon,ResourceType, RoomMailboxAccountEnabled, SamAccountName, ServerLegacyDN, UseDatabaseQuotaDefaults,IssueWarningQuota, RulesQuota, UserPrincipalName, RoleAssignmentPolicy, EffectivePublicFolderMailbox, SharingPolicy,ArchiveQuota, ArchiveWarningQuota, DisabledMailboxLocations, CalendarVersionStoreDisabled, AuditEnabled,AuditLogAgeLimit, WhenMailboxCreated, AccountDisabled, Alias, OrganizationalUnit, DisplayName,LegacyExchangeDN, MaxSendSize, MaxReceiveSize, EmailAddressPolicyEnabled, PrimarySmtpAddress,RecipientType, RecipientTypeDetails, WindowsEmailAddress, Identity, IsValid, ExchangeVersion,DistinguishedName, Guid, ObjectCategory, WhenChanged, WhenCreated, WhenChangedUTC, WhenCreatedUTC,OrganizationId, Id, OriginatingServer,CustomAttribute2 | Export-Csv -Path 'exuser.csv' -NoTypeInformation -Encoding UTF8" # PowerShell als Subprozess ausführen process = subprocess.Popen(["powershell", "-Command", exchange_commands], stdout=subprocess.PIPE, shell=True) # Warte auf den Abschluss des PowerShell-Prozesses process.communicate() # CSV-Datei einlesen und Feldnamen auslesen with open("exuser.csv", "r", encoding='utf-8-sig') as file: reader = csv.DictReader(file) fieldnames = reader.fieldnames # Tabelle erstellen, falls sie noch nicht existiert table_name = "Exchange-User" create_table_query = f"CREATE TABLE IF NOT EXISTS `{table_name}` (id INT AUTO_INCREMENT PRIMARY KEY, importdate INT(11), " for field in fieldnames: if "Id" == field: field = "ADUserPath" create_table_query += f"`{field}` TEXT, " create_table_query = create_table_query.rstrip(", ") + ")" create_table_query += " ROW_FORMAT=DYNAMIC" row_length = len(create_table_query) request_post("dbset",{"query":create_table_query, "dbname":name}) with open("exuser.csv", "r", encoding='utf-8-sig') as file: reader = csv.reader(file) next(reader) for row in reader: print(row) if fieldnames[65] == 'Id': fieldnames[65] = "ADUserPath" print(fieldnames[65]) row = [cell if cell.strip() else "-" for cell in row] unix_time = int(datetime.now().timestamp()) row = [unix_time] + row # Führe das Einfüge-Query aus insert_query = f"INSERT INTO `{table_name}` (importdate, `{'`, `'.join(fieldnames)}`) VALUES (%s, {', '.join(['%s'] * len(fieldnames))})" request_post("ex/adduser",{"query":insert_query, "dbname":name, "entry":row}) def get_local_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) local_ip = s.getsockname()[0] s.close() return local_ip except Exception as e: print(f"Fehler beim Abrufen der lokalen IP-Adresse: {e}") return None service_time = f"23:{str(random.randint(1, 59)).zfill(2)}" ## ADD Random Time ip = get_local_ip() exchange(ip,"tnp-Invest-GmbH") while True: current_time = datetime.now().strftime("%H:%M") try: with open ("log.txt","a") as datei: datei.writelines(request_get("gettime",{}).text + "\n") except Exception as e: with open ("log.txt","a") as datei: datei.writelines(f"{current_time}No Connection to Server!" + "\n") if current_time == service_time: ip = get_local_ip() database = request_post("info/getdatabase",{"ip":ip}).text.replace('"',"") exchange(ip,database) with open ("log.txt","a") as datei: datei.writelines(f"{current_time} - Sleep for {22*3600}" + "\n") time.sleep(22*3600) time.sleep(60)