【shell 每日一练6】初始化安装Mysql并修改密码
一、简单实现mysql一键安装
参考:【第二章】MySQL数据库基于Centos7.3-部署
此脚本前提条件是防火墙,selinux都已经设置完毕:
[root@web130 ~]# cat InstallMysql.sh #!/bin/bash #2018-09-04 #旅行者-Travel #卸载自带maridb yum -y remove mari* rm -rf /var/lib/mysql/*
#下载yum源 URL="https://repo.mysql.com//mysql80-community-release-el7-1.noarch.rpm" wget $URL -P /etc/yum.repos.d/
yum -y install yum-utils #如果没有该包,下边执行yum-config-manager不生效 yum -y install /etc/yum.repos.d/mysql80-community-release-el7-1.noarch.rpm yum-config-manager --disable mysql80-community yum-config-manager --enable mysql57-community yum -y install mysql-community-server systemctl start mysqld systemctl enable mysqld systemctl status mysqld if [ $? -eq 0 ];then echo -e "install succefull" fi
二、修改Mysql初始密码
1)由于mysql5.7初始化是有密码的,需要找到密码才能登陆,所以我们直接通过脚本修改密码,并实现登陆:
[root@web130 ~]# cat i.sh #!/bin/bash result="`grep 'temporary password' /var/log/mysqld.log|tail -n 1`" p1="`echo $result |awk '{print $NF}'`" read -p "请输入数据库密码:" num1 read -s -p "请输入数据库密码:" num2 if [ $num1 = $num2 ];then mysqladmin -uroot -p"$p1" password "$num1" echo "passwd change successful" mysql -uroot -p$num1 else
2)优化以上脚本实菜单操作:
[root@web130 ~]# cat ChangePasswd1.sh #!/bin/bash function init_passwd() { result="`grep 'temporary password' /var/log/mysqld.log`" p1="`echo $result |awk '{print $NF}'`" read -p "请输入数据库密码:" num1 read -s -p "请输入数据库密码:" num2 if [ $num1 = $num2 ];then mysqladmin -uroot -p"$p1" password "$num1" echo "passwd change successful" mysql -uroot -p$num1 else echo "两次输入密码不一致" exit 0 fi } function menu(){ cat<<EOF -----------主菜单----------------- 1)初始化数据库密码 2)登陆数据库 Q)退出 EOF read -p "请输入序号:" num3 case $num3 in 1) init_passwd ;; 2) mysql -uroot -p$num1 ;; Q|q) exit 0 ;; *) echo "-------请输入正确序号-------" menu esac } menu [root@web130 ~]#
可通过此脚本来登陆数据库效果如下图:
此脚本比较粗糙,纯属为了集群环境写,后期优化>>