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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
| #!/usr/bin/env sh
#
# Name: addDB
#
# Description: This is a script to create a database and user of the same
# name on a given host. It returns a generated password to
# standard out.
#
# Synopsis: addDB dbname [-P port] [-a dbadmin] [-d dbhost] [-n dbuser] [-m userhost] [-h help]
#
# Notes: The password generated may not be strong, see:
# "Analysis of the Linux Random Number Generator
# www.cs.huji.ac.il/~reinman/GuttermanPinkasReinman2006.pdf
#
# Copyright: Anntoin Wilkinson (2013)
help()
{
echo >&2 "usage: $0 dbname [-P port] [-a dbadmin] [-d dbhost] [-n dbuser] [-m userhost] [-h help]"
exit 1
}
# Creates the database and user and grants that user the required privileges
createdb()
{
mysql -h$DBHOST -P$PORT -u$DBADMIN -p <<COMMANDS
CREATE DATABASE $DBNAME;
CREATE USER $DBUSER@$USERHOST IDENTIFIED BY '$DBPASSWORD';
GRANT ALL PRIVILEGES ON $DBNAME.* TO $DBUSER@$USERHOST WITH GRANT OPTION;
COMMANDS
}
# Variables with default values
if [ $1 ]; then
DBNAME=$1
else
help
fi
PORT=3306
DBADMIN=root
DBHOST=localhost
DBUSER=$DBNAME
USERHOST=localhost
DBPASSWORD=`cat /dev/urandom | tr -cd [:alnum:] | head -c 12`
# Handle Option flags
OPTIND=2
while getopts P:a:d:n:m:h opt
do
case "$opt" in
P) PORT="$OPTARG";;
a) DBADMIN="$OPTARG";;
d) DBHOST="$OPTARG";;
n) DBUSER="$OPTARG";;
m) USERHOST="$OPTARG";;
h) help;;
\?) # unknown flag
help;;
esac
done
echo "MySQL will request your admin password."
if createdb; then
echo "The password for the db $DBNAME is '$DBPASSWORD' (minus quotes)"
echo "Note: This password will be visible in your shell history unless removed"
else
echo "MySQL returned a non-zero exit status. The database was probably not created"
fi
|