Skip to content
Search

Python:pwd

lastmod 2021-06-29created 2021-06-284 edits

The password database

About

This module provides access to the Unix user account and password database. It is available on all Unix versions.

passwd

Password database entries are reported as a tuple-like object whose attributes correspond to the members of the passwd structure (Attribute field below, see <pwd.h>):

Index

Attribute

Meaning

0

pw_name

Login name

1

pw_passwd

Optional encrypted password

2

pw_uid

Numerical user ID

3

pw_gid

Numerical group ID

4

pw_gecos

User name or comment field

5

pw_dir

User home directory

6

pw_shell

User command interpreter

The uid and gid items are integers; all others are strings. KeyError is raised if the entry asked for cannot be found.

Example

os.setuid(uid) is used to change the process user ID; to look up the UID, use it as follows.

def drop_privileges():
    from certidude import config
    import pwd
    _, _, uid, gid, gecos, root, shell = pwd.getpwnam("certidude")
    restricted_groups = []
    restricted_groups.append(gid)

    # PAM needs access to /etc/shadow
    if config.AUTHENTICATION_BACKENDS == {"pam"}:
        import grp
        name, passwd, num, mem = grp.getgrnam("shadow")
        click.echo("Adding current user to shadow group due to PAM authentication backend")
        restricted_groups.append(num)

    os.setgroups(restricted_groups)
    os.setgid(gid)
    os.setuid(uid)
    click.echo("Switched %s (pid=%d) to user %s (uid=%d, gid=%d); member of groups %s" %
        (getproctitle(), os.getpid(), "certidude", os.getuid(), os.getgid(), ", ".join([str(j) for j in os.getgroups()])))
    os.umask(0o007)

See also

Favorite site

author Zer0 sitemap