多实例MySQL批量添加用户和密码并授权

时间:2021-04-14 06:37:44

OS:Cent OS 6.3

DB:5.5.14

如果一台服务器上有100个MySQL数据库实例,此时需要给不同端口的几个数据库添加用户名、密码并授权应用IP,一个个授权没问题,反正累的不是我,哇咔咔。

创建add_user.sh

#/bin/bash
#add user to mysql db

passpwd="yoon"

cat user.txt | while read user
do
  port=`echo $user |awk '{print $1 }'`
  username=`echo $user |awk '{print $2 }'`
  pwd=`echo $user |awk '{print $3 }'`
  db=`echo $user |awk '{print $4 }'`
#  echo 'port='$port';username='$username';pwd='$pwd';db='$db

/export/servers/mysql/bin/mysql -S /export/data/mysql/tmp/mysql$port.sock -uroot -p$passpwd <<EOF

use mysql;

GRANT  SELECT,INSERT,UPDATE,DELETE ON $db.* TO '$username'@'192.17.12.2' IDENTIFIED BY '$pwd';
GRANT  SELECT,INSERT,UPDATE,DELETE ON $db.* TO '$username'@'192.17.12.3' IDENTIFIED BY '$pwd';
GRANT  SELECT,INSERT,UPDATE,DELETE ON $db.* TO '$username'@'192.17.12.4' IDENTIFIED BY '$pwd';

flush privileges;

EOF

done

创建user.txt

2013     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k09kX  yoon
2014     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k10kX  yoon
2015     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k11kX  yoon
2016     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k12kX  yoon
2017     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k13kX  yoon
2018     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k14kX  yoon
2020     yoon_rw     WY811JnJTzcjjfZO..Ui_8Q8i8k15kX  yoon

[root@yoon ~]# sh  add_user.sh