Get logged-in user username and groups with Python

Get logged-in user username and groups with Python

Created:15 Jul 2023 16:56:31 , in  Host development

When developing a desktop application for a Linux distribution in Python programming language often it is desirable to know username of a logged-in user and operating system group names the user belongs to. Obtaining these pieces of information requires a bit of knowledge of Python, its modules and also availability of one common command-line utility on the underlying operating system.

Obtaining username of logged-in user with Python

To obtain logged-in user's username with Python one can use a module called getpass and a function it provides called getUser.

Here is an example of this:

import getpass     
username = getpass.getuser()

Obtaing group names for logged-in user

Obtaining operating system group names a logged-in user is a member of is somewhat more tricky. One Python module which helps complete the task is called subprcess. Here is how one can use the module and method run it provides to fetch the group names in the form of a string.

import subprocess
groups =["id", "-nG"],capture_output=True,text=True).stdout.strip()

Internally the code uses a command-line utility called id, So the utility has to be available on the operating system where the code is run.

Tags:  Python 

Author, Copyright and citation


Sylwester Wojnowski

Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.


©Copyright, 2024 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.


Cite this article as:

Wojnowski, Sylwester. "Get logged-in user username and groups with Python." From sWWW - Code For The Web .

Add Comment

Allowed BB Code - style tags: [b][/b], [i][/i], [code=text][/code],[code=javascript][/code],[code=php][/code],[code=bash][/code],[code=css][/code],[code=html][/code]

I constent to processing my data given through this form for purposes of a reply by the administrator of this website.

Recent Comments

Nobody has commented on this post yet. Be first!