4

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?

ScotchAndSoda
  • 3,811
  • 4
  • 34
  • 38

2 Answers2

2

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

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • Thanks, for your reply, spwd does it. I had inadvertently tried spwd as normal user, but not as root, so I got sp_pwd=[], which makes sense. – ScotchAndSoda Nov 25 '12 at 16:37
  • Which is the password here in the tuple? Can I read that password as string? or how to convert that to string? – veeresh patil May 06 '21 at 03:48
0

A search on google for the terms "python" and "shadow" returns the spwd library as first result.

Since shadow passwords were introduced to prevent normal users from brute force attacking the password file, you will only be able to access the shadowed passwords using a privileged user account like root.

Christian Thieme
  • 1,114
  • 6
  • 6