with open(’/etc/group’,‘r’) as groupslist:
for eachline2 in groupslist:
groupname2 = os.popen('echo ’ + eachline2.strip() + ‘| cut -d":" -f1’).read()
Is there a reason you’re piping to cut(1) to extract a field? This is an
extremely slow way to do this when:
fields = groupline2.split(':')
groupname2 = fields
is both clearer and much faster?
Using cut and awk is fine for a shell script, that’s part of what
they’re for. But the shell is not a rich language for string processing.
However Python has a whole suite of str methods for cutting strings up
which are very well suited to what you’re doing here.
Also, constructing a shell command such as yours:
echo ... | cat ...
is something to be done with far greater care.
See: xkcd: Exploits of a Mom That example is for SQL, but the shell (and,
generally, any constructed command string) has the same hazards.
with open(args.filename,‘r’) as data:
for eachline in data:
groupname = os.popen('echo ’ + eachline.strip() + ‘| cut -d":" -f1’).read()
gid = os.popen('echo ’ + eachline.strip() + ‘| cut -d":" -f2’).read()
users = os.popen('echo ’ + eachline.strip() + ‘| cut -d":" -f3’).read()
#print('Group Name: ’ + groupname + ’ GID = ’ + gid + ‘Usuarios :’ + users)
in variable groupname = the groups of the file, line by line.
In variablegid = the GID of each group line by line
In users = the users of each group debilitated by ,
I opened the /etc/group to check if each group already exist in the system or no.
I need some help to make that checking
I would makea function like:
which contained your code to read the group file and look for
group_name, and to return True if found and False otherwise. Then you
can write stuff like:
... the group was found ...
... the group was not found ...
And to make a new variable that separate by , the contents of users.
See the str.split method in the Python documentation.
Once I do that, I need to create that groups (those that doesn’t exist
in the system), with its GI (if none GID is written, use the next
available) and with those users that belongs to that group.
You could write a more general version of check_for_group() which
scanned the /etc/group file and returned a dict mapping group names to a
tuple of (gid, members). Then you can implement check_for_group() by
looking in that dict, and compute the next GID by computing the maximium
GID in the dict and adding 1.
You can make a new group by either executing the groupadd command via
subprocess, or opening the group file for append and just writing a
valid group definition line. Take a copy of it (by hand) first, in case
you destroy it. Or work on a totally different file which is a copy of
Do not develop this code as root, you can do all sorts of damage to
your system with accidents.
Cameron Simpson firstname.lastname@example.org