【MySQL 5.7】SHELL脚本监控主从复制的状态之最小权限用户
xixuefeng
MySQL-DEV, Shell
2021-04-25 19:25:21
972 次浏览
【MySQL 5.7】SHELL脚本监控主从复制的状态之最小权限用户已关闭评论
MySQL有两种登录方式socket与TCP,当要对数据库通过脚本进行监控的时候,难免会用到账号和密码,那么socket是一种非常好的方式。
但如果socket登录存在问题,那么也可以通过账号密码登录。
场景:MySQL5.7 一套主从复制的数据库,从库定时监控主从复制的状态是否正常,通过定时执行脚本的方式执行show slave status命令监控。
实现:通过最小权限的方式实现
1:创建最小权限用户
1 2 |
mysql> grant replication client on *.* to 'monitor'@'localhost' identified by 'monitor'; mysql> |
2:脚本中执行show slave status命令如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/bin/sh filename=mcheck_$(date "+%Y%m%d").log dir=/data/shell/logs/ # 我们可以看到,下面填写了账号和密码 slave_is=($(mysql -umonitor -pmonitor -e "show slave status\G"|grep "Slave_.*_Running" |awk '{print $2}')) BTime="Begin:"$(date +"%Y-%m-%d %H:%M:%S") running="Slave is running "$(date -d "1 minute " +"%Y-%m-%d %H:%M:%S") notrunning="Slave is not running "$(date -d "1 minute " +"%Y-%m-%d %H:%M:%S") if [ "${slave_is[0]}" = "Yes" -a "${slave_is[1]}" = "Yes" ]; then r="$running" else r="$notrunning" fi echo $r >> $dir$filename |
3:执行结果,我们希望看到的结果没问题,但是多出来一行Warning,原因是,脚本中包含了账号和密码
1 2 3 4 |
[root@xxf scirpts]# sh mysql_sync_check.sh mysql: [Warning] Using a password on the command line interface can be insecure. Begin:2021-04-25 19:16:33 Slave is running 2021-04-25 19:17:33 End:2021-04-25 19:16:33 [root@xxf scirpts]# |
4:解决此问题,首先删除脚本中的账号和密码
1 2 3 |
……略…… slave_is=($(mysql -e "show slave status\G"|grep "Slave_.*_Running" |awk '{print $2}')) ……略…… |
5:然后,修改/etc/my.cnf
1 2 3 4 |
# 增加或修改client,添加账号和密码的参数 [client] user = monitor password = monitor |
6:重启数据库
1 2 3 4 |
[root@xxf scirpts]# service mysql restart Shutting down MySQL... SUCCESS! Starting MySQL.. SUCCESS! [root@xxf scirpts]# |
7:测试,已无警告
1 2 3 |
[root@sq1332---mysql scirpts]# sh mysql_sync_check.sh Begin:2021-04-25 19:22:24 Slave is running 2021-04-25 19:23:24 End:2021-04-25 19:22:24 [root@sq1332---mysql scirpts]# |
小结:
虽然在参数文件中添加了账号和密码,但由于该用户的权限非常小,所以,并没有什么影响。