I have been trying to fetch the last and first field from the /etc/passwd file in Linux. I want to fetch the last fields of the file(the shell which users are using) and the first field(number of users using the shell) and add it to a list. For eg my final output must be something like
JavaScript
x
2
1
{"/bin/bash/" :[username1,username2],"/usr/sbin/nologin": [username2]}
2
Basically, I want the key of the dictionary to be the shell and its value must be an array of users.
For this, I have tried the below code
JavaScript
1
13
13
1
password_file = '/etc/passwd'
2
handler = open(password_file)
3
empty_dict = {}
4
5
for line in handler:
6
last_line = line.split(':')[6] #to fetch last line
7
first_line = line.split(':')[0] #to fetch first line
8
userlist[] #create an array for users
9
userlist.append(first_line)
10
if(first_line not in last_line):
11
empty_dict[last_line] = userlist #adding the user array to the dict as value
12
print(empty_dict)
13
This gives the output but this doesn’t involve all the users to the dictionary key. Can you guys help me on which logic I went wrong? Any help would be great. Thank you
Advertisement
Answer
If I understood your question correctly, you’re resetting the userlist
inside the loop. Here is one possible way of doing this:
JavaScript
1
13
13
1
from collections import defaultdict
2
3
password_file = '/etc/passwd'
4
handler = open(password_file)
5
6
userlist = defaultdict(list)
7
for line in handler:
8
first, *_, last = line.strip().split(':')
9
if first not in last:
10
userlist[last or 'nologin'].append(first)
11
12
handler.close()
13