sh 创建MySQL数据库,dito用户和随机生成的密码。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh 创建MySQL数据库,dito用户和随机生成的密码。相关的知识,希望对你有一定的参考价值。

#!/bin/sh
# Tiny script to create a mysql user and database with same
# name. A random password is generated (yay!)
usage() {
    cat << __EOT
Usage: createmysqldb.sh <dbname>
   where <dbname> is the one-word name you'd like to use as database name and
   username if -u parameter is not set.

   Options:
   -u <username>: set a username different from the dbname
   -p <password>: set a custom password, if not set a random password is generated

__EOT
    exit 1
}
MYSQL=`which mysql`

if [ -z $MYSQL ]; then
     cat << __EOT
Error: there was no 'mysql' executable found.
If you have MySQL installed you have to make a symbolic link in '/usr/local/bin'
to the 'mysql' program located in the MySQL installation directory.

e.g.    $ ln -s /usr/local/mysql5.1.49/bin/mysql /usr/local/bin/mysql

__EOT
    exit 1
fi

PASSWORD=
USERNAME=
while getopts "u:p:" OPTION
do
    case $OPTION in
        u)
            USERNAME=$OPTARG
            ;;
        p)
            PASSWORD=$OPTARG
            ;;
        ?)
            usage
            ;;
    esac
done
shift $(($OPTIND - 1))

if [ -z $1 ]; then
    usage
fi

if [ -z $PASSWORD ]; then
    PASSWORD=`openssl rand -base64 16 | tr -d "="`
fi

if [ -z $USERNAME ]; then
    USERNAME=$1
fi

if [ ${#USERNAME} -gt 16 ]; then
    echo "Username is too long: ${#USERNAME} characters, limit is 16"
    exit 1
fi

Q1="CREATE USER '$USERNAME'@'localhost' IDENTIFIED BY  '$PASSWORD';"
Q2="GRANT USAGE ON *.* TO '$USERNAME'@'localhost' IDENTIFIED BY '$PASSWORD';"
Q3="CREATE DATABASE IF NOT EXISTS  \`$1\` CHARACTER SET utf8 COLLATE utf8_general_ci;"
Q4="GRANT ALL PRIVILEGES ON  \`$1\` . * TO  '$USERNAME'@'localhost';"
Q5="FLUSH PRIVILEGES;"
SQL="${Q1}${Q2}${Q3}${Q4}${Q5}"

$MYSQL -u root -p -e "$SQL"

if [ $? -eq 0 ]; then
cat << __EOT
Created database $1
Generated user "$USERNAME" with following password: "$PASSWORD"

__EOT
fi

以上是关于sh 创建MySQL数据库,dito用户和随机生成的密码。的主要内容,如果未能解决你的问题,请参考以下文章

sh Bash脚本:创建MySQL数据库和用户

MySql大批量生成测试数据

MySql大批量生成测试数据

mysql大批量生成测试数据

sh 用于创建MySQL数据库和用户的Shell脚本

sh 生成一个带有N行随机结构化数据的postgresql数据库