summaryrefslogtreecommitdiffstats
path: root/userconfig
diff options
context:
space:
mode:
authorSlávek Banko <slavek.banko@axis.cz>2023-01-19 18:01:26 +0100
committerMichele Calgaro <michele.calgaro@yahoo.it>2023-01-20 13:05:37 +0900
commit94f5a3f12e1c61aa2f3cde2d7b260c08489336ac (patch)
tree9062a30a1d81a1a97e9397548e4ec48ae63c18a4 /userconfig
parentb9c0b6996a6da72f93baf50121a1be4a6fa48d2e (diff)
downloadtde-guidance-94f5a3f12e1c61aa2f3cde2d7b260c08489336ac.tar.gz
tde-guidance-94f5a3f12e1c61aa2f3cde2d7b260c08489336ac.zip
Drop python2 support.
Signed-off-by: Slávek Banko <slavek.banko@axis.cz>
Diffstat (limited to 'userconfig')
-rwxr-xr-xuserconfig/unixauthdb.py198
-rwxr-xr-xuserconfig/userconfig.py246
2 files changed, 222 insertions, 222 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()
diff --git a/userconfig/userconfig.py b/userconfig/userconfig.py
index fb47f57..9ef5bdc 100755
--- a/userconfig/userconfig.py
+++ b/userconfig/userconfig.py
@@ -315,12 +315,12 @@ class UserConfigApp(programbase):
cmenu.setItemEnabled(1,False)
cmenu.exec_loop(p)
- #######################################################################
+ #######################################################################
def sizeHint(self):
global programbase
size_hint = programbase.sizeHint(self)
# Just make the dialog a little shorter by default.
- size_hint.setHeight(size_hint.height()-200)
+ size_hint.setHeight(size_hint.height()-200)
return size_hint
#######################################################################
@@ -439,7 +439,7 @@ class UserConfigApp(programbase):
for userobj in users:
uid = userobj.getUID()
if self.showsystemaccounts or not userobj.isSystemUser():
- lvi = TDEListViewItem(self.userlist,userobj.getUsername(),userobj.getRealName(),unicode(uid))
+ lvi = TDEListViewItem(self.userlist,userobj.getUsername(),userobj.getRealName(),str(uid))
if userobj.isLocked():
lvi.setPixmap(0,UserIcon("hi16-encrypted"))
self.useridsToListItems[uid] = lvi
@@ -457,7 +457,7 @@ class UserConfigApp(programbase):
userobj = self.admincontext.lookupUID(userid)
lvi.setText(0,userobj.getUsername())
lvi.setText(1,userobj.getRealName())
- lvi.setText(2,unicode(userobj.getUID()))
+ lvi.setText(2,str(userobj.getUID()))
if userobj.isLocked():
lvi.setPixmap(0,UserIcon("hi16-encrypted"))
else:
@@ -477,7 +477,7 @@ class UserConfigApp(programbase):
username = userobj.getUsername()
self.loginnamelabel.setText(username)
self.realnamelabel.setText(userobj.getRealName())
- self.uidlabel.setText(unicode(userid))
+ self.uidlabel.setText(str(userid))
if userobj.isLocked():
self.statuslabel.setText(i18n("Disabled"))
else:
@@ -490,7 +490,7 @@ class UserConfigApp(programbase):
# Secondary Groups
secondarygroups = [g.getGroupname() for g in userobj.getGroups() if g is not userobj.getPrimaryGroup()]
- self.secondarygrouplabel.setText(unicode(i18n(", ")).join(secondarygroups))
+ self.secondarygrouplabel.setText(str(i18n(", ")).join(secondarygroups))
if isroot:
self.deletebutton.setDisabled(userobj.getUID()==0)
@@ -505,7 +505,7 @@ class UserConfigApp(programbase):
for groupobj in groups:
gid = groupobj.getGID()
if self.showsystemgroups or not groupobj.isSystemGroup():
- lvi = TQListViewItem(self.grouplist,groupobj.getGroupname(),unicode(gid))
+ lvi = TQListViewItem(self.grouplist,groupobj.getGroupname(),str(gid))
self.groupidsToListItems[gid] = lvi
if self.selectedgroupid==gid:
firstselectedgroupid = gid
@@ -528,7 +528,7 @@ class UserConfigApp(programbase):
self.groupmemberlist.clear()
for userobj in members:
if userobj!=None:
- lvi = TQListViewItem(self.groupmemberlist,userobj.getUsername(),userobj.getRealName(),unicode(userobj.getUID()))
+ lvi = TQListViewItem(self.groupmemberlist,userobj.getUsername(),userobj.getRealName(),str(userobj.getUID()))
if isroot:
self.deletegroupbutton.setDisabled(groupobj.getGID()==0)
@@ -563,7 +563,7 @@ class UserConfigApp(programbase):
def save(self):
pass
def defaults(self):
- pass
+ pass
def sysdefaults(self):
pass
@@ -578,28 +578,28 @@ class UserConfigApp(programbase):
# Rudd-O convenience class to map groups to privilege names
class PrivilegeNames(dict):
- """Convenience dict-derived class: map known secondary groups to privilege names, provide default mapping for groups that do not have a description. This could be replaced by a simple dict() but I simply preferred the class declaration.
-
- FIXME This should ideally be included in a more general module so it can be reused."""
-
- def __init__(self):
- dict.__init__(self, {
- "plugdev":i18n("Access external storage devices automatically"),
- "adm":i18n("Administer the system"),
- "ltsp":i18n("Allow use of FUSE filesystems like LTSP thin client block devices"),
- "dialout":i18n("Connect to the Internet using a modem"),
- "syslog":i18n("Monitor system logs"),
- "fax":i18n("Send and receive faxes"),
- "cdrom":i18n("Use CD-ROM and DVD drives"),
- "floppy":i18n("Use floppy drives"),
- "modem":i18n("Use modems"),
- "scanner":i18n("Use scanners"),
- })
-
- def __getitem__(self,name):
- # This is cruft but I couldn't bring myself to kill it bua!
- if name in self: return dict.__getitem__(self,name)
- return i18n("Be a member of the %s group")%name
+ """Convenience dict-derived class: map known secondary groups to privilege names, provide default mapping for groups that do not have a description. This could be replaced by a simple dict() but I simply preferred the class declaration.
+
+ FIXME This should ideally be included in a more general module so it can be reused."""
+
+ def __init__(self):
+ dict.__init__(self, {
+ "plugdev":i18n("Access external storage devices automatically"),
+ "adm":i18n("Administer the system"),
+ "ltsp":i18n("Allow use of FUSE filesystems like LTSP thin client block devices"),
+ "dialout":i18n("Connect to the Internet using a modem"),
+ "syslog":i18n("Monitor system logs"),
+ "fax":i18n("Send and receive faxes"),
+ "cdrom":i18n("Use CD-ROM and DVD drives"),
+ "floppy":i18n("Use floppy drives"),
+ "modem":i18n("Use modems"),
+ "scanner":i18n("Use scanners"),
+ })
+
+ def __getitem__(self,name):
+ # This is cruft but I couldn't bring myself to kill it bua!
+ if name in self: return dict.__getitem__(self,name)
+ return i18n("Be a member of the %s group")%name
class UserEditDialog(KDialogBase):
def __init__(self,parent,admincontext):
@@ -637,7 +637,7 @@ class UserEditDialog(KDialogBase):
hbox.setStretchFactor(self.disabledradio,0)
label = TQLabel(hbox)
label.setPixmap(UserIcon("hi16-encrypted"))
- hbox.setStretchFactor(label,1)
+ hbox.setStretchFactor(label,1)
infogrid.addWidget(hbox,1,1)
self.enabledradiogroup.insert(self.enabledradio,0)
@@ -691,19 +691,19 @@ class UserEditDialog(KDialogBase):
infogrid.addWidget(self.shelledit,8,1)
# Rudd-O rules. Not so much, but enough to rule.
- # yeah it's not my finest hour, but it works like a charm over here. Please feel free to clean up dead code that I commented
- # I extend my deepest thanks to the people that have worked hard to construct this tool in the first place. I have no idea who the authors and contributors are, but it would make sense to have all the contributors listed on top of the file.
- # Privileges and groups tab
+ # yeah it's not my finest hour, but it works like a charm over here. Please feel free to clean up dead code that I commented
+ # I extend my deepest thanks to the people that have worked hard to construct this tool in the first place. I have no idea who the authors and contributors are, but it would make sense to have all the contributors listed on top of the file.
+ # Privileges and groups tab
groupsvbox = self.addHBoxPage(i18n("Privileges and groups"))
- # Rudd-O now here we create the widget that will hold the group listing, and fill it with the groups.
+ # Rudd-O now here we create the widget that will hold the group listing, and fill it with the groups.
self.privilegeslistview = TQListView(groupsvbox)
- self.privilegeslistview.addColumn(i18n("Privilege"),-1)
+ self.privilegeslistview.addColumn(i18n("Privilege"),-1)
self.groupslistview = TQListView(groupsvbox)
- self.groupslistview.addColumn(i18n("Secondary group"),-1)
- groupsvbox.setStretchFactor(self.privilegeslistview,3)
- groupsvbox.setStretchFactor(self.groupslistview,2)
-
+ self.groupslistview.addColumn(i18n("Secondary group"),-1)
+ groupsvbox.setStretchFactor(self.privilegeslistview,3)
+ groupsvbox.setStretchFactor(self.groupslistview,2)
+
# Password and Security Tab.
passwordvbox = self.addVBoxPage(i18n("Password && Security"))
@@ -771,7 +771,7 @@ class UserEditDialog(KDialogBase):
self.connect(self.forcepasswordchangecheckbox,SIGNAL("toggled(bool)"),self.slotForcePasswordChangeToggled)
passwordaginggrid.addWidget(self.forcepasswordchangecheckbox,0,0)
label = TQLabel(i18n("Require new password after:"),passwordagingwidget)
- passwordaginggrid.addWidget(label,0,1)
+ passwordaginggrid.addWidget(label,0,1)
self.maximumpasswordedit = TQSpinBox(passwordagingwidget)
self.maximumpasswordedit.setSuffix(i18n(" days"))
self.maximumpasswordedit.setMinValue(1)
@@ -816,25 +816,25 @@ class UserEditDialog(KDialogBase):
self.updatingGUI = False
def _repopulateGroupsPrivileges(self,excludegroups=None):
- # needs listviews to be constructed. Expects a list of PwdGroups to be excluded
-
- # rehash everything
- self.privilegeslistview.clear()
- self.groupslistview.clear()
- self.secondarygroupcheckboxes = {}
- pn = PrivilegeNames()
-
- if excludegroups: excludegroups = [ g.getGroupname() for g in excludegroups ]
- else: excludegroups = []
- for group in [g.getGroupname() for g in self.admincontext.getGroups()]:
- if group in excludegroups: continue
- if group in pn:
- name = i18n(unicode(pn[group]).encode(locale.getpreferredencoding()))
- wid = self.privilegeslistview
- else:
- name = unicode(group).encode(locale.getpreferredencoding())
- wid = self.groupslistview
- self.secondarygroupcheckboxes[group] = TQCheckListItem(wid,name,TQCheckListItem.CheckBox)
+ # needs listviews to be constructed. Expects a list of PwdGroups to be excluded
+
+ # rehash everything
+ self.privilegeslistview.clear()
+ self.groupslistview.clear()
+ self.secondarygroupcheckboxes = {}
+ pn = PrivilegeNames()
+
+ if excludegroups: excludegroups = [ g.getGroupname() for g in excludegroups ]
+ else: excludegroups = []
+ for group in [g.getGroupname() for g in self.admincontext.getGroups()]:
+ if group in excludegroups: continue
+ if group in pn:
+ name = i18n(str(pn[group]).encode(locale.getpreferredencoding()))
+ wid = self.privilegeslistview
+ else:
+ name = str(group).encode(locale.getpreferredencoding())
+ wid = self.groupslistview
+ self.secondarygroupcheckboxes[group] = TQCheckListItem(wid,name,TQCheckListItem.CheckBox)
########################################################################
def showEditUser(self,userid):
@@ -845,14 +845,14 @@ class UserEditDialog(KDialogBase):
self.passwordedit.erase()
self.selectedgroups = [g.getGroupname() for g in self.userobj.getGroups()
if g is not self.userobj.getPrimaryGroup()]
-
- # Rudd-O: now here we tick the appropriate group listing checkbox, and hide the currently active primary group of the user. We are repopulating because if the user to edit changes, we need to hide the user's secondary group. FIXME we should repopulate the groups privileges list when the primary group is changed in the other tab -- that is, on the change slot of the primary group drop down.
- self._repopulateGroupsPrivileges(excludegroups=[self.userobj.getPrimaryGroup()])
- for group,checkbox in self.secondarygroupcheckboxes.items():
- if group in self.selectedgroups: checkbox.setState(TQCheckListItem.On)
- else: checkbox.setState(TQCheckListItem.Off)
-
- self.originalgroups = self.selectedgroups[:]
+
+ # Rudd-O: now here we tick the appropriate group listing checkbox, and hide the currently active primary group of the user. We are repopulating because if the user to edit changes, we need to hide the user's secondary group. FIXME we should repopulate the groups privileges list when the primary group is changed in the other tab -- that is, on the change slot of the primary group drop down.
+ self._repopulateGroupsPrivileges(excludegroups=[self.userobj.getPrimaryGroup()])
+ for group,checkbox in list(self.secondarygroupcheckboxes.items()):
+ if group in self.selectedgroups: checkbox.setState(TQCheckListItem.On)
+ else: checkbox.setState(TQCheckListItem.Off)
+
+ self.originalgroups = self.selectedgroups[:]
self.selectedgroups.sort()
self.__syncGUI()
self.uidedit.setReadOnly(True)
@@ -864,18 +864,18 @@ class UserEditDialog(KDialogBase):
if self.passwordedit.password()!="":
self.userobj.setPassword(self.passwordedit.password())
# Update the groups for this user object. Rudd-O here's when you go in, stud.
- # we collect the selected groups
- self.selectedgroups = [ group for group,checkbox in self.secondarygroupcheckboxes.items() if checkbox.isOn() ]
+ # we collect the selected groups
+ self.selectedgroups = [ group for group,checkbox in list(self.secondarygroupcheckboxes.items()) if checkbox.isOn() ]
for g in self.userobj.getGroups(): # this seems wasteful to remove the user from all groups then re-add, why not a cross check?
self.userobj.removeFromGroup(g)
for gn in self.selectedgroups:
self.userobj.addToGroup(self.admincontext.lookupGroupname(gn))
- primarygroupname = unicode(self.primarygroupedit.currentText())
+ primarygroupname = str(self.primarygroupedit.currentText())
self.userobj.setPrimaryGroup(self.admincontext.lookupGroupname(primarygroupname))
- # Enable/Disable the account
+ # Enable/Disable the account
self.userobj.setLocked(self.enabledradiogroup.id(self.enabledradiogroup.selected())!=0)
self.admincontext.save()
@@ -889,17 +889,17 @@ class UserEditDialog(KDialogBase):
self.newgroup.setGroupname(self.__fudgeNewGroupName(self.userobj.getUsername()))
self.userobj.setPrimaryGroup(self.newgroup)
- self.selectedgroups = [ u'dialout',u'cdrom',u'floppy',u'audio',u'video',
- u'plugdev',u'lpadmin',u'scanner']
+ self.selectedgroups = [ 'dialout','cdrom','floppy','audio','video',
+ 'plugdev','lpadmin','scanner']
homedir = self.__fudgeNewHomeDirectory(self.userobj.getUsername())
-
- # Rudd-O FIXME: now here we tick the proper groups that should be allowed. Now it selects what userconfig selected before. FIXME consider adding a drop down that will select the appropriate profile Limited User, Advanced User or Administrator (and see if there is a config file where these profiles can be read). We are repopulating because if the user to edit changes, we need to hide the user's secondary group. FIXME we should repopulate the groups privileges list when the primary group is changed in the other tab -- that is, on the change slot of the primary group drop down.
- self._repopulateGroupsPrivileges()
- for group,checkbox in self.secondarygroupcheckboxes.items():
- if group in self.selectedgroups: checkbox.setState(TQCheckListItem.On)
- else: checkbox.setState(TQCheckListItem.Off)
-
- self.userobj.setHomeDirectory(homedir)
+
+ # Rudd-O FIXME: now here we tick the proper groups that should be allowed. Now it selects what userconfig selected before. FIXME consider adding a drop down that will select the appropriate profile Limited User, Advanced User or Administrator (and see if there is a config file where these profiles can be read). We are repopulating because if the user to edit changes, we need to hide the user's secondary group. FIXME we should repopulate the groups privileges list when the primary group is changed in the other tab -- that is, on the change slot of the primary group drop down.
+ self._repopulateGroupsPrivileges()
+ for group,checkbox in list(self.secondarygroupcheckboxes.items()):
+ if group in self.selectedgroups: checkbox.setState(TQCheckListItem.On)
+ else: checkbox.setState(TQCheckListItem.Off)
+
+ self.userobj.setHomeDirectory(homedir)
self.homediredit.setText(homedir)
shells = self.admincontext.getUserShells()
@@ -909,9 +909,9 @@ class UserEditDialog(KDialogBase):
elif '/bin/bash' in shells:
self.userobj.setLoginShell('/bin/bash')
elif '/bin/sh' in shells:
- self.userobj.setLoginShell('/bin/sh')
+ self.userobj.setLoginShell('/bin/sh')
elif len(shells)!=0:
- self.userobj.setLoginShell(shells[0])
+ self.userobj.setLoginShell(shells[0])
self.__syncGUI()
@@ -944,8 +944,8 @@ class UserEditDialog(KDialogBase):
self.userobj.setPrimaryGroup(newgroup)
# Update the groups for this user object. Rudd-O here's when you go in, stud.
- # we collect the selected groups
- self.selectedgroups = [ group for group,checkbox in self.secondarygroupcheckboxes.items() if checkbox.isOn() ]
+ # we collect the selected groups
+ self.selectedgroups = [ group for group,checkbox in list(self.secondarygroupcheckboxes.items()) if checkbox.isOn() ]
for gn in self.selectedgroups:
self.userobj.addToGroup(self.admincontext.lookupGroupname(gn))
@@ -953,7 +953,7 @@ class UserEditDialog(KDialogBase):
if self.passwordedit.password()!="":
self.userobj.setPassword(self.passwordedit.password())
- # Enable/Disable the account
+ # Enable/Disable the account
self.userobj.setLocked(self.enabledradiogroup.id(self.enabledradiogroup.selected())!=0)
self.admincontext.save()
@@ -972,18 +972,18 @@ class UserEditDialog(KDialogBase):
ok = True
# Sanity check all values.
if self.newusermode:
- newusername = unicode(self.realnameedit.text())
+ newusername = str(self.realnameedit.text())
if self.admincontext.lookupUsername(newusername)!=None:
KMessageBox.sorry(self,i18n("Sorry, you must choose a different user name.\n'%1' is already being used.").arg(newusername))
ok = False
else:
- newuid = int(unicode(self.uidedit.text()))
+ newuid = int(str(self.uidedit.text()))
originaluid = self.userobj.getUID()
if self.admincontext.lookupUID(newuid)!=None:
rc = KMessageBox.questionYesNo(self,i18n("User ID in use"),
i18n("Sorry, the UID %1 is already in use. Should %2 be used instead?").arg(newuid).arg(originaluid))
if rc==KMessageBox.Yes:
- self.uidedit.setValue(unicode(originaluid))
+ self.uidedit.setValue(str(originaluid))
else:
ok = False
else:
@@ -994,7 +994,7 @@ class UserEditDialog(KDialogBase):
########################################################################
def slotLoginChanged(self,text):
- newtext = unicode(text)
+ newtext = str(text)
if not self.updatingGUI:
if self.newusermode:
self.newprimarygroupname = self.__fudgeNewGroupName(newtext)
@@ -1019,7 +1019,7 @@ class UserEditDialog(KDialogBase):
self.loginnameedit.setText(self.userobj.getUsername())
self.realnameedit.setText(self.userobj.getRealName())
- self.uidedit.setText(unicode(self.userobj.getUID()))
+ self.uidedit.setText(str(self.userobj.getUID()))
self.homediredit.setText(self.userobj.getHomeDirectory())
self.shelledit.setCurrentText(self.userobj.getLoginShell())
@@ -1036,7 +1036,7 @@ class UserEditDialog(KDialogBase):
if self.newusermode:
# New user mode
- self.newprimarygroupname = self.__fudgeNewGroupName(unicode(self.userobj.getUsername()))
+ self.newprimarygroupname = self.__fudgeNewGroupName(str(self.userobj.getUsername()))
primarygroupname = self.newprimarygroupname
self.primarygroupedit.insertItem(self.newprimarygroupname)
else:
@@ -1050,7 +1050,7 @@ class UserEditDialog(KDialogBase):
if self.userobj.getExpirationDate() is None:
self.validradiogroup.setButton(0)
self.expiredate.setDisabled(True)
- self.expiredate.setDate(SptimeToQDate(99999L))
+ self.expiredate.setDate(SptimeToQDate(99999))
else:
self.validradiogroup.setButton(1)
self.expiredate.setDisabled(False)
@@ -1097,13 +1097,13 @@ class UserEditDialog(KDialogBase):
########################################################################
def __updateObjectFromGUI(self,userobj):
- username = unicode(self.loginnameedit.text())
+ username = str(self.loginnameedit.text())
userobj.setUsername(username)
- userobj.setRealName(unicode(self.realnameedit.text()))
+ userobj.setRealName(str(self.realnameedit.text()))
- userobj.setHomeDirectory(unicode(self.homediredit.text()))
- userobj.setLoginShell(unicode(self.shelledit.currentText()))
- self.primarygroupname = unicode(self.primarygroupedit.currentText())
+ userobj.setHomeDirectory(str(self.homediredit.text()))
+ userobj.setLoginShell(str(self.shelledit.currentText()))
+ self.primarygroupname = str(self.primarygroupedit.currentText())
groupobj = self.admincontext.lookupGroupname(self.primarygroupname)
if groupobj is not None:
userobj.setPrimaryGroup(groupobj)
@@ -1165,30 +1165,30 @@ class UserEditDialog(KDialogBase):
if self.admincontext.lookupGroupname(basename) is None:
return basename
x = 1
- while self.admincontext.lookupGroupname(basename + u'_' + unicode(x)) is not None:
+ while self.admincontext.lookupGroupname(basename + '_' + str(x)) is not None:
x += 1
- return basename + u'_' + unicode(x)
+ return basename + '_' + str(x)
#######################################################################
def __fudgeNewHomeDirectory(self,origbasename):
basename = origbasename.replace("/","")
if basename=="":
- basename = u"user"
+ basename = "user"
dhome = self.admincontext.dhome
if not os.path.isdir(dhome):
- raise OSError, dhome+" does not exist, is it correctly set in "+ \
- self.admincontext.adduserconf+" ?"
+ raise OSError(dhome+" does not exist, is it correctly set in "+ \
+ self.admincontext.adduserconf+" ?")
else:
# Make sure there's a trailing /
- if dhome[-1] is not '/':
+ if dhome[-1] != '/':
dhome = dhome+'/'
if os.path.exists(dhome+basename)==False:
return dhome+basename
else:
x = 1
- while os.path.exists(dhome+basename + u'_' + unicode(x)):
+ while os.path.exists(dhome+basename + '_' + str(x)):
x += 1
return dhome+basename
@@ -1200,7 +1200,7 @@ class LoginNameValidator(TQValidator):
#######################################################################
def validate(self,inputstr,pos):
- instr = unicode(inputstr)
+ instr = str(inputstr)
if len(instr)==0:
return (TQValidator.Intermediate,pos)
for c in instr:
@@ -1218,7 +1218,7 @@ class LoginNameValidator(TQValidator):
#######################################################################
def fixup(self,inputstr):
- instr = unicode(inputstr)
+ instr = str(inputstr)
newstr = ""
for c in instr:
if (ord(c)<0x20 or ord(c)>0x7f or c.isspace() or c==":" or c=="," or c==".")==False:
@@ -1236,7 +1236,7 @@ class RealUserNameValidator(TQValidator):
#######################################################################
def validate(self,inputstr,pos):
- instr = unicode(inputstr)
+ instr = str(inputstr)
for c in instr:
if c==":":
return (TQValidator.Invalid,pos)
@@ -1252,7 +1252,7 @@ class RealUserNameValidator(TQValidator):
#######################################################################
def fixup(self,inputstr):
- return unicode(inputstr).replace(":","")
+ return str(inputstr).replace(":","")
###########################################################################
class ListPickerDialog(KDialogBase):
@@ -1314,7 +1314,7 @@ class ListPickerDialog(KDialogBase):
if self.exec_loop()==TQDialog.Accepted:
newlist = []
for i in range(self.selectedlist.count()):
- newlist.append(unicode(self.selectedlist.item(i).text()))
+ newlist.append(str(self.selectedlist.item(i).text()))
return newlist
else:
return selectedlist
@@ -1411,7 +1411,7 @@ class UserDeleteDialog(KDialog):
self.connect(cancelbutton,SIGNAL("clicked()"),self.slotCancelClicked)
def deleteUser(self,userid):
- # Setup the
+ # Setup the
userobj = self.admincontext.lookupUID(userid)
self.usernamelabel.setText(i18n("Are you sure want to delete user account '%1' (%2)?").arg(userobj.getUsername()).arg(userobj.getUID()) )
self.deletedirectorycheckbox.setChecked(False)
@@ -1507,7 +1507,7 @@ class OverwriteHomeDirectoryDialog(KDialog):
self.connect(cancelbutton,SIGNAL("clicked()"),self.slotCancelClicked)
def do(self,userobj):
- # Setup the
+ # Setup the
self.toplabel.setText(i18n("The directory '%1' was entered as the home directory for new user '%2'.\n This directory already exists.") \
.arg(userobj.getHomeDirectory()).arg(userobj.getUsername()) )
self.radiogroup.setButton(0)
@@ -1602,7 +1602,7 @@ class GroupEditDialog(KDialogBase):
groupobj = self.admincontext.lookupGID(groupid)
self.groupnamelabel.setText(groupobj.getGroupname())
- self.groupidlabel.setText(unicode(groupid))
+ self.groupidlabel.setText(str(groupid))
availablemembers = [u.getUsername() for u in self.admincontext.getUsers()]
originalmembers = [u.getUsername() for u in groupobj.getUsers()]
@@ -1612,7 +1612,7 @@ class GroupEditDialog(KDialogBase):
if self.exec_loop()==TQDialog.Accepted:
newmembers = []
for i in range(self.selectedlist.count()):
- newmembers.append(unicode(self.selectedlist.item(i).text()))
+ newmembers.append(str(self.selectedlist.item(i).text()))
# Remove from the group object any unselected users.
for member in originalmembers:
@@ -1639,7 +1639,7 @@ class GroupEditDialog(KDialogBase):
groupname = self.groupobj.getGroupname()
self.groupnamelabel.setText(groupname)
self.groupnamelabel.setReadOnly(False)
- self.groupidlabel.setText(unicode(self.groupobj.getGID()))
+ self.groupidlabel.setText(str(self.groupobj.getGID()))
self.groupidlabel.setReadOnly(False)
availablemembers = [u.getUsername() for u in self.admincontext.getUsers()]
@@ -1647,13 +1647,13 @@ class GroupEditDialog(KDialogBase):
self.__updateLists(availablemembers,[])
if self.exec_loop()==TQDialog.Accepted:
- self.groupobj.setGroupname(unicode(self.groupnamelabel.text()))
- newgroupid = int(unicode(self.groupidlabel.text()))
+ self.groupobj.setGroupname(str(self.groupnamelabel.text()))
+ newgroupid = int(str(self.groupidlabel.text()))
self.groupobj.setGID(newgroupid)
newmembers = []
for i in range(self.selectedlist.count()):
- newmembers.append(unicode(self.selectedlist.item(i).text()))
+ newmembers.append(str(self.selectedlist.item(i).text()))
self.admincontext.addGroup(self.groupobj)
@@ -1725,9 +1725,9 @@ class GroupEditDialog(KDialogBase):
if basename not in availablegroups:
return basename
x = 1
- while basename + u'_' + unicode(x) in availablegroups:
+ while basename + '_' + str(x) in availablegroups:
x += 1
- return basename + u'_' + unicode(x)
+ return basename + '_' + str(x)
############################################################################
# Factory function for KControl
@@ -1737,7 +1737,7 @@ def create_userconfig(parent,name):
##########################################################################
def MakeAboutData():
aboutdata = TDEAboutData("guidance", programname, version,
- unicode(i18n("User and Group Configuration Tool")).encode(locale.getpreferredencoding()),
+ str(i18n("User and Group Configuration Tool")).encode(locale.getpreferredencoding()),
TDEAboutData.License_GPL, "Copyright (C) 2003-2007 Simon Edwards")
aboutdata.addAuthor("Simon Edwards", "Developer", "simon@simonzone.com", "http://www.simonzone.com/software/")
aboutdata.addAuthor("Sebastian Kügler", "Developer", "sebas@kde.org", "http://vizZzion.org")