in reply to adding users to mysql db
It's got some pretty serious security problems. It's taking the root db password on the command line so it could end up snooped or in a publically viewable history file. You also aren't DB quoting the variables you're feeding to SQL which can be pretty dangerous. (Lots more and a stab at a redo of the code below.)
The connection file is one of the real beauties in MySQL. Instead of running the script as root, you might set up a user that has permission to fiddle with the mysql:user table and nothing else. Then give it a .my.cnf file that is set to 0600 or even 0400. Something like:
[client] password=shark!salad39 database=mysql
The cnf doesn't need to have the user b/c the user will be running the script so the ENV will know it.
To get auto quoting of your vars you should prepare the SQL with bindings instead. Though I couldn't get the ".*" through the binding correctly so I fudged it below. Maybe someone knows a trick with CONCAT or binding or something I don't know.
You're also not checking for reasonableness of new user, new db, and new password and you really should. Here's a stab at a redo but for something like this there are many DB GUIs and web interfaces that are really good that you might try instead.
use DBI; sub usage { my ( $script ) = $0 =~ m,([^\/]+)$,; print <<"MeMeMe"; ------------------------------------------------------------ USAGE: $script [DB] [new_user] [new_user_pswd] This is how this must be used. You didn't do it right! ------------------------------------------------------------ MeMeMe exit 0; } my $server = 'localhost'; my $db = 'mysql'; my $connect_file = '/Users/jinx/.my.users.cnf'; #my $connect_file = '/whatever/.my_user_master.cnf'; my $new_user_db = shift || usage(); my $new_user = shift || usage(); my $new_user_pw = shift || usage(); $new_user_db =~ /^\w+$/ or die "DB name is innappropriate!"; my $dbh = DBI->connect("dbi:mysql:database=$db:host=$server;" . "mysql_read_default_file=$connect_file;", undef, undef, {}, ); my $grant_local = $dbh->prepare(<<SQL); GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP ON $new_user_db.* TO ? IDENTIFIED BY ? SQL for my $sth ( $grant_local ) { $new_user .= '@localhost'; $sth->execute($new_user, $new_user_pw); $sth->finish(); } $dbh->disconnect(); exit 0;
|
|---|