Created
November 18, 2014 19:54
-
-
Save PEKTOP/9d2537c05eace70526f4 to your computer and use it in GitHub Desktop.
Create granted user for every mysql database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$dns = 'mysql:dbname=mysql;host=localhost'; | |
$db_user = 'root'; | |
$db_password = 'admin'; | |
$db_handler = new PDO($dns, $db_user, $db_password); | |
$statment = $db_handler->query('SHOW DATABASES'); | |
$dbs = $statment->fetchAll(); | |
$exclude_dbs = [ | |
'information_schema', | |
'mysql', | |
'performance_schema', | |
'phpmyadmin', | |
]; | |
$stack = []; | |
foreach($dbs as $db) { | |
if ( ! in_array($db['Database'], $exclude_dbs)) { | |
$pwd = randomPassword(); | |
$db_handler->query( | |
'CREATE USER \''. | |
$db['Database']. | |
'\'@\'localhost\' IDENTIFIED BY \''. | |
$pwd.'\''); | |
print("\nUser {$db['Database']} created with password '{$pwd}'."); | |
$db_handler->query( | |
'GRANT ALL PRIVILEGES ON '. | |
$db['Database']. | |
'.* TO \''. | |
$db['Database']. | |
'\'@\'localhost\''); | |
print("\nAll privileges granted for '{$db['Database']}'.*.\n\n"); | |
$stack[] = [ | |
'username' => $db['Database'], | |
'password' => $pwd, | |
]; | |
} | |
} | |
$db_handler->query('FLUSH PRIVILEGES'); | |
print("Privileges flushed. Finish!\n"); | |
file_put_contents('user_password.json', json_encode($stack)); | |
print("Saved to 'user_password.json' file.\n\nDone.\n\n"); | |
function randomPassword() { | |
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789"; | |
$pass = array(); //remember to declare $pass as an array | |
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache | |
for ($i = 0; $i < 8; $i++) { | |
$n = rand(0, $alphaLength); | |
$pass[] = $alphabet[$n]; | |
} | |
return implode($pass); //turn the array into a string | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment