Access to the Password Database in Python

PythonProgrammingServer Side Programming

To access the password database, we should use the pwd module. Using this module, we can access users account and password database. The password database entries are like tuple like object.

To use the pwd module, we should import it using.

import pwd

The attributes of the password database are −

IndexAttribute & Description
The Login Name or the username of the user
The Encrypted password
Numeric ID for the user
Numeric ID for the user’s group
Name of the user and comment field
Home directory of the user
User’s Command interpreter.

Note − Generally, the pw_passwd holds the encrypted passwords. But in the new systems, they use the shadow password system. So now, in the pw_passwd, we can find ‘*’ or ‘x’ symbol only.

Some methods of this module are −

Method pwd.getpwuid(uid)

This method will return the password database entry for the given numeric user ID.

Method pwd.getpwnam(name)

This method will return the password database entry for the given user name.

Method pwd.getpwall()

This method will return the all password database entry.

Example Code

 Live Demo

import pwd
print("Root: " + str(pwd.getpwnam('root')) + '\n') #Password detail for root
for entry in pwd.getpwall():
   print("Name: " + entry[0] + "\t\tShell: " + entry.pw_shell)


$ python3
Root: pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root', pw_dir='/root', pw_shell='/bin/bash')

Name: root       Shell: /bin/bash
Name: daemon       Shell: /usr/sbin/nologin
Name: bin       Shell: /usr/sbin/nologin
Name: sys       Shell: /usr/sbin/nologin
Name: sync       Shell: /bin/sync
Name: games       Shell: /usr/sbin/nologin
Name: man       Shell: /usr/sbin/nologin
Published on 31-Oct-2018 12:31:45