Created
July 31, 2013 13:02
-
-
Save janich/6121771 to your computer and use it in GitHub Desktop.
Export MySQL users and permissions
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 | |
/** | |
* Export MySQL users and permissions | |
* | |
* This script exports raw CREATE USER and GRANT queries of a given database | |
* to help migrate MySQL users and permissions to a new server. | |
* Users will keep their passwords across the migration. | |
* | |
* Warning: The import queries expects exactly the same database structure! | |
* | |
* This was made in 10 min a rainy afternoon. | |
* Usage is on your own responsibility! | |
* Feel free to improve it. | |
* | |
* @requires PHP 5.3+ | |
* @package ExportMySQLUsers | |
* @author Janich Rasmussen <[email protected]> | |
* @license http://www.dbad-license.org/ DBAD license | |
*/ | |
// Set up database root credentials | |
$host = 'localhost'; | |
$user = 'root'; | |
$pass = '--Insert Your Root Password Here And Delete It When You Are Done--'; | |
$port = 3306; | |
// ---- Do not edit below this ---- | |
// Misc settings | |
header('Content-type: text/plain; Charset=UTF-8'); | |
// Final import queries goes here | |
$export = array(); | |
// Connect to database | |
$link = new mysqli($host, $user, $pass, 'mysql', $port, 'mysql'); | |
// Test connection | |
if ($link->connect_error) | |
{ | |
printf('Connect failed (%s): %s', $link->connect_errno, $link->connect_error); | |
die(); | |
} | |
// Do this right! | |
$link->query('SET NAMES \'utf8\''); | |
// Get users from database | |
$result = $link->query('SELECT `User`, `Host`, `Password` FROM `user`'); | |
if ($result) | |
{ | |
while ($row = $result->fetch_row()) | |
{ | |
$user = $row[0]; | |
$host = $row[1]; | |
$pass = $row[2]; | |
$export[] = 'CREATE USER `'. $user .'`@`'. $host .'` IDENTIFIED BY `'. $pass .'`'; | |
// Fetch any permissions found in database | |
$result2 = $link->query('SHOW GRANTS FOR `'. $user .'`@`'. $host .'`'); | |
if ($result2) | |
{ | |
while ($row2 = $result2->fetch_row()) | |
{ | |
$export[] = $row2[0]; | |
} | |
} | |
} | |
} | |
$link->close(); | |
echo implode(";\n", $export); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this! I added password hash / auth_plugin support for this, as the password field is gone in version 5.6 of MySQL. https://gist.github.com/hackmods/88714fb81e998102b4052e7957e39ef2