Search code examples
pythoncryptpwd

python, get encrypted user password from shadow


I'm trying to obtain the encrypted system user password in order to compare it with another sha512 encrypted one. I tried pwd, but it seems that this module does not deal with user passwords, or the used system is "too modern" for it (a debian squeeze). Here's what I obtain:

import pwd
username = 'root' #or another user
pwd_struct = pwd.getpwnam(username)
print pwd_struct

>>>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')

where pw_passwd='x' and not a sha512 string.

Intended to use this with the python crypt module (example here), I got the exception "Sorry, currently no support for shadow passwords", which is normal, as my pw_passwd = 'x'.

Is there another proper method to obtain hashed passwords, or I should white my own parser for /etc/shadow?


Solution

  • Try the spwd module

    Platforms: Unix

    New in version 2.5.

    This module provides access to the Unix shadow password database. It is available on various Unix versions.

    You must have enough privileges to access the shadow password database (this usually means you have to be root).

    Shadow password database entries are reported as a tuple-like object, whose attributes correspond to the members of the spwd structure (Attribute field below, see ):

    >>> import spwd
    >>> spwd.getspnam('root')
    spwd.struct_spwd(sp_nam='root', sp_pwd='!', sp_lstchg=15238, sp_min=0, sp_max=99999, sp_warn=7, sp_inact=-1, sp_expire=-1, sp_flag=-1)
    

    Remember, you need to have read permission of /etc/shadow for this to work