我的目标是编写一个python脚本,该脚本枚举来自/ etc / passwd和/ etc / group(或它们的用户)的系统用户和组。
网络数据库等效项)。为每个用户打印用户的UID以及该用户所属的组。
标记具有多个用户名的UID。标记具有多个组名的GID
与他们相关联。我有两个单独的脚本可以实现这一目标,但是如何将它们组合为一个?
#!/usr/bin/env python
from collections import defaultdict
# Initialize dictionary of user ids
uids = defaultdict(list)
# loop through password file, building dictionary of uid:[list of usernames]
with open("/etc/passwd") as passwd_file:
for line in passwd_file:
line_array = line.split(":")
uids[line_array[2]].append(line_array[0])
# loop though dictionary.
# If duplicate usernames for uid found, print on standard out
for uid in uids:
if len(uids[uid]) > 1:
print ( uid + ": " + " ".join(uids[uid]))
#!/usr/bin/env python
from collections import defaultdict
# Initialize dictionary of group ids
gids = defaultdict(list)
# loop through password file, building dictionary of gid:[list of groups]
with open("/etc/group") as group_file:
for line in group_file:
line_array = line.split(":")
gids[line_array[2]].append(line_array[0])
# loop though dictionary.
# If duplicate group for gid found, print on standard out
for gid in gids:
if len(gids[gid]) > 1:
print ( gid + ": " + " ".join(gids[gid]))