There is os.getuid() which "Returns the current process’s user id.". But how do I find out any given user's id?
Try creating a User where User.id = None. It should take the next available id. If it is autoincrementing, after inserting the User the correct id will be placed in the User.id.
UID stands for user identifier. A UID is a number assigned to each Linux user. It is the user’s representation in the Linux kernel. The UID is used for identifying the user within the system and for determining which system resources the user can access. This is why the user ID should be unique. You can find UID stored in the /etc/passwd file.
You can either simply type the “ id ” in the terminal or use the username with the “ id ” command as mentioned below: The “ getent ” command in UNIX and Linux-like systems is used to fetch the entries from a system database supported by NSS (Name Service Switch) libraries. The user details have been stored in the passwd and group databases.
Another case might occur if the user is connected remotely on a server and needs a quick response to get details of the logged-in username. In Linux distributions, we have multiple commands that help to find the user ID very quickly: The id command is the simplest way to display a list of real and effective users, and it also shows the group IDs.
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.
You could use pwd.getpwnam()
:
In [5]: pwd.getpwnam('aix').pw_uid Out[5]: 1004
Assuming what you want is the username string associated with the userid for your program, try:
import os import pwd pwd.getpwuid( os.getuid() ).pw_name
Use os.geteuid() to get the effective uid instead, if that difference matters to you.
Use pw_gecos instead of pw_name to get the "real name" if that's populated on your system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With