shell脚本——检索mysql数据库中得用户,如果没有就创建
#!/bin/bash #author: goujinyang set -e USER1=mysqlsi USER2=dbquery USER3=dboper USER4=yyzc USERS=($USER1 $USER2 $USER3 $USER4) USER_PASS=123123 # MySQL 用户名和密码 MYSQL_USER="root" MYSQL_PASSWORD="Root#123" #MYSQL_HOST="localhost" create(){ for USER in "${USERS[@]}"; do # 使用mysql命令和-sN选项(无输出,仅错误)检查用户是否存在 # 注意:这里假设你有足够的权限来执行SELECT语句 EXISTS=$(mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -h$MYSQL_HOST -sN -e "SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user='$USER')") # 检查用户是否存在(EXISTS查询将返回1或0) if [ "$EXISTS" -eq 0 ]; then # 用户不存在,创建用户 mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "CREATE USER '$USER'@'%' IDENTIFIED BY '$USER_PASS';" echo "用户 $USER 已创建" else echo "用户 $USER 已存在" fi done } grants(){ mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "grant all on *.* to '$USER1'@'%' with grant option;" mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "grant select,show view,process on *.* to '$USER2'@'%';" mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "grant select on *.* to '$USER3'@'%';" mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "grant select on *.* to '$USER4'@'%';" } create grants