# -*- coding: UTF-8 -*- # # Copyright (C) 2007 by Jan Dittberner. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, # USA. # # Version: $Id$ import os, popen2 class PasswdUser(object): """This class represents users in the user database.""" def __init__(self, username, pw, uid, gid, gecos, home, shell): self.username = username self.uid = int(uid) self.gid = int(gid) self.gecos = gecos self.home = home self.shell = shell def __repr__(self): return "%s(%s:%d:%d:%s:%s:%s)" % (self.__class__.__name__, self.username, self.uid, self.gid, self.gecos, self.home, self.shell) class PasswdGroup(object): """This class represents lines in the groups database.""" def __init__(self, groupname, pw, gid, members): self.groupname = groupname self.gid = int(gid) self.members = members.split(",") def __repr__(self): return "%s(%s:%d:%s)" % (self.__class__.__name__, self.groupname, self.gid, ",".join(self.members)) def parsegroups(): (stdout, stdin) = popen2.popen2("getent group") return [PasswdGroup(*arr) for arr in [line.strip().split(":") for line in stdout]] def parseusers(): (stdout, stdin) = popen2.popen2("getent passwd") return [PasswdUser(*arr) for arr in [line.strip().split(":") for line in stdout]] def finduserbyprefix(prefix): """Finds all user entries with the given prefix.""" return [user for user in parseusers() if user.username.startswith(prefix)] def getuserbyid(uid): """Gets the user with the given user id.""" users = [user for user in parseusers() if user.uid == uid] if users: return users[0] return None def getgroupbyid(gid): """Gets the group with the given group id.""" groups = [group for group in parsegroups() if group.gid == gid] if groups: return groups[0] return None def getmaxuid(boundary = 65536): """Gets the highest uid value.""" return max([user.uid for user in parseusers() if user.uid <= boundary]) def getmaxgid(boundary = 65536): """Gets the highest gid value.""" return max([group.gid for group in parsegroups() if group.gid <= boundary]) if __name__ == "__main__": print "Max UID is %d" % (getmaxuid(40000)) print "Max GID is %d" % (getmaxgid(40000)) print "User with max UID is %s" % (getuserbyid(getmaxuid(40000))) print "Group with max GID is %s" % (getgroupbyid(getmaxgid(40000)))