Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Python and linux how to get given user's id [duplicate]

Tags:

python

linux

There is os.getuid() which "Returns the current process’s user id.". But how do I find out any given user's id?

like image 678
ren Avatar asked Oct 14 '11 15:10

ren


People also ask

How do you create a user ID in Python?

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.

What is a user ID in Linux?

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.

How to find a user’s name in Linux?

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.

How to quickly get the user ID of a user?

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.

How to get user usernames in psutil Python?

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.


2 Answers

You could use pwd.getpwnam():

In [5]: pwd.getpwnam('aix').pw_uid Out[5]: 1004 
like image 170
NPE Avatar answered Oct 11 '22 04:10

NPE


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.

like image 33
murphstein Avatar answered Oct 11 '22 05:10

murphstein