From ac6fc7c6bf16f308964d2c6873c6df127cd29457 Mon Sep 17 00:00:00 2001
From: Lyanis SOUIDI <lyanis.souidi@etu.u-pec.fr>
Date: Sat, 21 Dec 2024 00:14:51 +0100
Subject: [PATCH] Add vm/extract_acl.py

---
 vm/extract_acl.py | 68 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 68 insertions(+)
 create mode 100644 vm/extract_acl.py

diff --git a/vm/extract_acl.py b/vm/extract_acl.py
new file mode 100644
index 0000000..b83cdb8
--- /dev/null
+++ b/vm/extract_acl.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+
+import json
+import subprocess
+import sys
+import threading
+
+def extract_acls(vmid_min, vmid_max, output_file, remove_acl=False, append=False):
+    print("Fetching ACLs...")
+
+    if not append:
+        with open(output_file, "w") as f:
+            f.write("")
+
+    result = subprocess.run(
+        ["pveum", "acl", "list", "--output-format=json"],
+        capture_output=True,
+        text=True
+    )
+
+    acls = json.loads(result.stdout)
+
+    def process_acl(acl_entry):
+        path = acl_entry["path"]
+        role = acl_entry["roleid"]
+        user = acl_entry["ugid"]
+
+        if "/vms/" in path:
+            vmid = int(path.split("/vms/")[1])
+            if vmid_min <= vmid <= vmid_max:
+                print(f"Processing VMID: {vmid} (Path: {path}, Role: {role}, User: {user})")
+
+                with open(output_file, "a") as f:
+                    f.write(f"{path} {user} {role}\n")
+
+                if (remove_acl):
+                    subprocess.run(["pveum", "acl", "delete", path, users, "--roles", roles])
+
+    # Process each ACL in background
+    threads = []
+    for acl_entry in acls:
+        thread = threading.Thread(target=process_acl, args=(acl_entry,))
+        thread.start()
+        threads.append(thread)
+
+    # Wait for all threads to finish
+    for thread in threads:
+        thread.join()
+
+    print(f"ACLs extracted and saved to {output_file}")
+
+
+def main():
+    if len(sys.argv) < 4:
+        print("Usage: extract_acls.py <vmid_min> <vmid_max> <output_file> --remove --append")
+        sys.exit(1)
+
+    vmid_min = int(sys.argv[1])
+    vmid_max = int(sys.argv[2])
+    output_file = sys.argv[3]
+    remove_acl = "--remove" in sys.argv
+    append = "--append" in sys.argv
+
+    extract_acls(vmid_min, vmid_max, output_file, remove_acl, append)
+
+
+if __name__ == "__main__":
+    main()
\ No newline at end of file