Python pwd Module

Learn how to use the Python pwd module on Unix/Linux systems. See examples for pwd.getpwnam(), pwd.getpwuid(), pwd.getpwall(), struct_passwd fields, current user lookup, Windows availability, and common errors.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python pwd Module

The pwd module reads Unix user account records from the password database. On Linux and other Unix systems, it is useful when you need a username, UID, GID, home directory, or login shell.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


Quick answer: look up a Unix user in Python

Use pwd.getpwnam("username") to get a user by name. Use pwd.getpwuid(uid) to get a user by UID. Use pwd.getpwall() to list available password database entries. The pwd module is Unix-specific and is not available on Windows.

python
import pwd

entry = pwd.getpwnam("root")
print(entry.pw_name, entry.pw_uid, entry.pw_dir)
Output

This prints the login name, UID, and home directory for root. On your system the UID is typically 0.


Python pwd module quick reference

Task Use
Import module import pwd
Get user by username pwd.getpwnam("root")
Get user by UID pwd.getpwuid(0)
Get all users pwd.getpwall()
Get username from result entry.pw_name
Get UID entry.pw_uid
Get GID entry.pw_gid
Get home directory entry.pw_dir
Get login shell entry.pw_shell
Get current user by UID pwd.getpwuid(os.getuid())
Portable current username getpass.getuser()
Current working directory os.getcwd() or Path.cwd()
Windows support Not available on Windows

What is the Python pwd module?

pwd is a Unix-specific standard library module. It provides read-only access to the Unix password database and returns user account information. It does not return plain-text passwords.

Use it in system scripts, Linux administration tasks, file ownership logic, and account lookup workflows. The Python pwd documentation describes entries as tuple-like struct_passwd objects with fields such as login name, UID, GID, home directory, and command interpreter.


Is the pwd module available on Windows?

No. pwd is Unix-specific and is not available on Windows. Importing it on Windows raises ModuleNotFoundError.

For a portable current username, use getpass.getuser(). The getpass documentation checks common environment variables and falls back to pwd only on systems that support it.

For cross-platform code, guard Unix-only imports:

python
import sys

if sys.platform == "win32":
    print("pwd is not available on Windows")
else:
    import pwd
    print(pwd.getpwnam("root").pw_name)
Output

pwd module vs shell pwd command

The Python pwd module reads Unix user account records. The shell pwd command prints the current working directory. They are unrelated despite the similar name.

In Python, use os.getcwd() or Path.cwd() for the current directory:

python
import os
from pathlib import Path

print(os.getcwd())
print(Path.cwd())
Output

See Python get home directory for home-path lookups.


Import the pwd module

python
import pwd
Output

No pip install is needed on supported Unix systems. On unsupported platforms, import pwd raises ModuleNotFoundError.


pwd.struct_passwd fields

Field Meaning
pw_name Login name
pw_passwd Password field placeholder or optional encrypted password
pw_uid Numeric user ID
pw_gid Numeric group ID
pw_gecos User name or comment field
pw_dir Home directory
pw_shell User command interpreter

Modern Unix systems usually store password hashes in shadow files. pw_passwd commonly contains x or * and should not be treated as the actual password. The Python docs note this shadow-password behavior explicitly.

python
import pwd

entry = pwd.getpwnam("root")
print(entry.pw_name)
print(entry.pw_uid)
print(entry.pw_gid)
print(entry.pw_dir)
print(entry.pw_shell)
Output

Avoid logging or printing pw_passwd in application output.


Get user information by username using getpwnam()

Use pwd.getpwnam(name) to look up a user by login name. It returns a struct_passwd object. If the username does not exist, Python raises KeyError.

python
import pwd

entry = pwd.getpwnam("root")

print(entry.pw_name)
print(entry.pw_uid)
print(entry.pw_gid)
print(entry.pw_dir)
print(entry.pw_shell)
Output

Use entry.pw_dir when you need a user's home directory path in a script.


Get user information by UID using getpwuid()

Use pwd.getpwuid(uid) to look up a user by numeric UID. This is useful with os.getuid(), os.geteuid(), or file ownership metadata.

python
import pwd

entry = pwd.getpwuid(0)

print(entry.pw_name)
print(entry.pw_uid)
print(entry.pw_dir)
Output

If the UID does not exist in the password database, Python raises KeyError.


Get current user details

Use os.getuid() for the current real UID on Unix. Use pwd.getpwuid(os.getuid()) to map that UID to full account information. Use os.geteuid() when the effective user ID matters.

python
import os
import pwd
import getpass

entry = pwd.getpwuid(os.getuid())

print(entry.pw_name)
print(entry.pw_dir)
print(getpass.getuser())
Output

For only the login name in portable code, prefer getpass.getuser() over os.getlogin(). The os.getuid() documentation applies on Unix systems.


List all users using getpwall()

pwd.getpwall() returns a list of available password database entries. The order is arbitrary.

python
import pwd

users = pwd.getpwall()

for entry in users[:5]:
    print(entry.pw_name, entry.pw_uid)

print(f"Total entries: {len(users)}")
Output

Useful for reporting or filtering system accounts. Avoid printing sensitive fields unnecessarily.


getpwnam() vs getpwuid() vs getpwall()

Function Input Output Best for
pwd.getpwnam() username struct_passwd Lookup user by name
pwd.getpwuid() UID struct_passwd Lookup user by numeric ID
pwd.getpwall() none list of struct_passwd List or filter users

Handle KeyError with pwd lookups

getpwnam() raises KeyError when the username is missing. getpwuid() raises KeyError when the UID is missing. Catch KeyError when input comes from users, config files, or command-line arguments.

python
import pwd

username = "no_such_user"

try:
    entry = pwd.getpwnam(username)
except KeyError:
    print(f"User not found: {username}")
else:
    print(entry.pw_uid)
Output

The Python pwd docs state that KeyError is raised when the requested entry cannot be found.


Common use cases for the pwd module

  • Get a Unix user's home directory.
  • Convert UID to username.
  • Convert username to UID.
  • Check a user's login shell.
  • Filter service or system accounts from getpwall().
  • Build Linux administration or audit scripts.
  • Combine with the grp module to resolve group data, or use Python subprocess when you need to run account-related shell commands.

pwd module and file ownership

pwd resolves UID to username. Use os.stat() to read a file owner's UID, then map it with getpwuid().

python
import os
import pwd
from pathlib import Path

path = Path("/etc/passwd")
stat_result = path.stat()
owner = pwd.getpwuid(stat_result.st_uid)

print(path)
print(owner.pw_name)
print(stat_result.st_uid)
Output

For more on stat() metadata, see get file size in Python, which also uses os.stat_result.


pwd module limitations

  • Unix-only; not available on Windows.
  • Read-only; cannot create, delete, or modify users.
  • Does not change passwords.
  • Does not return real plain-text passwords.
  • Database content depends on OS and NSS configuration.
  • Some fields may be placeholders or empty values.
  • LDAP, SSSD, or other directory services may influence lookup results on Linux.

Security notes

  • Do not log pw_passwd.
  • Do not assume pw_passwd contains a usable password hash.
  • Do not expose full user database output in web apps or APIs.
  • Run scripts with least privilege.
  • For password input, use getpass.getpass(), not pwd.

Normal getpwnam() and getpwuid() lookups usually do not require root on typical Linux systems.


Summary

The pwd module reads Unix password database entries. Use getpwnam() for username lookup, getpwuid() for UID lookup, and getpwall() to list available entries. It is Unix-only and not available on Windows. Use os.getcwd() or Path.cwd() for the current working directory, not pwd. Use getpass.getuser() when you need a portable current username.


References


Frequently Asked Questions

1. What does the Python pwd module do?

pwd provides read-only access to Unix password database entries. It returns username, UID, GID, home directory, shell, and related fields, not plain-text passwords.

2. Is the pwd module available on Windows?

No. pwd is Unix-specific. On Windows, importing pwd raises ModuleNotFoundError. Use getpass.getuser() for a portable current username.

3. What is the difference between pwd.getpwnam() and pwd.getpwuid()?

getpwnam() looks up a user by login name. getpwuid() looks up a user by numeric UID. Both return a struct_passwd object.

4. Does pwd return the real user password?

No. pw_passwd is usually a placeholder such as x or * because modern systems store password hashes in shadow files.

5. How do I get the current user with pwd?

On Unix, use pwd.getpwuid(os.getuid()). For portable code that only needs the login name, prefer getpass.getuser().

6. Is the Python pwd module the same as the shell pwd command?

No. The pwd module reads user account records. The shell pwd command prints the current working directory; in Python use os.getcwd() or Path.cwd().
Bashir Alam

Data Analyst and Machine Learning Engineer

Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and …