diff options
author | Slávek Banko <[email protected]> | 2023-01-19 18:01:26 +0100 |
---|---|---|
committer | Michele Calgaro <[email protected]> | 2023-01-20 13:05:37 +0900 |
commit | 94f5a3f12e1c61aa2f3cde2d7b260c08489336ac (patch) | |
tree | 9062a30a1d81a1a97e9397548e4ec48ae63c18a4 /userconfig/unixauthdb.py | |
parent | b9c0b6996a6da72f93baf50121a1be4a6fa48d2e (diff) | |
download | tde-guidance-94f5a3f12e1c61aa2f3cde2d7b260c08489336ac.tar.gz tde-guidance-94f5a3f12e1c61aa2f3cde2d7b260c08489336ac.zip |
Drop python2 support.
Signed-off-by: Slávek Banko <[email protected]>
Diffstat (limited to 'userconfig/unixauthdb.py')
-rwxr-xr-x | userconfig/unixauthdb.py | 198 |
1 files changed, 99 insertions, 99 deletions
diff --git a/userconfig/unixauthdb.py b/userconfig/unixauthdb.py index 92ffcc8..e2e80c1 100755 --- a/userconfig/unixauthdb.py +++ b/userconfig/unixauthdb.py @@ -37,7 +37,7 @@ def createTempFile(origfile): try: ret = tempfile.mkstemp(prefix=tmp_prefix, dir=tmp_dir) except: - raise IOError, "Unable to create a new temporary file for " + origfile + raise IOError("Unable to create a new temporary file for " + origfile) (fd, tmpfile) = ret shutil.copymode(origfile, tmpfile) os.chown(tmpfile, origstat.st_uid, origstat.st_gid) @@ -68,18 +68,18 @@ def getContext(editmode=False): try: if os.environ["USERCONFIG_USES_LDAP"].lower() == "true": use_ldap = True - except KeyError,e: + except KeyError as e: use_ldap = False if not use_ldap: return PwdContext(editmode) else: - print "===================================================================" - print "Warning:" - print "\tYou are using LDAP as backend. This feature is under development" - print "\tand it is currently not recommended to use it." - print "\tIf you do not want to use LDAP as backend, set the environmental" - print "\tvariabale 'USERCONFIG_USES_LDAP' to 'False'." - print "===================================================================" + print("===================================================================") + print("Warning:") + print("\tYou are using LDAP as backend. This feature is under development") + print("\tand it is currently not recommended to use it.") + print("\tIf you do not want to use LDAP as backend, set the environmental") + print("\tvariabale 'USERCONFIG_USES_LDAP' to 'False'.") + print("===================================================================") return LdapContext(editmode) ########################################################################### @@ -117,9 +117,9 @@ class Context(object): newuserobj = self._createUser() if defaults: if systemuser: - r = xrange(0,self.last_system_uid) + r = range(0,self.last_system_uid) else: - r = xrange(self.first_uid,self.last_uid) + r = range(self.first_uid,self.last_uid) for candiate in r: for u in self._users: if u.getUID()==candiate: @@ -128,13 +128,13 @@ class Context(object): newuserobj.setUID(candiate) break - if self.lookupUsername(u'new_user') is None: - newuserobj.setUsername(u'new_user') + if self.lookupUsername('new_user') is None: + newuserobj.setUsername('new_user') else: i = 1 while 1: - if self.lookupUsername(u'new_user_'+str(i)) is None: - newuserobj.setUsername(u'new_user_'+str(i)) + if self.lookupUsername('new_user_'+str(i)) is None: + newuserobj.setUsername('new_user_'+str(i)) break i += 1 return newuserobj @@ -155,7 +155,7 @@ class Context(object): try: self._groups.remove("new_user") except ValueError: - print "no user removed" + print("no user removed") pass return self._groups[:] @@ -180,9 +180,9 @@ class Context(object): newgroupobj = self._createGroup() if defaults: if systemgroup: - r = xrange(0,self.last_system_gid) + r = range(0,self.last_system_gid) else: - r = xrange(self.first_gid,self.last_gid) + r = range(self.first_gid,self.last_gid) for candiate in r: for u in self._groups: if u.getGID()==candiate: @@ -190,19 +190,19 @@ class Context(object): else: newgroupobj.setGID(candiate) break - if self.lookupGroupname(u'new_group') is None: - newgroupobj.setGroupname(u'new_group') + if self.lookupGroupname('new_group') is None: + newgroupobj.setGroupname('new_group') else: i = 1 while 1: - if self.lookupGroupname(u'new_user_'+str(i)) is None: - newgroupobj.setGroupname(u'new_user_'+str(i)) + if self.lookupGroupname('new_user_'+str(i)) is None: + newgroupobj.setGroupname('new_user_'+str(i)) break i += 1 return newgroupobj def _createGroup(self): - raise NotImplementedError, "Context.newGroup()" + raise NotImplementedError("Context.newGroup()") def addUser(self,userobj): """Adds the given user to the authorisation database. @@ -308,7 +308,7 @@ class Context(object): fhandle = codecs.open('/etc/shells','r',locale.getpreferredencoding()) for l in fhandle.readlines(): # TODO: strangely this lets some comented lines slip through - if len(l.strip()) > 1 and l.strip()[0] is not "#": + if len(l.strip()) > 1 and l.strip()[0] != "#": # Only show existing shells if os.path.isfile(l.strip()): self._shells.append(l.strip()) @@ -321,11 +321,11 @@ class Context(object): After a successful save, any changes to the Context will be reflected system wide. """ - raise NotImplementedError, "Context.save()" + raise NotImplementedError("Context.save()") def createHomeDirectory(self,userobj): if os.path.exists(userobj.getHomeDirectory()): - raise IOError, u"Home directory %s already exists." % userobj.getHomeDirectory() + raise IOError("Home directory %s already exists." % userobj.getHomeDirectory()) # Copy the skeleton directory over shutil.copytree(self._getSkeletonDirectory(),userobj.getHomeDirectory(),True) @@ -348,26 +348,26 @@ class Context(object): shutil.rmtree(userobj.getHomeDirectory()) def _createUser(self): - raise NotImplementedError, "Context._createUser()" + raise NotImplementedError("Context._createUser()") def _sanityCheck(self): userids = [] for u in self._users: if isinstance(u,UnixUser)==False: - raise TypeError,"Found an object in the list of users that is not a UnixUser object." + raise TypeError("Found an object in the list of users that is not a UnixUser object.") uid = u.getUID() if uid in userids: - raise ValueError, "User ID %i appears more than once." % uid + raise ValueError("User ID %i appears more than once." % uid) userids.append(uid) u._sanityCheck() groupids = [] for g in self._groups: if isinstance(g,UnixGroup)==False: - raise TypeError,"Found an object in the list of groups that is not a UnixGroup object." + raise TypeError("Found an object in the list of groups that is not a UnixGroup object.") gid = g.getGID() if gid in groupids: - raise ValueError, "Group ID %i appears more than once." % gid + raise ValueError("Group ID %i appears more than once." % gid) groupids.append(gid) g._sanityCheck() @@ -447,7 +447,7 @@ class Context(object): self.dir_mode = int(self.defaults["DIR_MODE"],8) except (KeyError,ValueError): self.dir_mode = int("0755",8) - print "Didn't read default DIR_MODE" + print("Didn't read default DIR_MODE") try: self.dhome = self.defaults["DHOME"] @@ -496,11 +496,11 @@ class UnixUser(object): new_group = self._context.newGroup() new_group.setGID(self._gid) - new_group_name = u"group%i" % self._gid + new_group_name = "group%i" % self._gid i = 0 while self._context.lookupGroupname(new_group_name) is not None: i += 1 - new_group_name = u"group%i_%i" % (self._gid,i) + new_group_name = "group%i_%i" % (self._gid,i) new_group.setGroupname(new_group_name) self._context.addGroup(new_group) @@ -526,7 +526,7 @@ class UnixUser(object): """ uid = int(uid) if uid<0: - raise ValueError, "User ID (%i) is a negative number." % uid + raise ValueError("User ID (%i) is a negative number." % uid) self._uid = uid def isSystemUser(self): @@ -642,9 +642,9 @@ class UnixUser(object): def _sanityCheck(self): if self._primarygroup is None: - raise ValueError,"Userobj has no primary group!" + raise ValueError("Userobj has no primary group!") if self._uid is None: - raise ValueError,"Userobj has no UID!" + raise ValueError("Userobj has no UID!") ########################################################################### class UnixGroup(object): @@ -722,7 +722,7 @@ class PwdContext(Context): # Read in the password file fhandle = codecs.open(passwordfile,'r',locale.getpreferredencoding()) if LockFDRead(fhandle.fileno())==False: - raise IOError,"Unable to lock the "+passwordfile+" file." + raise IOError("Unable to lock the "+passwordfile+" file.") try: for line in fhandle.readlines(): if line.strip()!="": @@ -736,7 +736,7 @@ class PwdContext(Context): # Read the group file fhandle = codecs.open(groupfile,'r',locale.getpreferredencoding()) if LockFDRead(fhandle.fileno())==False: - raise IOError,"Unable to lock the "+groupfile+" file." + raise IOError("Unable to lock the "+groupfile+" file.") try: for line in fhandle.readlines(): if line.strip()!="": @@ -751,7 +751,7 @@ class PwdContext(Context): # Load up the info from the shadow file too. fhandle = codecs.open(shadowfile,'r',locale.getpreferredencoding()) if LockFDRead(fhandle.fileno())==False: - raise IOError,"Unable to lock the "+shadowfile+" file." + raise IOError("Unable to lock the "+shadowfile+" file.") try: for line in fhandle.readlines(): if line.strip()!="": @@ -762,7 +762,7 @@ class PwdContext(Context): userobj = self.lookupUsername(username) if userobj is not None: if encpass=="": - encpass = u"*" + encpass = "*" userobj._encpass = encpass if userobj._encpass[0]=='!': userobj._islocked = True @@ -770,7 +770,7 @@ class PwdContext(Context): else: userobj._islocked = False # FIXME : set time - if passlastchange and passlastchange!=u"None": + if passlastchange and passlastchange!="None": userobj._passlastchange = int(passlastchange) else: passlastchange = 0 @@ -804,14 +804,14 @@ class PwdContext(Context): else: userobj._passexpiredisabledays = int(passexpiredisabledays) - if disableddays=="" or disableddays==u"99999": + if disableddays=="" or disableddays=="99999": userobj._disableddays = None else: userobj._disableddays = int(disableddays) userobj._reserve = reserve else: - print "Couldn't find",username + print("Couldn't find",username) except ValueError: pass finally: @@ -831,7 +831,7 @@ class PwdContext(Context): def save(self): if self.__editmode==False: - raise IOError, "Can't save, the context was created Read only." + raise IOError("Can't save, the context was created Read only.") self._sanityCheck() @@ -845,7 +845,7 @@ class PwdContext(Context): # Update the passwd file passwordlock = os.open(self.__passwordfile, os.O_WRONLY) # FIXME encoding if LockFDWrite(passwordlock)==False: - raise IOError,"Couldn't get a write lock on "+self.__passwordfile + raise IOError("Couldn't get a write lock on "+self.__passwordfile) try: os.rename(tmpname, self.__passwordfile) finally: @@ -864,7 +864,7 @@ class PwdContext(Context): # Update the group file. grouplock = os.open(self.__groupfile, os.O_WRONLY) if LockFDWrite(grouplock)==False: - raise IOError,"Couldn't get write lock on "+self.__groupfile + raise IOError("Couldn't get write lock on "+self.__groupfile) try: os.rename(tmpname, self.__groupfile) finally: @@ -887,7 +887,7 @@ class PwdContext(Context): shadowlock = os.open(self.__shadowfile, os.O_WRONLY) if LockFDWrite(shadowlock)==False: - raise IOError,"Couldn't get write lock on "+self.__shadowfile + raise IOError("Couldn't get write lock on "+self.__shadowfile) try: os.rename(tmpname, self.__shadowfile) finally: @@ -917,7 +917,7 @@ class LdapContext(Context): self.editmode = editmode if not self.editmode: self.ldapserver.simple_bind("admin",admin_pass) - print "Connected to ", self.url + print("Connected to ", self.url) self._users = self._getUsers() @@ -925,7 +925,7 @@ class LdapContext(Context): """ Retrieve a list of users from the LDAP server. """ _users = [] - print "LdapContext._getUsers" + print("LdapContext._getUsers") searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = None searchFilter = "cn=*" @@ -942,11 +942,11 @@ class LdapContext(Context): #print " --------------------- " result_set.append(result_data[0][1]) #print result_set - except ldap.LDAPError, e: - print "ERROR: ",e + except ldap.LDAPError as e: + print("ERROR: ",e) if len(result_set) == 0: - print "No Results." + print("No Results.") return count = 0 """ @@ -975,12 +975,12 @@ class LdapContext(Context): new_user.setLoginShell(loginshell) new_user.setUsername(login) _users.append(new_user) - print "Number of Users:", len(self._users) + print("Number of Users:", len(self._users)) - except KeyError, e: + except KeyError as e: # Debugging output... - print "ERR:: ",e - print 'err:: ',entry + print("ERR:: ",e) + print('err:: ',entry) return _users def _createUser(self): @@ -990,7 +990,7 @@ class LdapContext(Context): return LdapGroup(self) def save(self): - print "LdapContext.save() does nothing yet." + print("LdapContext.save() does nothing yet.") ########################################################################### class LdapUser(UnixUser): @@ -1010,7 +1010,7 @@ class LdapGroup(UnixGroup): class PwdUser(UnixUser): def __init__(self,context): UnixUser.__init__(self,context) - self._reserve = u"" + self._reserve = "" def _initString(self,line): (self._username,x,self._uid,self._gid,self._gecos,self._homedirectory, \ @@ -1019,17 +1019,17 @@ class PwdUser(UnixUser): self._gid = int(self._gid) def _getPasswdEntry(self): - return u":".join( [self._username, - u"x", - unicode(self._uid), - unicode(self._primarygroup.getGID()), + return ":".join( [self._username, + "x", + str(self._uid), + str(self._primarygroup.getGID()), self._gecos, self._homedirectory, - self._loginshell ] ) + u"\n" + self._loginshell ] ) + "\n" def _getShadowEntry(self): if self._islocked: - encpass = u'!' + self._encpass + encpass = '!' + self._encpass else: encpass = self._encpass @@ -1039,41 +1039,41 @@ class PwdUser(UnixUser): passminimumagebeforechange = str(self._passminimumagebeforechange) if self._passmaximumage==None: - passmaximumage = u"99999" + passmaximumage = "99999" else: - passmaximumage = unicode(self._passmaximumage) + passmaximumage = str(self._passmaximumage) if self._disableddays==None: - disableddays = u"" + disableddays = "" else: - disableddays = unicode(self._disableddays) + disableddays = str(self._disableddays) if self._passexpiredisabledays==None: - passexpiredisabledays = u"" + passexpiredisabledays = "" else: - passexpiredisabledays = unicode(self._passexpiredisabledays) + passexpiredisabledays = str(self._passexpiredisabledays) if self._passexpirewarn==None: - passexpirewarn = u"" + passexpirewarn = "" else: - passexpirewarn = unicode(self._passexpirewarn) + passexpirewarn = str(self._passexpirewarn) - return u":".join( [self._username, + return ":".join( [self._username, encpass, - unicode(self._passlastchange), + str(self._passlastchange), passminimumagebeforechange, passmaximumage, passexpirewarn, passexpiredisabledays, disableddays, - self._reserve ])+ u"\n" + self._reserve ])+ "\n" ########################################################################### class PwdGroup(UnixGroup): def __init__(self,context): UnixGroup.__init__(self,context) - self._memberids = u"" - self._encpass = u"" + self._memberids = "" + self._encpass = "" def _initString(self,line): (self._groupname,self._encpass,self._gid,self._memberids) = tuple(line.strip().split(":")) @@ -1087,10 +1087,10 @@ class PwdGroup(UnixGroup): self._members.append(userobj) def _getGroupFileEntry(self): - return u":".join( [ self._groupname, + return ":".join( [ self._groupname, self._encpass, - unicode(self._gid), - u",".join([u.getUsername() for u in self._members if u.getPrimaryGroup() is not self])]) + u"\n" + str(self._gid), + ",".join([u.getUsername() for u in self._members if u.getPrimaryGroup() is not self])]) + "\n" ########################################################################### def LockFDRead(fd): @@ -1121,34 +1121,34 @@ def UnlockFD(fd): ########################################################################### if __name__=='__main__': - print "Testing" + print("Testing") context = getContext(True) - print "Stopping here..." + print("Stopping here...") #import sys #sys.exit(0) ## Remove. #print "Users:" #for user in context.getUsers(): for user in context._users: - print "--------------------------------------------------" - print "UID:",user.getUID() - print "Is system user:",user.isSystemUser() - print "Username:",user.getUsername() - print "Primary Group:",str(user.getPrimaryGroup()) - print "Groups:",[str(u) for u in user.getGroups()] - print "Is locked:",user.isLocked() - print "Real name:",user.getRealName() - print "Home Dir:",user.getHomeDirectory() - print "Maximum password age:",user.getMaximumPasswordAge() - print "Minimum password age before change:",user.getMinimumPasswordAgeBeforeChange() - print "Expire warning:",user.getPasswordExpireWarning() - print "Disable after Expire:",user.getPasswordDisableAfterExpire() + print("--------------------------------------------------") + print("UID:",user.getUID()) + print("Is system user:",user.isSystemUser()) + print("Username:",user.getUsername()) + print("Primary Group:",str(user.getPrimaryGroup())) + print("Groups:",[str(u) for u in user.getGroups()]) + print("Is locked:",user.isLocked()) + print("Real name:",user.getRealName()) + print("Home Dir:",user.getHomeDirectory()) + print("Maximum password age:",user.getMaximumPasswordAge()) + print("Minimum password age before change:",user.getMinimumPasswordAgeBeforeChange()) + print("Expire warning:",user.getPasswordExpireWarning()) + print("Disable after Expire:",user.getPasswordDisableAfterExpire()) #print user._getPasswdEntry() - print "Groups" + print("Groups") for group in context.getGroups(): - print str(group) + print(str(group)) #print group._getGroupFileEntry() - print "Saving" + print("Saving") context.save() |