#!/usr/bin/perl # see bottom of code for notes. use DBI; @ARGV > 0 or die "usage: $0 key value ...\n"; $user='root'; $pass=''; # set the password accordingly %fields; @cols; %params=@ARGV; # store the parameter pairs in a hash $/=';'; $dbh=DBI->connect('mysql',$user,$pass,'mysql'); die "connection failed\n" unless $dbh; # execute a query to retrieve the fields of the "user" table (permissions) $sth=$dbh->prepare("describe user;"); $sth->execute; $err=$sth->errstr; die "failed to describe the table, reason $err\n" if $err; # fetch rows (a column name at a time) while(@vals=$sth->fetchrow) { push(@cols,$vals[0]); # add column name to a list $fields{$vals[0]}='N'; # create a hash entry and default it # loop through the params trying to find a matching entry in # the hash. If found then redefine the hash key value to that # passed on the command line foreach $key (keys %params) { next unless $vals[0] =~ /^${key}/i; $fields{$vals[0]}=$params{$key}; } } $sth->finish; # check for and reset specific fields die "username must be specified\n" if $fields{'User'} eq 'N'; $fields{'Host'}='localhost' if $fields{'Host'} eq 'N'; $fields{'Password'}='' if $fields{'Password'} eq 'N'; # build an insert statement $"=","; $query="insert into user (@cols) values ("; foreach (@cols) { $query.="'$fields{$_}',"; } #replace the trailing ',' added in the loop with a ');' $query =~ s/(.*),$/$1\);/g; #print $query."\n"; # execute the built statement to insert a new row $sth=$dbh->prepare($query); $sth->execute; $err=$sth->errstr; die "Failed to insert into table, reason $err\n" if $err; $sth->finish; print "Insert completed\n"; # happy message $dbh->disconnect; # # add a user to the mysql permissions table # # example usage :- # # adduser user mark select y insert y update y # # parameters are key,value combinations. # params not passed are defaulted to N, # except Hostname which is defaulted to 'localhost' and # Password which is defaulted to '' (no password). # # key fields do not have to be complete but are anchored during the RE, thus # 'select', 'Sel' & 'select_priv' will all work, but 'elect' etc... will not. # # # NOTE: also remember to set the $pass scalar above to the correct password. # you could also change the $user one too if you have another user # with full permissions. # # Mark W J Redding # # please excuse any poor perl, this is only my second script since completing # a 4 day Perl training course with Learning Tree (thanx Derek G Jones @ scuna) #