From 9a21cd49c7f724aae92af9d3818511f89a8d7709 Mon Sep 17 00:00:00 2001 From: Dorian Zedler Date: Sat, 15 Nov 2025 21:56:16 +0100 Subject: [PATCH] Chore: refactor string formatting --- .../linuxmusterLinuxclient7/computer.py | 2 +- .../linuxmusterLinuxclient7/constants.py | 4 +-- .../linuxmusterLinuxclient7/environment.py | 6 ++--- .../linuxmusterLinuxclient7/fileHelper.py | 6 ++--- .../linuxmusterLinuxclient7/gpo.py | 26 +++++++++---------- .../linuxmusterLinuxclient7/hooks.py | 24 ++++++++--------- .../linuxmusterLinuxclient7/imageHelper.py | 16 ++++++------ .../linuxmusterLinuxclient7/keytab.py | 10 +++---- .../linuxmusterLinuxclient7/ldapHelper.py | 8 +++--- .../localUserHelper.py | 2 +- .../linuxmusterLinuxclient7/printers.py | 18 ++++++------- .../linuxmusterLinuxclient7/realm.py | 8 +++--- .../linuxmusterLinuxclient7/shares.py | 26 +++++++++---------- .../tests/test_hooks.py | 2 +- .../tests/test_printers.py | 2 +- .../tests/test_realm.py | 4 +-- .../linuxmusterLinuxclient7/user.py | 2 +- .../scripts/onLoginLogoutAsRoot | 2 +- 18 files changed, 84 insertions(+), 84 deletions(-) diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/computer.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/computer.py index 701ab81..dd71347 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/computer.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/computer.py @@ -26,7 +26,7 @@ def readAttributes(): :return: Tuple (success, dict of attributes) :rtype: tuple """ - return ldapHelper.searchOne("(sAMAccountName={}$)".format(hostname())) + return ldapHelper.searchOne(f"(sAMAccountName={hostname()}$)") def isInGroup(groupName): """ diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/constants.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/constants.py index 8ef7bfe..f2dd633 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/constants.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/constants.py @@ -35,12 +35,12 @@ "/usr/sbin/linuxmuster-client-adsso", "/usr/sbin/linuxmuster-client-adsso-print-logs", "/etc/systemd/system/linuxmuster-client-adsso.service", - "{}/.config/autostart/linuxmuster-client-adsso-autostart.desktop".format(userTemplateDir), + f"{userTemplateDir}/.config/autostart/linuxmuster-client-adsso-autostart.desktop", "/etc/cups/client.conf", "/usr/share/linuxmuster-linuxclient7/templates/linuxmuster-client-adsso.service", "/usr/share/linuxmuster-linuxclient7/templates/linuxmuster-client-adsso-autostart.desktop", "/etc/security/pam_mount.conf.xml", - "{}/pam_mount.conf.xml".format(configFileTemplateDir) + f"{configFileTemplateDir}/pam_mount.conf.xml" ] obsoleteDirectories = [ diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/environment.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/environment.py index 06ea20d..0ed8366 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/environment.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/environment.py @@ -10,7 +10,7 @@ def export(keyValuePair): :return: True or False :rtype: bool """ - logging.debug("Saving export '{}' to tmp file".format(keyValuePair)) + logging.debug(f"Saving export '{keyValuePair}' to tmp file") envList = keyValuePair.split("=", 1) if len(envList) == 2: @@ -27,7 +27,7 @@ def unset(key): :return: True or False :rtype: bool """ - logging.debug("Saving unset '{}' to tmp file".format(key)) + logging.debug(f"Saving unset '{key}' to tmp file") return _appendToTmpEnvFile("unset", key) # -------------------- @@ -53,7 +53,7 @@ def _appendToTmpEnvFile(mode, keyValuePair): try: with open(tmpEnvironmentFilePath, fileOpenMode) as tmpEnvironmentFile: - tmpEnvironmentFile.write("\n{0} '{1}'".format(mode, keyValuePair)) + tmpEnvironmentFile.write(f"\n{mode} '{keyValuePair}'") return True except Exception as e: logging.exception(e) diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/fileHelper.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/fileHelper.py index 3fccd1f..993a86e 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/fileHelper.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/fileHelper.py @@ -81,8 +81,8 @@ def deleteFilesWithExtension(directory, extension): for file in existingFiles: if file.endswith(extension): - logging.info("* Deleting {}".format(file)) - if not deleteFile("{}/{}".format(directory, file)): + logging.info(f"* Deleting {file}") + if not deleteFile(f"{directory}/{file}"): logging.error("Failed!") return False @@ -121,7 +121,7 @@ def deleteAllInDirectory(directory): existingFiles=os.listdir(directory) for file in existingFiles: - fullFilePath = "{}/{}".format(directory, file) + fullFilePath = f"{directory}/{file}" if os.path.isdir(fullFilePath): rc = deleteDirectory(fullFilePath) else: diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/gpo.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/gpo.py index d3d1984..1a845b2 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/gpo.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/gpo.py @@ -56,7 +56,7 @@ def _findApplicablePolicies(): """ Do this later! # 1. Domain - rc, domainAdObject = ldapHelper.searchOne("(distinguishedName={})".format(ldapHelper.baseDn())) + rc, domainAdObject = ldapHelper.searchOne(f"(distinguishedName={ldapHelper.baseDn()})") if not rc: return False, None @@ -64,7 +64,7 @@ def _findApplicablePolicies(): policyDNs.extend(_parseGplinkSring(domainAdObject["gPLink"])) # 2. OU policies from top to bottom - rc, userAdObject = ldapHelper.searchOne("(sAMAccountName={})".format(user.username())) + rc, userAdObject = ldapHelper.searchOne(f"(sAMAccountName={user.username()})") if not rc: return False, None @@ -77,10 +77,10 @@ def _findApplicablePolicies(): if not rc: return False, None - policyName = "sophomorix:school:{}".format(schoolName) + policyName = f"sophomorix:school:{schoolName}" # find policy - rc, policyAdObject = ldapHelper.searchOne("(displayName={})".format(policyName)) + rc, policyAdObject = ldapHelper.searchOne(f"(displayName={policyName})") if not rc: return False, None @@ -89,7 +89,7 @@ def _findApplicablePolicies(): return True, policyDnList def _parsePolicy(policyDn): - logging.info("=== Parsing policy [{0};{1}] ===".format(policyDn[0], policyDn[1])) + logging.info(f"=== Parsing policy [{policyDn[0]};{policyDn[1]}] ===") """ (not needed because it's currently hardcoded) # Check if the policy is disabled @@ -99,7 +99,7 @@ def _parsePolicy(policyDn): """ # Find policy in AD - rc, policyAdObject = ldapHelper.searchOne("(distinguishedName={})".format(policyDn[0])) + rc, policyAdObject = ldapHelper.searchOne(f"(distinguishedName={policyDn[0]})") if not rc: logging.error("===> Could not find poilcy in AD! ===") return False @@ -120,7 +120,7 @@ def _parsePolicy(policyDn): logging.exception(e) return False - logging.info("===> Parsed policy [{0};{1}] ===".format(policyDn[0], policyDn[1])) + logging.info(f"===> Parsed policy [{policyDn[0]};{policyDn[1]}] ===") return allSuccessfull def _parseXmlFilters(filtersXmlNode): @@ -153,13 +153,13 @@ def _processFilters(policies): else: filtersPassed = True for filter in policy["filters"]: - logging.debug("Testing filter: {}".format(filter)) + logging.debug(f"Testing filter: {filter}") if filter["bool"] == "AND": filtersPassed = filtersPassed and _processFilter(filter) elif filter["bool"] == "OR": filtersPassed = filtersPassed or _processFilter(filter) else: - logging.warning("Unknown boolean operation: {}! Assuming condition is false.".format(filter["bool"])) + logging.warning(f"Unknown boolean operation: {filter['bool']}! Assuming condition is false.") filtersPassed = False if filtersPassed: @@ -192,7 +192,7 @@ def _parseXmlPolicy(policyFile): def _processDrivesPolicy(policyBasepath): logging.info("== Parsing a drive policy! ==") - policyFile = "{}/User/Preferences/Drives/Drives.xml".format(policyBasepath) + policyFile = f"{policyBasepath}/User/Preferences/Drives/Drives.xml" shareList = [] rc, tree = _parseXmlPolicy(policyFile) @@ -235,7 +235,7 @@ def _processDrivesPolicy(policyBasepath): logging.info("Found shares:") for drive in shareList: - logging.info("* {:15}| {:5}| {:40}| {:5}".format(drive["label"], drive["letter"], drive["path"], drive["useLetter"])) + logging.info(f"* {drive['label']:15}| {drive['letter']:5}| {drive['path']:40}| {drive['useLetter']:5}") for drive in shareList: if drive["useLetter"] == "1": @@ -252,7 +252,7 @@ def _processDrivesPolicy(policyBasepath): def _processPrintersPolicy(policyBasepath): logging.info("== Parsing a printer policy! ==") - policyFile = "{}/User/Preferences/Printers/Printers.xml".format(policyBasepath) + policyFile = f"{policyBasepath}/User/Preferences/Printers/Printers.xml" printerList = [] # test rc, tree = _parseXmlPolicy(policyFile) @@ -300,7 +300,7 @@ def _processPrintersPolicy(policyBasepath): logging.info("Found printers:") for printer in printerList: - logging.info("* {0}\t\t| {1}\t| {2}".format(printer["name"], printer["path"], printer["filters"])) + logging.info(f"* {printer['name']}\t\t| {printer['path']}\t| {printer['filters']}") printers.installPrinter(printer["path"], printer["name"]) logging.info("==> Successfully parsed a printer policy! ==") diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/hooks.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/hooks.py index 9e9ea3f..a655141 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/hooks.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/hooks.py @@ -51,13 +51,13 @@ def runLocalHook(hookType): :type hookType: hooks.Type """ hookDir = _getLocalHookDir(hookType) - logging.info("=== Running local hook on{0} in {1} ===".format(hookType.name, hookDir)) + logging.info(f"=== Running local hook on{hookType.name} in {hookDir} ===") if os.path.exists(hookDir): _prepareEnvironment() for fileName in sorted(os.listdir(hookDir)): filePath = hookDir + "/" + fileName _runHookScript(filePath) - logging.info("===> Finished running local hook on{0} ===".format(hookType.name)) + logging.info(f"===> Finished running local hook on{hookType.name} ===") def runRemoteHook(hookType): @@ -67,7 +67,7 @@ def runRemoteHook(hookType): :param hookType: The type of hook to run :type hookType: hooks.Type """ - logging.info("=== Running remote hook on{0} ===".format(hookType.name)) + logging.info(f"=== Running remote hook on{hookType.name} ===") rc, hookScripts = _getRemoteHookScripts(hookType) if rc: @@ -75,7 +75,7 @@ def runRemoteHook(hookType): _runHookScript(hookScripts[0]) _runHookScript(hookScripts[1]) - logging.info("===> Finished running remote hook on{0} ===".format(hookType.name)) + logging.info(f"===> Finished running remote hook on{hookType.name} ===") def runHook(hookType): """ @@ -95,7 +95,7 @@ def getLocalHookScript(hookType): :return: The path :rtype: str """ - return "{0}/on{1}".format(constants.scriptDir,hookType.name) + return f"{constants.scriptDir}/on{hookType.name}" def shouldHooksBeExecuted(overrideUsername=None): """Check if hooks should be executed @@ -120,7 +120,7 @@ def shouldHooksBeExecuted(overrideUsername=None): overrideUsername = user.username() if not user.isUserInAD(overrideUsername): - logging.info("==== {0} is not an AD user, exiting ====".format(user.username())) + logging.info(f"==== {overrideUsername} is not an AD user, exiting ====") return False return True @@ -148,7 +148,7 @@ def _prepareEnvironment(): _writeEnvironment(environment) def _getLocalHookDir(hookType): - return "{0}/on{1}.d".format(constants.etcBaseDir,hookType.name) + return f"{constants.etcBaseDir}/on{hookType.name}.d" def _getRemoteHookScripts(hookType): if not hookType in remoteScriptNames: @@ -184,7 +184,7 @@ def _getRemoteHookScripts(hookType): logging.error("Could not execute server hook {} because the sysvol could not be mounted!\n") return False, None - hookScriptPathTemplate = "{0}/{1}/scripts/{2}/{3}/linux/{4}".format(sysvolPath, domain, school, "{}", scriptName) + hookScriptPathTemplate = f"{sysvolPath}/{domain}/scripts/{school}/{{}}/linux/{scriptName}" return True, [hookScriptPathTemplate.format("lmn"), hookScriptPathTemplate.format("custom")] @@ -202,17 +202,17 @@ def _dictsToEnv(dictsAndPrefixes): def _runHookScript(filePath): if not os.path.isfile(filePath): - logging.warning("* File {0} should be executed as hook but does not exist!".format(filePath)) + logging.warning(f"* File {filePath} should be executed as hook but does not exist!") return if not os.access(filePath, os.X_OK): - logging.warning("* File {0} is in hook dir but not executable!".format(filePath)) + logging.warning(f"* File {filePath} is in hook dir but not executable!") return - logging.info("== Executing script {0} ==".format(filePath)) + logging.info(f"== Executing script {filePath} ==") result = subprocess.call([filePath]) - logging.info("==> Script {0} finished with exit code {1} ==".format(filePath, result)) + logging.info(f"==> Script {filePath} finished with exit code {result} ==") def _writeEnvironment(environment): for key in environment: diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/imageHelper.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/imageHelper.py index a7a6c66..b8c176b 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/imageHelper.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/imageHelper.py @@ -54,7 +54,7 @@ def prepareForImage(unattended=False): def _askStep(step, printPlaceholder=True): if printPlaceholder: print() - response = input("Do you want to {}? (y/n): ".format(step)) + response = input(f"Do you want to {step}? (y/n): ") result = response in ["y", "Y", "j", "J"] if result: print() @@ -114,7 +114,7 @@ def _checkLoggedInUsers(): for loggedInUser in loggedInUsers: if user.isUserInAD(loggedInUser): - logging.error("User {} is still logged in, please log out first! Aborting!".format(loggedInUser)) + logging.error(f"User {loggedInUser} is still logged in, please log out first! Aborting!") return False return True @@ -169,12 +169,12 @@ def _clearUserHomes(unattended=False): logging.info("Deleting all user homes now!") for userHome in userHomes: if not user.isUserInAD(userHome): - logging.info("* {} [SKIPPED]".format(userHome)) + logging.info(f"* {userHome} [SKIPPED]") continue - logging.info("* {}".format(userHome)) + logging.info(f"* {userHome}") try: - shutil.rmtree("/home/{}".format(userHome)) + shutil.rmtree(f"/home/{userHome}") except Exception as e: logging.error("* FAILED!") logging.exception(e) @@ -188,9 +188,9 @@ def _clearUserHomes(unattended=False): return True def _clearPrinters(unattended=False): - print("\nCAUTION! This will delete all printers of {}!".format(constants.templateUser)) + print(f"\nCAUTION! This will delete all printers of {constants.templateUser}!") print("This makes sure that local printers do not conflict with remote printers defined by GPOs.") - if not unattended and not _askStep("remove all local printers of {}".format(constants.templateUser), False): + if not unattended and not _askStep(f"remove all local printers of {constants.templateUser}", False): return True if not printers.uninstallAllPrintersOfUser(constants.templateUser): @@ -213,7 +213,7 @@ def _emptyTrash(unattended=False): if not unattended and not _askStep("clear the Trash of linuxadmin"): return True - if not fileHelper.deleteAllInDirectory("/home/{}/.local/share/Trash".format(constants.templateUser)): + if not fileHelper.deleteAllInDirectory(f"/home/{constants.templateUser}/.local/share/Trash"): return False return True \ No newline at end of file diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/keytab.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/keytab.py index 1e6dbf0..0675907 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/keytab.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/keytab.py @@ -9,13 +9,13 @@ def patchKeytab(): :rtype: bool """ krb5KeytabFilePath = "/etc/krb5.keytab" - logging.info("Patching {}".format(krb5KeytabFilePath)) + logging.info(f"Patching {krb5KeytabFilePath}") krb5KeytabUtil = Krb5KeytabUtil(krb5KeytabFilePath) try: krb5KeytabUtil.read() except: - logging.error("Error reading {}".format(krb5KeytabFilePath)) + logging.error(f"Error reading {krb5KeytabFilePath}") return False for entry in krb5KeytabUtil.keytab.entries: @@ -40,15 +40,15 @@ def patchKeytab(): entry.principal.components[1].data = newData - logging.debug("{} was changed to {}".format(oldData, entry.principal.components[-1].data)) + logging.debug(f"{oldData} was changed to {entry.principal.components[-1].data}") - logging.info("Trying to overwrite {}".format(krb5KeytabFilePath)) + logging.info(f"Trying to overwrite {krb5KeytabFilePath}") try: result = krb5KeytabUtil.write() except: result = False if not result: - logging.error("Error overwriting {}".format(krb5KeytabFilePath)) + logging.error(f"Error overwriting {krb5KeytabFilePath}") return result diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/ldapHelper.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/ldapHelper.py index c9856f4..9d8c124 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/ldapHelper.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/ldapHelper.py @@ -16,7 +16,7 @@ def serverUrl(): return False, None serverHostname = networkConfig["serverHostname"] - return 'ldap://{0}'.format(serverHostname) + return f"ldap://{serverHostname}" def baseDn(): """ @@ -108,9 +108,9 @@ def isObjectInGroup(objectDn, groupName): :return: True if it is a member, False otherwise :rtype: bool """ - logging.debug("= Testing if object {0} is a member of group {1} =".format(objectDn, groupName)) - rc, groupAdObject = searchOne("(&(member:1.2.840.113556.1.4.1941:={0})(sAMAccountName={1}))".format(objectDn, groupName)) - logging.debug("=> Result: {} =".format(rc)) + logging.debug(f"= Testing if object {objectDn} is a member of group {groupName} =") + rc, groupAdObject = searchOne(f"(&(member:1.2.840.113556.1.4.1941:={objectDn})(sAMAccountName={groupName}))") + logging.debug(f"=> Result: {rc} =") return rc # -------------------- diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/localUserHelper.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/localUserHelper.py index f1adcc8..0ffa627 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/localUserHelper.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/localUserHelper.py @@ -15,5 +15,5 @@ def getGroupsOfLocalUser(username): stringList=[x.decode('utf-8') for x in groups.split(b"\x00")] return True, stringList except Exception as e: - logging.warning("Exception when querying groups of user {}, it probaply does not exist".format(username)) + logging.warning(f"Exception when querying groups of user {username}, it probably does not exist") return False, None \ No newline at end of file diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/printers.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/printers.py index b1f3c6b..036b656 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/printers.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/printers.py @@ -35,7 +35,7 @@ def uninstallAllPrintersOfUser(username): :return: True on success, False otherwise :rtype: bool """ - logging.info("Uninstalling all printers of {}".format(username)) + logging.info(f"Uninstalling all printers of {username}") installedPrinters = _getInstalledPrintersOfUser(username) for installedPrinter in installedPrinters: @@ -59,10 +59,10 @@ def translateSambaToIpp(networkPath): result = pattern.findall(networkPath) if len(result) != 1 or len(result[0]) != 2: - logging.error("Cannot convert printer network path from samba to ipp, as it is invalid: {}".format(networkPath)) + logging.error(f"Cannot convert printer network path from samba to ipp, as it is invalid: {networkPath}") return False, None - ippNetworkPath = "ipp://{0}/printers/{1}".format(result[0][0], result[0][1]) + ippNetworkPath = f"ipp://{result[0][0]}/printers/{result[0][1]}" return True, ippNetworkPath # -------------------- @@ -70,9 +70,9 @@ def translateSambaToIpp(networkPath): # -------------------- def _installPrinter(username, networkPath, name): - logging.info("Install Printer {0} on {1}".format(name, networkPath)) + logging.info(f"Install Printer {name} on {networkPath}") installCommand = ["timeout", "10", "lpadmin", "-p", name, "-E", "-v", networkPath, "-m", "everywhere", "-u", f"allow:{username}"] - logging.debug("* running '{}'".format(" ".join(installCommand))) + logging.debug(f"* running '{' '.join(installCommand)}'") p = subprocess.call(installCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p == 0: logging.debug("* Success Install Printer!") @@ -88,8 +88,8 @@ def _installPrinterWithoutRoot(networkPath, name): def _getInstalledPrintersOfUser(username): logging.info(f"Getting installed printers of {username}") - command = f"lpstat -U {username} -p" - #logging.debug("running '{}'".format(command)) + command = ["lpstat", "-U", username, "-p"] + #logging.debug(f"running '{command}'") result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) @@ -112,9 +112,9 @@ def _getInstalledPrintersOfUser(username): return installedPrinters def _uninstallPrinter(name): - logging.info("Uninstall Printer {}".format(name)) + logging.info(f"Uninstall Printer {name}") uninstallCommand = ["timeout", "10", "lpadmin", "-x", name] - logging.debug("* running '{}'".format(" ".join(uninstallCommand))) + logging.debug(f"* running '{' '.join(uninstallCommand)}'") p = subprocess.call(uninstallCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p == 0: logging.debug("* Success Uninstall Printer!") diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/realm.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/realm.py index eb77f62..ae1af0c 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/realm.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/realm.py @@ -48,7 +48,7 @@ def leaveAll(): return False for joinedDomain in joinedDomains: - logging.info("* {}".format(joinedDomain)) + logging.info(f"* {joinedDomain}") if not leave(joinedDomain): logging.error("-> Failed! Aborting!") return False @@ -115,7 +115,7 @@ def getJoinedDomains(): :return: Tuple (success, list of joined domians) :rtype: tuple """ - result = subprocess.run("realm list --name-only", stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) + result = subprocess.run(["realm", "list", "--name-only"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) if result.returncode != 0: logging.error("Failed to read domain joins!") @@ -155,10 +155,10 @@ def getDomainConfig(domain): :return: Tuple (success, dict with domain config) :rtype: tuple """ - result = subprocess.run("adcli info '{}'".format(domain), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) + result = subprocess.run(["adcli", "info", domain], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True) if result.returncode != 0: - logging.error("Failed to get details of domain {}!".format(domain)) + logging.error(f"Failed to get details of domain {domain}!") return False, None rawConfig = _readConfigFromString(result.stdout) diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/shares.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/shares.py index 2528288..2759759 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/shares.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/shares.py @@ -60,7 +60,7 @@ def getMountpointOfRemotePath(remoteFilePath, hiddenShare = False, username = No match = pattern.search(remoteFilePath) if match is None: - logging.error("Cannot get local file path of {} beacuse it is not a valid path!".format(remoteFilePath)) + logging.error(f"Cannot get local file path of {remoteFilePath} beacuse it is not a valid path!") return False, None shareBasepath = match.group(0) @@ -85,25 +85,25 @@ def unmountAllSharesOfUser(username): :return: True or False :rtype: bool """ - logging.info("=== Trying to unmount all shares of user {0} ===".format(username)) + logging.info(f"=== Trying to unmount all shares of user {username} ===") for basedir in [constants.shareMountBasepath, constants.hiddenShareMountBasepath]: shareMountBasedir = basedir.format(username) try: mountedShares = os.listdir(shareMountBasedir) except FileNotFoundError: - logging.info("Mount basedir {} does not exist -> nothing to unmount".format(shareMountBasedir)) + logging.info(f"Mount basedir {shareMountBasedir} does not exist -> nothing to unmount") continue for share in mountedShares: - _unmountShare("{0}/{1}".format(shareMountBasedir, share)) + _unmountShare(f"{shareMountBasedir}/{share}") if len(os.listdir(shareMountBasedir)) > 0: - logging.warning("* Mount basedir {} is not empty so not removed!".format(shareMountBasedir)) + logging.warning(f"Mount basedir {shareMountBasedir} is not empty so not removed!") return False else: # Delete the directory - logging.info("Deleting {0}...".format(shareMountBasedir)) + logging.info(f"Deleting {shareMountBasedir}...") try: os.rmdir(shareMountBasedir) except Exception as e: @@ -111,7 +111,7 @@ def unmountAllSharesOfUser(username): logging.exception(e) return False - logging.info("===> Finished unmounting all shares of user {0} ===".format(username)) + logging.info(f"===> Finished unmounting all shares of user {username} ===") return True def getLocalSysvolPath(): @@ -177,7 +177,7 @@ def _mountShare(username, networkPath, shareName, hiddenShare, useCruidOfExecuti else: logging.warning("* The target directory already exists, proceeding anyway!") - logging.debug("* Executing '{}' ".format(" ".join(mountCommand))) + logging.debug(f"* Executing '{' '.join(mountCommand)}' ") logging.debug("* Trying to mount...") if not subprocess.call(mountCommand, stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0: logging.fatal(f"* Error mounting share {networkPath} to {mountpoint}!\n") @@ -204,7 +204,7 @@ def _unmountShare(mountpoint): logging.warning(f"* Could not unmount {mountpoint}, it does not exist.") # Try to unmount share - logging.info("* Trying to unmount {0}...".format(mountpoint)) + logging.info(f"* Trying to unmount {mountpoint}...") if not subprocess.call(["umount", mountpoint]) == 0: logging.warning("* Failed!") if _directoryIsMountpoint(mountpoint): @@ -215,11 +215,11 @@ def _unmountShare(mountpoint): # check if the mountpoint is empty if len(os.listdir(mountpoint)) > 0: - logging.warning("* mountpoint {} is not empty so not removed!".format(mountpoint)) + logging.warning(f"* mountpoint {mountpoint} is not empty so not removed!") return # Delete the directory - logging.info("* Deleting {0}...".format(mountpoint)) + logging.info(f"* Deleting {mountpoint}...") try: os.rmdir(mountpoint) except Exception as e: @@ -253,9 +253,9 @@ def _getShareMountpoint(networkPath, username, hidden, shareName = None): shareName = _getDefaultShareName(networkPath, shareName) if hidden: - return "{0}/{1}".format(constants.hiddenShareMountBasepath.format(username), shareName) + return f"{constants.hiddenShareMountBasepath.format(username)}/{shareName}" else: - return "{0}/{1}".format(constants.shareMountBasepath.format(username), shareName) + return f"{constants.shareMountBasepath.format(username)}/{shareName}" def _directoryIsMountpoint(dir): return subprocess.call(["mountpoint", "-q", dir]) == 0 diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_hooks.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_hooks.py index 4aadb3e..ce0bd9c 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_hooks.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_hooks.py @@ -166,7 +166,7 @@ def _createRemoteHookScripts(hook, sysvolPath="/tmp/sysvol", domain="linuxmuster if not hook in hooks.remoteScriptNames: return [] - hookScriptPathTemplate = "{0}/{1}/scripts/{2}/{3}/linux/{4}".format(sysvolPath, domain, school, "{}", hooks.remoteScriptNames[hook]) + hookScriptPathTemplate = f"{sysvolPath}/{domain}/scripts/{school}/{{}}/linux/{hooks.remoteScriptNames[hook]}" createdFiles = [] for hookKind in ["lmn", "custom"]: diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_printers.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_printers.py index 6108905..5a86cee 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_printers.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_printers.py @@ -57,7 +57,7 @@ def test_uninstallAllPrintersOfUser(mockSubprocessRun, mockSubprocessCall): mockSubprocessRun.return_value = CompletedProcess(args=["lpstat", "-U", "user1", "-p"], returncode=0, stdout=lpstatStdout) assert printers.uninstallAllPrintersOfUser("user1") - assert _getCallsTo(mockSubprocessRun, "lpstat")[-1] == "lpstat -U user1 -p" + assert _getCallsTo(mockSubprocessRun, "lpstat")[-1] == ['lpstat', '-U', 'user1', '-p'] assert _getCallsTo(mockSubprocessCall, "timeout") == [["timeout", "10", "lpadmin", "-x", "printer1"], ["timeout", "10", "lpadmin", "-x", "printer2"]] mockSubprocessRun.return_value = CompletedProcess(args=["lpstat", "-U", "user1", "-p"], returncode=1) diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_realm.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_realm.py index 067ecb5..979876d 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_realm.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/tests/test_realm.py @@ -35,7 +35,7 @@ def test_getJoinedDomains(mockSubprocessRun): assert realm.getJoinedDomains() == (True, ["linuxmuster.lan", "windowsmuster.lan"]) calls = _getCallsTo(mockSubprocessRun, "realm") assert len(calls) == 1 - assert "realm list --name-only" in calls + assert ['realm', 'list', '--name-only'] in calls mockSubprocessRun.return_value = CompletedProcess(args=["realm", "list", "--name-only"], returncode=1, stdout="") assert realm.getJoinedDomains() == (False, None) @@ -140,7 +140,7 @@ def test_getDomainConfig(mockSubprocessRun): assert realm.getDomainConfig("linuxmuster.lan") == (True, {"domain-controller": "server.linuxmuster.lan", "domain-name": "linuxmuster.lan"}) calls = _getCallsTo(mockSubprocessRun, "adcli") assert len(calls) == 1 - assert "adcli info 'linuxmuster.lan'" in calls + assert ['adcli', 'info', 'linuxmuster.lan'] in calls mockSubprocessRun.return_value = CompletedProcess(args=["adcli", "info", "linuxmuster.lan"], returncode=1, stdout="") assert realm.getDomainConfig("linuxmuster.lan") == (False, None) diff --git a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/user.py b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/user.py index e34bafd..6ed989b 100644 --- a/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/user.py +++ b/usr/lib/python3/dist-packages/linuxmusterLinuxclient7/user.py @@ -90,7 +90,7 @@ def isInGroup(groupName): def cleanTemplateUserGtkBookmarks(): """Remove gtk bookmarks of the template user from the current users `~/.config/gtk-3.0/bookmarks` file. """ - logging.info("Cleaning {} gtk bookmarks".format(constants.templateUser)) + logging.info(f"Cleaning {constants.templateUser} gtk bookmarks") gtkBookmarksFile = constants.gtkBookmarksFile.format(user.username()) if not os.path.isfile(gtkBookmarksFile): logging.warning("Gtk bookmarks file not found, skipping!") diff --git a/usr/share/linuxmuster-linuxclient7/scripts/onLoginLogoutAsRoot b/usr/share/linuxmuster-linuxclient7/scripts/onLoginLogoutAsRoot index 301d520..3258c0a 100755 --- a/usr/share/linuxmuster-linuxclient7/scripts/onLoginLogoutAsRoot +++ b/usr/share/linuxmuster-linuxclient7/scripts/onLoginLogoutAsRoot @@ -13,7 +13,7 @@ try: pamType = os.getenv("PAM_TYPE") pamUser = os.getenv("PAM_USER") #PAM_RHOST, PAM_RUSER, PAM_SERVICE, PAM_TTY, PAM_USER and PAM_TYPE - logging.info("====== onLoginLogoutAsRoot started with PAM_TYPE={0} PAM_RHOST={1} PAM_RUSER={2} PAM_SERVICE={3} PAM_TTY={4} PAM_USER={5} ======".format(pamType, os.getenv("PAM_RHOST"), os.getenv("PAM_RUSER"), os.getenv("PAM_SERVICE"), os.getenv("PAM_TTY"), pamUser)) + logging.info(f"====== onLoginLogoutAsRoot started with PAM_TYPE={pamType} PAM_RHOST={os.getenv('PAM_RHOST')} PAM_RUSER={os.getenv('PAM_RUSER')} PAM_SERVICE={os.getenv('PAM_SERVICE')} PAM_TTY={os.getenv('PAM_TTY')} PAM_USER={pamUser} ======") # check if whe should execute if not hooks.shouldHooksBeExecuted(pamUser):