Python Function to Check UNIX Passwords


To verify UNIX password, we should use the crypt module. It has crypt(3) routine. It is basically one-way hash function based on the modified DES algorithm.

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

import crypt

Method crypt.crypt(word, salt)

This method takes two arguments. The first one is the word and second one is salt. The word is basically the user password, which is given in the prompt. The salt is a random string. It is used to perturb the DES Algorithm in one of 4096 ways. The salt contains only Upper-case, Lower-case, Numeric values and ‘/’, ‘.’ characters.

This method returns a hashed password as string.

Example Code

import crypt, getpass, spwd
def check_pass():
   username = input("Enter The Username: ")
   password = spwd.getspnam(username).sp_pwdp
   if password:
      clr_text = getpass.getpass()
      return crypt.crypt(clr_text, password) == password
   else:
      return 1
        
if check_pass():
   print("The password matched")
else:    
   print("The password does not match")

Output

(Run this Program with root level permission)

$ sudo python3 example.py
Enter The Username: unix_user
Password:
The password matched

Updated on: 30-Jul-2019

468 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements