Bootstrap FreeKB - Python (Scripting) - Return users group using os.getgroups
Python (Scripting) - Return users group using os.getgroups

Updated:   |  Python (Scripting) articles

There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).

os.getgroups() can be used to get the username of the user running a Python script.

#!/usr/bin/python3
import os
print(f"group IDs = {os.getgroups()}")

 

Which should return something like this.

group IDs = [100, 2001]

 

Or like this, to loop through the group IDs.

#!/usr/bin/python3
import os

group_ids = os.getgroups()

for group_id in group_ids:
  print(f"group ID = {group_id}")

 

Which should return something like this.

group ID = 100
group ID = 2001

 

Taking this a step further, grp and getgrgid and gr_name can be used to return the group name.

#!/usr/bin/python3
import grp
import os

group_ids = os.getgroups()

for group_id in group_ids:
  print(f"group ID = {group_id}")
  print(f"group name = {grp.getgrgid(group_id).gr_name}")

 

Which should return something like this.

group ID = 100
group name = users
group ID = 2001
group name = mygroup

 

Or like this, as a one liner, to create a list that contains the group names.

#!/usr/bin/python
import grp
import os

group_names = [grp.getgrgid(group_id).gr_name for group_id in os.getgroups()]

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter de3376 in the box below so that we can be sure you are a human.