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()
print(username)
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 = subprocess.run(["id", "-nG"],capture_output=True,text=True).stdout.strip()
print(groups)
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
Author
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.
Copyrights
©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.
Citation
Cite this article as:
Wojnowski, Sylwester. "Get logged-in user username and groups with Python." From sWWW - Code For The Web . https://swww.com.pl//main/index/get-logged-in-user-username-and-groups-with-python
Add Comment