Generate MySQL Password Hash using Python
In this post I am showing how to use generate a MySQL 5 password-hash that can be used to create MySQL GRANTS using a hash instead of a password.
To use a password-hash to create GRANTs:
GRANT ALL ON *.* to user@% identified by PASSWORD '';
A good use case is the Puppet puppetlabs-mysql module to automate the MySQL environment, You can automate/define USER and GRANT creation by using the code below, but notice that it requires a password-hash instead of a password:
users => {
'someuser@localhost' => {
ensure => 'present',
max_connections_per_hour => '0',
max_queries_per_hour => '0',
max_updates_per_hour => '0',
max_user_connections => '0',
password_hash => '*F3A2A51A9B0F2BE2468926B4132313728C250DBF',
},
}
OR:
mysql_user { 'root@127.0.0.1':
ensure => 'present',
max_connections_per_hour => '0',
max_queries_per_hour => '0',
max_updates_per_hour => '0',
max_user_connections => '0',
password_hash => '*F3A2A51A9B0F2BE2468926B4132313728C250DBF',
}
They recommend using mysql_password() for creating such a hash. But that means you need to have a MySQL server available. In this post I am writing about getting those hashes using Python, I wrote a program/script to get the password-hash programatically.
The Python program/script can be found at: https://github.com/parcejohn/mysql_password_hash
Usage
$ ./mysql_password_hash -h
usage: mysql_password_hash [-h] [-p PASSWORD | -r] [-l PASSWORD_LENGTH]
MySQL Password Hash Generator
optional arguments:
-h, --help show this help message and exit
-p PASSWORD, --password PASSWORD
Enter a password
-r, --generate_random
Generate a random password
-l PASSWORD_LENGTH, --password_length PASSWORD
# Using Command line arguments - User provided password (e.g. ‘secret’)
$ mysql_password_hash -p secret
PASSWORD: secret
HASH: *14e65567abdb5135d0cfd9a70b3032c179a49ee7
# Using Command line arguments - Random password with length=20 (default length=12)
$ mysql_password_hash -r -l 20
PASSWORD: gnlrn96^g18jcblmssa6
HASH: *e3cbe60709e8abe2082c92cc5e72a762d5f18e22
# interactive mode (no arguments)
mysql_password_hash