Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)

# --------------------
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
26 changes: 13 additions & 13 deletions usr/lib/python3/dist-packages/linuxmusterLinuxclient7/gpo.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ 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

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
Expand All @@ -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

Expand All @@ -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
Expand All @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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":
Expand All @@ -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)
Expand Down Expand Up @@ -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! ==")
Expand Down
24 changes: 12 additions & 12 deletions usr/lib/python3/dist-packages/linuxmusterLinuxclient7/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -67,15 +67,15 @@ 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:
_prepareEnvironment()
_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):
"""
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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")]

Expand All @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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):
Expand All @@ -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
10 changes: 5 additions & 5 deletions usr/lib/python3/dist-packages/linuxmusterLinuxclient7/keytab.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def serverUrl():
return False, None

serverHostname = networkConfig["serverHostname"]
return 'ldap://{0}'.format(serverHostname)
return f"ldap://{serverHostname}"

def baseDn():
"""
Expand Down Expand Up @@ -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

# --------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading