shell脚本创建MySQL数据库、远程主机连接的用户名与密码

发布时间:2020-08-07编辑:脚本学堂
本文分享一段shell脚本,用来创建mysql数据库,远程主机连接的用户名与密码、数据库用户权限等。有需要的朋友参考下吧。

以下脚本用来创建mysql数据库,包括远程主机连接的用户名、密码。

代码:
 

复制代码 代码示例:
#!/bin/bash
# shell脚本,创建 mysql数据库、用户名、密码。
# 也可以同时添加用户权限。
#-----------------------------
_db="$1"
_user="$2"
_pass="$3"
_dbremotehost="$4"
_dbrights="$5"
 
## Path to mysql bins ##
mysql="/usr/bin/mysql"
## Mysql root settings ##
_madminuser='root'
_madminpwd='MySQL-PassWord'
_mhost='localhost'
 
# make sure we get at least 3 args, else die
[[ $# -le 2 ]] && { echo "Usage: $0 'DB_Name' 'DB_USER' 'DB_PASSORD' ['remote1|remote2|remoteN'] ['DB_RIGHTS']"; exit 1; }
 
# fallback to ALL rights
[[ -z "${_dbrights}" ]] && _dbrights="ALL"
 
# build mysql queries
_uamq="${mysql} -u "${_madminuser}" -h "${_mhost}" -p'${_madminpwd}' -e 'CREATE DATABASE ${_db};'"
_upermq1="${mysql} -u "${_madminuser}" -h "${_mhost}" -p'${_madminpwd}' -e "GRANT ${_dbrights} ON ${_db}.* TO ${_user}@localhost IDENTIFIED BY '${_pass}';""
 
# run mysql queries
$_uamq
$_upermq1
 
# read remote host ip in a bash loop
# build queires to grant permission to all remote webserver or hosts via ip using the same username
IFS='|'
for  i in ${_dbremotehost}
do
 _upermq2="${mysql} -u "${_madminuser}" -h "${_mhost}" -p'${_madminpwd}' -e "GRANT ${_dbrights} ON ${_db}.* TO ${_user}@${i} IDENTIFIED BY '${_pass}';""
 $_upermq2
done

脚本使用方法:

1,创建数据库test_db,用户名test123,密码123456
 

复制代码 代码示例:
./script.sh test_db test123 123456

2,创建数据库test_db,用户名test123,密码123456,而且只允许 192.168.1.5 and 192.168.1.11连接:
 

复制代码 代码示例:
./script.sh test_db test123 123456 '192.168.1.5|192.168.1.11'

3,创建数据库test_db,用户名test123,密码123456,仅允许192.168.1.5 & 192.168.1.11连接,仅权限仅限于:grant SELECT,INSERT,UPDATE,DELETE:
 

复制代码 代码示例:
./script.sh test_db test123 123456 '192.168.1.5|192.168.1.11' 'SELECT,INSERT,UPDATE,DELETE'