"""Exchange Online: Konfiguration und Postfach-Einstellungen über Get-Cmdlets (nur lesend). Die Cmdlets laufen über die Admin-REST-Schnittstelle (m365_auth.invoke, nur Get-*). Ausgabe nach exchange/.json, Bericht nach exchange_report.json. Mit --retry-gzip werden Cmdlets nachgeholt, die im Bericht wegen eines gzip-Fehlers fehlgeschlagen sind (früher ein eigenes Nachlauf-Skript).""" import datetime, json, os, sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import m365_auth as auth SIMPLE = [ "Get-OrganizationConfig", "Get-AcceptedDomain", "Get-RemoteDomain", "Get-TransportConfig", "Get-TransportRule", "Get-InboundConnector", "Get-OutboundConnector", "Get-HostedContentFilterPolicy", "Get-HostedContentFilterRule", "Get-HostedConnectionFilterPolicy", "Get-HostedOutboundSpamFilterPolicy", "Get-HostedOutboundSpamFilterRule", "Get-MalwareFilterPolicy", "Get-MalwareFilterRule", "Get-AntiPhishPolicy", "Get-AntiPhishRule", "Get-SafeLinksPolicy", "Get-SafeLinksRule", "Get-SafeAttachmentPolicy", "Get-SafeAttachmentRule", "Get-AtpPolicyForO365", "Get-QuarantinePolicy", "Get-GlobalQuarantinePolicy", "Get-DkimSigningConfig", "Get-MailboxPlan", "Get-CASMailboxPlan", "Get-DynamicDistributionGroup", "Get-UnifiedGroup", "Get-MailContact", "Get-MailUser", "Get-RetentionPolicy", "Get-RetentionPolicyTag", "Get-SharingPolicy", "Get-OwaMailboxPolicy", "Get-MobileDeviceMailboxPolicy", "Get-ActiveSyncDeviceAccessRule", "Get-ActiveSyncOrganizationSettings", "Get-RoleGroup", "Get-ManagementRoleAssignment", "Get-ManagementRole", "Get-AdminAuditLogConfig", "Get-AuthenticationPolicy", "Get-AddressList", "Get-GlobalAddressList", "Get-OfflineAddressBook", "Get-AddressBookPolicy", "Get-JournalRule", "Get-EmailAddressPolicy", "Get-EOPProtectionPolicyRule", "Get-ATPProtectionPolicyRule", "Get-ATPBuiltInProtectionRule", "Get-ExoPhishSimOverrideRule", "Get-PhishSimOverridePolicy", "Get-ApplicationAccessPolicy", "Get-AuthServer", "Get-IntraOrganizationConnector", "Get-OrganizationRelationship", "Get-MessageClassification", "Get-OutlookProtectionRule", "Get-DataClassification", "Get-ReportSubmissionPolicy", "Get-ReportSubmissionRule", "Get-TeamsProtectionPolicy", "Get-TeamsProtectionPolicyRule", "Get-MailboxAuditBypassAssociation", "Get-PartnerApplication", "Get-PolicyTipConfig", "Get-RoleAssignmentPolicy", "Get-ResourceConfig", "Get-ClientAccessRule", "Get-HybridConfiguration", "Get-AvailabilityConfig", "Get-OnPremisesOrganization", "Get-DeliveryAgentConnector", "Get-MalwareFilteringServer", "Get-ServicePrincipal", "Get-ManagementScope", "Get-MigrationEndpoint", "Get-OMEConfiguration", "Get-IRMConfiguration"] # Hinweis: Diese Cmdlets stehen bewusst nicht in der Liste (liefern nichts, brauchen Parameter oder laufen unten einzeln): # Get-MailboxFolderPermission, Get-MobileDevice, Get-SendConnector, Get-Recipient, Get-FeatureConfiguration, Get-Place, Get-SmimeConfig. def main(argv=None): p = auth.make_parser("Back up Exchange Online configuration via Get-* cmdlets (read-only)") p.add_argument("--retry-gzip", action="store_true", help="only repeat cmdlets whose earlier run failed with a gzip error") p.add_argument("--max-mailboxes", type=int, default=0, help="limit per-mailbox cmdlets to N mailboxes (0 = all)") args = p.parse_args(argv) out = args.out os.makedirs(out, exist_ok=True) report_path = os.path.join(out, "exchange_report.json") report = {"start": datetime.datetime.now(datetime.timezone.utc).isoformat(), "cmdlets": {}, "not_possible": {}} log_file = open(os.path.join(out, "exchange.log"), "a") def log(*a): s = " ".join(str(x) for x in a); log_file.write(s + "\n"); log_file.flush(); print(s, flush=True) def save(folder, name, data): os.makedirs(os.path.join(out, folder), exist_ok=True) with open(os.path.join(out, folder, name + ".json"), "w") as f: json.dump(data, f, indent=1, ensure_ascii=False, default=str) def run(folder, cmd, params=None, name=None, host="outlook.office365.com", **kw): name = name or cmd[4:] key = f"{folder}/{name}" try: d = auth.invoke(cmd, params, host=host, **kw) save(folder, name, d); report["cmdlets"][key] = {"cmdlet": cmd, "count": len(d)} log("OK", key, len(d)); return d except Exception as x: m = str(x)[:400] report["cmdlets"][key] = {"cmdlet": cmd, "error": m} if any(t in m.lower() for t in ("not recognized", "couldn't be found", "is not available", "not allowed", "isn't supported", "cmdlet")): report["not_possible"][key] = m log("ERROR", key, m); return None def per_object(folder, cmd, items, key_of, param="Identity", name=None, extra=None): name = name or cmd[4:]; res, errors = {}, {} for it in items: k = key_of(it) try: prm = {param: k}; prm.update(extra or {}) res[k] = auth.invoke(cmd, prm) except Exception as x: errors[k] = str(x)[:300] save(folder, name, {"data": res, "errors": errors}) key = f"{folder}/{name}" report["cmdlets"][key] = {"cmdlet": cmd, "objects_queried": len(items), "count": sum(len(v) for v in res.values()), "error_count": len(errors)} if errors: report["cmdlets"][key]["error_example"] = list(errors.values())[0] log("PER", key, len(items), "->", report["cmdlets"][key]["count"], "errors", len(errors)) return res X = "exchange" if args.retry_gzip: old = json.load(open(report_path)) report.update({k: old[k] for k in ("cmdlets", "not_possible", "start")}) for k, v in list(old["cmdlets"].items()): if "gzip" in v.get("error", ""): report["not_possible"].pop(k, None) run(X, v["cmdlet"], name=k.split("/")[1]) json.dump(report, open(report_path, "w"), indent=1, ensure_ascii=False) return 0 for c in dict.fromkeys(SIMPLE): run(X, c) # Besondere Aufrufe run(X, "Get-TenantAllowBlockListItems", {"ListType": "Sender"}, name="TenantAllowBlockListItems_Sender") for lt in ("Url", "FileHash", "IP"): run(X, "Get-TenantAllowBlockListItems", {"ListType": lt}, name=f"TenantAllowBlockListItems_{lt}") run(X, "Get-TenantAllowBlockListSpoofItems", name="TenantAllowBlockListSpoofItems") run(X, "Get-MobileDevice", name="MobileDevice") run(X, "Get-DistributionGroup", name="DistributionGroup") run(X, "Get-Recipient", name="Recipient") mailboxes = run(X, "Get-Mailbox", {"ResultSize": "Unlimited", "IncludeInactiveMailbox": True}, name="Mailbox") \ or run(X, "Get-Mailbox", name="Mailbox") or [] run(X, "Get-Mailbox", {"ResultSize": "Unlimited", "GroupMailbox": True}, name="Mailbox_GroupMailboxes") run(X, "Get-Mailbox", {"ResultSize": "Unlimited", "Archive": True}, name="Mailbox_WithArchive") run(X, "Get-CASMailbox", {"ResultSize": "Unlimited"}, name="CASMailbox") mailbox_key = lambda m: m.get("ExternalDirectoryObjectId") or m.get("Guid") or m.get("PrimarySmtpAddress") people = [m for m in mailboxes if not m.get("IsInactiveMailbox")] or mailboxes if args.max_mailboxes: people = people[:args.max_mailboxes] per_object(X, "Get-MailboxPermission", people, mailbox_key) per_object(X, "Get-RecipientPermission", people, mailbox_key, param="Identity") per_object(X, "Get-InboxRule", people, mailbox_key, param="Mailbox", extra={"IncludeHidden": True}) per_object(X, "Get-MailboxAutoReplyConfiguration", people, mailbox_key) per_object(X, "Get-MailboxRegionalConfiguration", people, mailbox_key) def load(name): p_ = os.path.join(out, X, name + ".json") return json.load(open(p_)) if os.path.exists(p_) else [] group_key = lambda g: g.get("ExternalDirectoryObjectId") or g.get("Guid") per_object(X, "Get-DistributionGroupMember", load("DistributionGroup"), group_key, name="DistributionGroupMember") per_object(X, "Get-RoleGroupMember", load("RoleGroup"), lambda g: g.get("Name"), name="RoleGroupMember") for lt in ("Members", "Owners"): per_object(X, "Get-UnifiedGroupLinks", load("UnifiedGroup"), group_key, name="UnifiedGroupLinks_" + lt, extra={"LinkType": lt}) json.dump(report, open(report_path, "w"), indent=1, ensure_ascii=False) return 0 if __name__ == "__main__": sys.exit(main())