How to get Users of Windows/Linux Systems using Python?
Hello Geek! In this article, we will use Python to get the current users on the Windows and Linux Systems.
The method that we are going to use to get the current users is users(). It is defined in the psutil Library. Therefore syntax of the function will be
The function psutil.users() returns all the users that are connected to the System. It returns the users as a list of named tuples.
Each tuple has the name, terminal, host, started and pid as its attributes. The attribute name gives us the username.
First, import the psutil Python Library to access the users() method.
Now, use the method psutil.users() method to get the list of users as a named tuple and assign to the variable user_list.
Implement a print statement to display that we are going to print the usernames of the users associated with the System.
Iterate over the list of users using a for a statement as the variable user.
Now, under the for loop, we can get the username from the named tuple as user.name and assign it to the variable username.
Now, print the variable username using a print statement.
user_list = psutil.users() print("Users associated with this System are :") for user in user_list: username = user.name print(username)
Users associated with this System are : Guthas
Hurrah! We have successfully obtained the username of all the users associated with the System using simple lines of code in Python.
Thank you for reading this article. I hope this article helped you in some way. Also do check out our other related articles below:
- How to Find and List All Running Processes in Python
- Python Program to get IP Address of your Computer