mysql⾃动化安装脚本(⼆进制安装)
为了⽇后安装数据库⽅便,遂写了⼀个⾃动安装MySQL的脚本:
测试可以安装mariadb和MySQL-5.7.X
安装前配置好对应的myf⽂件放在/tmp路径下
将启动脚本mysql3306放在/usr/local/下
将安装包放在/usr/local路径下
安装⽅式为:./install_mysql.sh mysql-5.7.20 3306  # 第⼀个参数为数据库版本(格式统⼀),第⼆个参数为端⼝号,两个参数都可以根据⾃⼰情况修改
数据库启动/关闭为:service mysql3306 start/stop/restart/status
下⾯分别为安装脚本install_mysql.sh、启动脚本mysql3306、配置⽂件myf
#!/bin/bash
>>## Install MySQL>>##
export LANG=C
export LC_ALL=C                  #Set the LANG and all environment variable beginning with LC_ to C
typeset -r version=$1
typeset -r port=$2
# DEFINED VAR START
typeset -r softwaredir="/usr/local"
typeset -r basedir="/usr/local/mysql" #input version of server
typeset -r databasedir="/data/${port}"
typeset -r datadir="${databasedir}/data"
typeset -r logdir="${databasedir}/log"
typeset -r mysqluser="mysql"
typeset -r defaults_file="${databasedir}/myf"
typeset -r mysqldautostartfile="/etc/rc.d/init.d/mysql${port}"
typeset -r pidfile="${databasedir}/mysql.pid"
typeset -r socketlink="${databasedir}/mysql.sock"
typeset timestamp=''
typeset sInsDir_G=''
typeset sLogDir_G=''
typeset sLog_G=''
#DEFINED ENV START
export PATH=/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:$PATH
#DEFINED ENV END
## -------------------- init global vars -------------------
sInsDir_G=$( echo $(basename $0) | awk -F. '{print $1}' )
if [ -z "${sLog_G}" ]; then
sLog_G="/backup/SysMgtScripts/Log/${sInsDir_G}/$( hostname ).log"
fi
if [ -z "${sLogDir_G}" ]; then
sLogDir_G=${sLog_G%/*}
fi
if [ ! -d ${sLogDir_G} ]; then
mkdir -p ${sLogDir_G}
fi
## ---------------------------------------------------------
export sLog_G
export sLogDir_G
## ensure the directory structure exists
BASEDIR="/backup/SysMgtScripts/"
if [ ! -d $BASEDIR ]; then
mkdir -p ${BASEDIR}/Log
fi
## -------------------- colourful print --------------------
rMsg ()  { echo -e "\033[031;1m$@\033[0m"; }
gMsg ()  { echo -e "\033[032;1m$@\033[0m"; }
yMsg ()  { echo -e "\033[033;1m$@\033[0m"; }
## normal message print and log
LogMsg()
{
local timestamp=$( date '+%F %T' )
gMsg "[${timestamp}]: $*"
printf "[%s]:%s\n" "${timestamp}" "$*" >> "${sLog_G}"
}
# warning
Warn()
{
local timestamp=$( date '+%F %T' )
yMsg "[${timestamp}]: $*"
printf "[%s]:%s\n" "${timestamp}" "$*" >> "${sLog_G}"
}
# error
Error()
{
local retval=$?
local timestamp=$( date '+%F %T' )
rMsg "[${timestamp}]: $*"
printf "[%s]:%s\n" "${timestamp}" "$*" >> "${sLog_G}"
exit $?
}
#Check mysql user exit or not.
CheckUser(){
cat /etc/passwd |grep mysql &>/dev/null
if [ $? -ne 0 ];then
Warn "user ${mysqluser} not exist"
useradd ${mysqluser} || Error "Create MySQL user Failed"
else
LogMsg "user ${mysqluser} exist"
fi
}
#Create dir for database
InitDirs(){
list="${databasedir} ${datadir} ${logdir}"
for i in $list;
do
if  [ ! -d $i ];then
Warn "Missing directory $i "
mkdir -p $i || Error "Fail to create directory $i"
LogMsg "$i create successfully"
fi
Test_Owner_T=`ls -l -d $i |awk '{print $3}'`
if [[ "${Test_Owner_T}" != "${mysqluser}" ]];then
chown -R ${mysqluser}:${mysqluser} $i || Error "Fail to change the directory owner"    fi
done
}
InitEnv(){
bashrc="/etc/profile"
Test_Env_T=`cat ${bashrc} |grep "${basedir}"`
if [[ "${Test_Env_T}" != "" ]];then
LogMsg "${basedir} is already exists in ${bashrc}"
else
MYSQL_HOME=${basedir}
echo "MYSQL_HOME=${basedir}" >> ${bashrc} || Error "Fail to init environment"
echo "export PATH=\$PATH:${MYSQL_HOME}/bin" >> ${bashrc}
LogMsg "Add MYSQL_HOME to /etc/profile"
fi
source /etc/profile
}
SetMycnf(){
cp /tmp/myf ${defaults_file} || Error "Fail to create myf"
if [[ ! -f "/etc/myf" ]];then
LogMsg "The Parameter File is OK"
else
mv /etc/myf /etc/myf.bak
LogMsg "removed /etc/myf to /etc/myf.bak"
fi
}
UnzipPackages() {
Mysql_Package=`find ${softwaredir} -name ${version}*.`
if [[ ! -f ${Mysql_Package} ]];then
Error "MySQL Install Package is not found"
else
Mysql_File=`find ${softwaredir} -name ${version}*. -exec basename {} . \;`
if [[ ! -d "/usr/local/${Mysql_File}" ]];then
LogMsg "unzip MySQL Install Package"
tar xf ${Mysql_Package} -C ${softwaredir} || Error "Fail to unzip the Package"
else
LogMsg "No need to unzip"
fi
fi
}
InstallMysql(){
mysql下载starting the serverreallinkname=${basedir}
Mysql_File=`find ${softwaredir} -name ${version}*. -exec basename {} . \;`
if [[ ! -d ${Mysql_File} ]];then
LogMsg "It is unziping mysql install Package ..."
UnzipPackages
LogMsg "unzip successful"
fi
cd ${softwaredir}
if [[ ! -d ${basedir} ]];then
ln -s ${Mysql_File} ${reallinkname}
chown -R ${mysqluser}:${mysqluser} ${reallinkname}
fi
cd ${reallinkname}
result=$(echo ${version}|grep mariadb)
if [[ "$result" != "" ]];then
LogMsg "Install $"
./scripts/mysql_install_db --defaults-file=${defaults_file} >>/dev/null || Error "Fail to init MySQL"
else
LogMsg "Install $"
bin/mysqld --defaults-file=${defaults_file} --user=mysql --initialize-insecure --datadir=${datadir} --basedir=${basedir} >>/dev/null || Error "Fail to init MySQL"    bin/mysql_ssl_rsa_setup --datadir=${datadir}>>/dev/null
sleep 2
fi
}
MakeScript(){
if [[ ! -f /usr/local/mysql3306 ]];then
Error "start script file mysql3306 not found"
else
chmod u+x /usr/local/mysql3306
cp ${softwaredir}/mysql3306  ${mysqldautostartfile}
sed -i "0,/^basedir=/s@basedir=@basedir=${basedir}@" ${mysqldautostartfile}
sed -i "0,/^datadir=/s@datadir=@datadir=${databasedir}@" ${mysqldautostartfile}
fi
}
#start script
StartMySQL(){
service mysql${port} start || Error "MySQL start Failed"
}
# change mysql password
ChangePassword(){
mysql -S /data/${port}/mysql.sock -e "set password for root@localhost = password('123456');" || Error "Change root password Failed"
mysql -S /data/${port}/mysql.sock -uroot -p123456 -e "grant all privileges on *.* to root@'%' identified by '123456' with grant option;"
}
TaskMain(){
LogMsg "It is checking whether the mysqluser ready or not ..."
CheckUser
LogMsg "The mysqluser is ready"
LogMsg "It is initiazating directories ..."
InitDirs
LogMsg "The directories initiazating successful"
LogMsg "It is initiazating environment variables ..."
InitEnv
LogMsg "The environment variables initiazating successful"
LogMsg "It is setting default files ..."
SetMycnf
LogMsg "The default files set successful"
LogMsg "It is installing mysql database ..."
InstallMysql
LogMsg "the mysql database install successful"
LogMsg "It is making mysql start script ..."
MakeScript
LogMsg "make script successful"
LogMsg "It is starting mysql ..."
StartMySQL
LogMsg "successful"
LogMsg "It is changing mysql password ..."
ChangePassword
LogMsg "change successful"
LogMsg "The mysql service set successful"
}
# The execution body of the script
LogMsg "============Start Install MySQL============"
TaskMain $@;rc=$?
if [ ${rc} -ne 0 ] ;then
Error '[ERROR] Failed to install mysql.'
else
LogMsg '[INFO] Completed install mysql.'
fi
LogMsg "The script execution ends."
exit ${rc}
启动脚本:
#!/bin/sh
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB # This file is public domain and comes with NO WARRANTY of any kind
# MySQL daemon start/stop script.
# Usually this is put in /etc/init.d (at least on machines SYSV R4 based
# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.
# When this is done the mysql server will be started when the machine is
# started and shut down when the systems goes down.
# Comments to support chkconfig on RedHat Linux
# chkconfig: 23456436
# description: A very fast and reliable SQL database engine.
# Comments to support LSB init script conventions
### BEGIN INIT INFO
# Provides: mysql
# Required-Start: $local_fs $network $remote_fs
# Should-Start: ypbind nscd ldap ntpd xntpd
# Required-Stop: $local_fs $network $remote_fs
# Default-Start:  2345
# Default-Stop: 016
# Short-Description: start and stop MySQL
# Description: MySQL is a very fast and reliable SQL database engine.
### END INIT INFO
# If you install MySQL on some other places than /usr/local/mysql, then you
# have to do one of the following things for this script to work:
#
# - Run this script from within the MySQL installation directory
# - Create a /etc/myf file with the following information:
#  [mysqld]
#  basedir=/usr/local/mysql<path-to-mysql-installation-directory>
# - Add the above to any other configuration file (for example ~/.my.ini)
#  and copy my_print_defaults to /usr/bin
# - Add the path to the mysql-installation-directory to the basedir variable
#  below.
#
# If you want to affect other MySQL variables, you should make your changes
# in the /etc/myf, ~/.myf or other MySQL configuration files.
# If you change base dir, you must also change datadir. These may get
# overwritten by settings in the MySQL configuration files.
basedir=
datadir=
# Default value, in seconds, afterwhich the script should timeout waiting
# for server start.
# Value here is overriden by value in myf.
# 0 means don't wait at all
# Negative numbers mean to wait indefinitely
service_startup_timeout=900
# Lock directory for RedHat / SuSE.
lockdir='/var/lock/subsys'
lock_file_path="$lockdir/mysql"
# The following variables are only set for letting mysql.server find things.
# Set some defaults
mysqld_pid_file_path=
if test -z "$basedir"
then
basedir=/usr/local/mysql
bindir=/usr/local/mysql/bin
if test -z "$datadir"
then
datadir=/usr/local/mysql/data
fi
sbindir=/usr/local/mysql/bin
libexecdir=/usr/local/mysql/bin
else
bindir="$basedir/bin"
if test -z "$datadir"
then
datadir="$basedir/data"
fi
sbindir="$basedir/sbin"
libexecdir="$basedir/libexec"
fi
# datadir_set is used to determine if datadir was set (and so should be
# *not* set inside of the --basedir= handler.)
datadir_set=
#
# Use LSB init script functions for printing messages, if possible
#
lsb_functions="/lib/lsb/init-functions"
if test -f $lsb_functions ; then
. $lsb_functions
else
log_success_msg()
{
echo" SUCCESS! $@"
}
log_failure_msg()
{
echo" ERROR! $@"
}
fi
PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin"
export PATH
mode=$1    # start or stop
[ $# -ge 1 ] && shift
other_args="$*"  # uncommon, but needed when called from an RPM upgrade action
# Expected: "--skip-networking --skip-grant-tables"
# They are not checked here, intentionally, as it is the resposibility
# of the "spec"file author to give correct arguments only.
case `echo"testing\c"`,`echo -n testing` in
*c*,-n*) echo_n=  echo_c=    ;;
*c*,*)  echo_n=-n echo_c=    ;;
*)      echo_n=  echo_c='\c' ;;
esac
parse_server_arguments() {
for arg do
case"$arg"in
--basedir=*)  basedir=`echo"$arg" | sed -e 's/^[^=]*=//'`
bindir="$basedir/bin"
if test -z "$datadir_set"; then
datadir="$basedir/data"
fi
sbindir="$basedir/sbin"
libexecdir="$basedir/libexec"
;;
--datadir=*)  datadir=`echo"$arg" | sed -e 's/^[^=]*=//'`
datadir_set=1
;;
--pid-file=*) mysqld_pid_file_path=`echo"$arg" | sed -e 's/^[^=]*=//'` ;;
--service-startup-timeout=*) service_startup_timeout=`echo"$arg" | sed -e 's/^[^=]*=//'` ;; esac
done
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。

发表评论