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
0pw_name
The Login Name or the username of the user
1pw_passwd
The Encrypted password
2pw_uid
Numeric ID for the user
3pw_gid
Numeric ID for the user’s group
4pw_gecos
Name of the user and comment field
5pw_dir
Home directory of the user
6pw_shell
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)

Output

$ python3 example.py
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
…….
…….
…….
raja
Published on 31-Oct-2018 12:31:45
Advertisements