summaryrefslogtreecommitdiffstats
path: root/new-mysql-user.pl
blob: 555cefde9802e07c9cc883e671e4425a9dd832a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
use File::Basename;

if (@ARGV != 1) {
  print "usage: ", basename($0), " <username>\n";
  exit 1;
}

sub random_string {
	my $length = shift;
	my @chars = ("A".."Z", "a".."z", 0..9);
	my $string;
	$string .= $chars[rand @chars] for 1..$length;
	return $string;
}

my $user = $ARGV[0];
my $password = random_string(15);

my @dsn = ('DBI:mysql:mysql_read_default_file='.$ENV{HOME}.'/.my.cnf');
my $db = DBI->connect(@dsn) || exit 1;

my $result;

$db->do("CREATE USER '$user'\@'localhost' IDENTIFIED BY '*';");
$db->do("GRANT USAGE ON *.* TO '$user'\@'localhost' IDENTIFIED BY '$password' WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;");
$db->do("CREATE DATABASE IF NOT EXISTS `$user`;");
$db->do("GRANT ALL PRIVILEGES ON `$user`.* TO '$user'\@'localhost';");
$db->do("GRANT ALL PRIVILEGES ON `${user}_%`.* TO '$user'\@'localhost';");
$db->disconnect();
print "Password for user $user: $password\n";