import os import systemd.daemon from typing import List class NFSServerConf: def __init__(self, nfs_srv_folders: List[str] = ["/nfsroot/publicnfs", "/nfsroot/datennfs"], nfs_config_file: str = "/etc/exports", allow_network: str = "192.168.50.0/25"): self._validate_input(nfs_srv_folders) self._validate_input(nfs_config_file) self.nfs_srv_folders = nfs_srv_folders self.nfs_config_file = nfs_config_file self.allow_network = allow_network def _validate_input(self, input_value: str) -> None: if not isinstance(input_value, str): raise ValueError(f"Input muss eine Zeichenkette sein. ({type(input_value).__name__} wurde verwendet.)") if not os.path.exists(input_value): raise ValueError(f"Datei {input_value} existiert nicht.") def mount_serverfolder(self) -> None: # Durchsuche das angegebene Verzeichnis und seine Unterordner nach Dateien und erstelle eine Liste von Dateipfaden server_folder_list = [] for folder in self.nfs_srv_folders: files_in_folder = [os.path.join(folder, file) for file in os.listdir(folder)] server_folder_list.extend(files_in_folder) # Erstelle für jedes Verzeichnis in nfs_srv_folders ein Unit-File im Format .mount in /etc/systemd/system/ for folder in self.nfs_srv_folders: mount_unit_file = f"/etc/systemd/system/{os.path.basename(folder)}.mount" with open(mount_unit_file, "w") as file: file.write("[Unit]\n") file.write(f"Description=Mount {folder}\n") file.write("[Mount]\n") file.write(f"Where={folder}\n") file.write("What=/mnt/nfs\n") # Starte und ermögliche den Dienst für jedes Unit-File systemd.daemon.notify(systemd.daemon.DaemonReload) def nfs_server_conf(self) -> None: # Durchsuche die Konfiguration des NFS-Servers (im Standardfall /etc/exports) nach Verzeichnissen with open(self.nfs_config_file, "r") as file: config_content = file.readlines() # Zähle, wie oft jeder Verzeichnis-Pfad in der Konfiguration vorkommt folder_count = {} for line in config_content: if ":" in line and not line.startswith("#"): folder_path = line.split(":")[0].strip() if folder_path not in folder_count: folder_count[folder_path] = 1 else: folder_count[folder_path] += 1 # Füge für jeden Verzeichnis-Pfad hinzu, der nicht bereits in der Konfiguration vorhanden ist, einen neuen Eintrag in die Konfiguration for folder in self.nfs_srv_folders: if folder not in [line.strip() for line in config_content]: with open(self.nfs_config_file, "a") as file: file.write(f"{folder}({self.allow_network})\n") def start_nfs_server(self) -> None: # Starte und ermögliche den Dienst für den NFS-Server (im Standardfall nfsv4-server.service) systemd.daemon.notify(systemd.daemon.DaemonReload) def main_install(): nfsserverconf = NFSServerConf() nfsserverconf.mount_serverfolder() nfsserverconf.nfs_server_conf() nfsserverconf.start_nfs_server() if __name__ == "__main__": main_install()