0

Hello guys I am really new to python and I am trying to sort the /etc/passwd file using PYTHON 3.4 based on the following criteria: Input (regular /etc/passwd file on linux system:

raj:x:501:512::/home/raj:/bin/ksh
ash:x:502:502::/home/ash:/bin/zsh
jadmin:x:503:503::/home/jadmin:/bin/sh
jwww:x:504:504::/htdocs/html:/sbin/nologin
wwwcorp:x:505:511::/htdocs/corp:/sbin/nologin
wwwint:x:506:507::/htdocs/intranet:/bin/bash
scpftp:x:507:507::/htdocs/ftpjail:/bin/bash
rsynftp:x:508:512::/htdocs/projets:/bin/bash
mirror:x:509:512::/htdocs:/bin/bash
jony:x:510:511::/home/jony:/bin/ksh
amyk:x:511:511::/home/amyk:/bin/ksh

Output that I am looking for either to the file or returned to the screen:

Group 511 : jony, amyk, wwwcorp
Group 512 : mirror, rsynftp, raj
Group 507 : wwwint, scpftp 
and so on 

Here is my plan:

1) Open and read the whole file or do it line by line 
2) Loop through the file using python regex 
3) Write it into temp file or create a dictionary 
4) Print the dictionary keys and values

I will really appreciate the example how it can be done efficiently or apply any sorting algorithm. Thanks!

1
  • 1
    You don't need regex for this. Just split by ":" and take the name (0th element) and gid (3rd element). Commented Jan 30, 2015 at 2:24

2 Answers 2

3

You can open the file, throw it into a list and then throw all the users into some kinda hash table

with open("/etc/passwd") as f:
    lines = f.readlines()

group_dict = {}
for line in lines:
    split_line = line.split(":")
    user = split_line[0]
    gid = split_line[3]
    # If the group id is not in the dict then put it in there with a list of users 
    # that are under that group
    if gid not in group_dict:
        group_dict[gid] = [user]
    # If the group id does exist then add the new user to the list of users in 
    # the group
    else:
        group_dict[gid].append(user)

# Iterate over the groups and users we found. Keys (group) will be the first item in the tuple, 
# and the list of users will be the second item. Print out the group and users as we go
for group, users in group_dict.iteritems():
    print("Group {}, users: {}".format(group, ",".join(users)))
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Greg, any chance you can put the comments for the second part of the script for me to better understand the flow
I added some comments to the code. The python documentation is also very helpful if you are having trouble understanding some of the syntax as well
1

This should loop through your /etc/passwd and sort users by group. You don't have to do anything fancy to solve this problem.

with open('/etc/passwd', 'r') as f:
    res = {}

    for line in f:
        parts = line.split(':')

        try:
            name, gid = parts[0], int(parts[3])
        except IndexError:
            print("Invalid line.")
            continue

        try:
            res[gid].append(name)
        except KeyError:
            res[gid] = [name]

for key, value in res.items():
    print(str(key) + ': ' + ', '.join(value))

4 Comments

Not bad, Andreas. FWIW, we (mostly) prefer an indentation of 4 spaces around here. You have a superfluous ; after res = {}, and to teach the Python beginners good habits you could use a slightly more meaningful name than res. And if you're going to test for IndexError perhaps you should print an error message rather than silently continuing. Also, why just test for IndexError and not for ValueError: invalid literal for int()? But kudos for using EAFP on the dict insertion.
Thanks Andreas, any chance you can put the comments so I can better understand the code ?
@Zerg12: Maybe you should read the section in the official Python tutorial on try: ... except: Errors and Exceptions. That should help you to understand the bulk of Andreas' code.
Sorry, have been writing too much JavaScript lately. Will change the indentation to four spaces. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.