Access to the Password Database in Python



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 −

Index Attribute & Description
0 pw_name
The Login Name or the username of the user
1 pw_passwd
The Encrypted password
2 pw_uid
Numeric ID for the user
3 pw_gid
Numeric ID for the user’s group
4 pw_gecos
Name of the user and comment field
5 pw_dir
Home directory of the user
6 pw_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
…….
…….
…….
Updated on: 2020-06-25T14:04:13+05:30

530 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements