2017년 3월 11일 토요일

Generate /etc/shadow PW hash from the cli using python2 and 3

In /etc/shadow, hashed and salted passwords are stored together with the user name as follows:

myuser:$6[someSaltedHash]:...

where the number following the $ can take the values 1~6 corresponding to the following hash algorithms:

1    md5
2a   Blowfish
2y   Blowfish with correct 8-bit char handling
5    sha-256
6    sha-512

Many How-to's on the Internet recommend using mkpasswd from the expect package, but I find it is much easier to use python2 or python3 to generate the salted hash.

Python 2:

python -c 'import crypt,getpass; print crypt.crypt(getpass.getpass())'

You will then be prompted to enter your plaintext password after which a /etc/shadow compatible hash will be output.


Python 3:

python3 -c 'import crypt; print(crypt.crypt("yourpw", crypt.mksalt(crypt.METHOD_SHA512)))'

In this snippet, you simply enter your plaintext password as an argument and then a /etc/shadow compatible hash will be printed out on the terminal.

You can copy-paste this salted hash into a Kickstart (RHEL and variants) or DI preseed file (Debian and variants) for automated installations.


References:

https://access.redhat.com/solutions/221403 (requires registration)

http://serverfault.com/questions/330069/how-to-create-an-sha-512-hashed-password-for-shadow