1. 程式人生 > >shell指令碼實現msyql5.7全自動安裝

shell指令碼實現msyql5.7全自動安裝

#! /bin/bash
#coding=utf-8
set -e
#auto instiall mysql for 5.7

userdir=/usr/local
basedir=/data/server/mysql3306
port=3306
socket=/tmp/mysql3306.sock
newpwd="123456"
tarfile="mysql-5.7.19-linux-glibc2.12-x86_64.tar.gz"
#------------------------------------------------------------------

tarfiledir="${tarfile%.tar.gz*}"
realpath=$(readlink -f "$0")
realdir=$(dirname "$realpath")

logfile=${realdir}/mysql_install.log
true > ${logfile}

#adduser
mkdir -p ${userdir}

result_user=$(id mysql)
if [ -z "$result_user" ]
then
	groupadd mysql
	useradd -g mysql -M  -s /sbin/nologin mysql
	echo "create user mysql by this script" >> ${logfile}
else
	echo "user mysql has been created before run this script" >> ${logfile}
fi

#init dir

cd "${realdir}"
wget https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.19-linux-glibc2.12-x86_64.tar.gz
if [ ! -d ${tarfiledir} ]
then
tar -zxvf ${tarfile}
fi
if [ ! -d "${basedir}" ] 
then

mkdir -p ${basedir}
cp -r ${tarfiledir}/*  ${basedir}/
fi

mkdir -p ${basedir}/{data,tmp,logs}
cd ${userdir}
ln -sf ${basedir} mysql
chown -R mysql:mysql ${basedir}
ip=$(/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:")
lastip=${ip##*.}
#init mysql
cat > /etc/my.cnf << EOF
[mysql]
socket=${socket}
[mysqld]
server_id=${lastip}${port}
user=mysql
socket=${socket}
port=${port}
basedir=${basedir}
datadir=${basedir}/data
log_bin=${basedir}/logs/binlog
log_error=${basedir}/logs/error
tmpdir=${basedir}/tmp

EOF

${basedir}/bin/mysqld --defaults-file=/etc/my.cnf --initialize && echo "init mysql successful"

#add mysql to server
\cp -f ${basedir}/support-files/mysql.server /etc/init.d/mysql

result_grep_path="$( grep   "${basedir}/bin" /etc/profile  )" || result_grep_path=""
if [ -z "${result_grep_path}" ]
then
	echo "export PATH=\$PATH:${basedir}/bin" >> /etc/profile ;
	source /etc/profile
fi
#start mysql server
service mysql start
#update root's pwd
genpwd=$(cat ${basedir}/logs/error.err | grep "password is generated for [email protected]") || genpwd=""
oldpwd=${genpwd##*[email protected]: } 
#mysql -uroot -p${oldpwd} -e "alter user user() identified by \"${newpwd}\"";
cd ${realdir}
cat > tmp_expect.sh << EOF
#! /usr/bin/expect

spawn mysql -uroot -p
expect {
	"password" { send "${oldpwd}\n";exp_continue;}
	"mysql>" {send "alter user user() identified by \"${newpwd}\";\n"}
}
interact
EOF
chmod 755 ./tmp_expect.sh
expect ./tmp_expect.sh && rm -rf ./tmp_expect.sh && rm -rf ./mysql_install.log