导航

MySQL单机单实例安装脚本(转载)

Posted on 2019-03-25 17:33  许爱琪  阅读(275)  评论(0编辑  收藏  举报

说明:使用mysql generic tar.gz包快速安装mysql

三个文件installation_of_single_mysql.sh、template_install-my.cnf、mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz

修改脚本的配置信息指定template_install-my.cnf和mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz位置

默认root账号是iforogt

  • installation_of_single_mysql.sh
#!/bin/bash
# line:           V1.8
# mail:           gczheng@139.com
# data:           2018-09-04
# script_name:    installation_of_single_mysql.sh
# function:       Install mysql5.7.18

#=======================================================================
#配置信息
#=======================================================================
MYSQL_DATADIR=/data/mysqldata
MYCNF=template_install-my.cnf
MYSQL_SOURCE_PACKAGES=/software/mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz
MYSQL_SOURCE_PACKAGES_NAMES=`echo $MYSQL_SOURCE_PACKAGES |awk -F '/' '{print $NF}' |awk -F ".tar.gz" '{printf $1}'`
MYSQL_DOWNLOAD_LINK='http://mirrors.sohu.com/mysql/MySQL-5.7/mysql-5.7.18-linux-glibc2.5-x86_64.tar.gz'
MYSQL=/usr/local/mysql/bin/mysql

#=======================================================================
# echo添加颜色
#=======================================================================
echo_color(){
    color=${1} && shift
    case ${color} in
        black)
            echo -e "\e[0;30m${@}\e[0m"
            ;;
        red)
            echo -e "\e[0;31m${@}\e[0m"
            ;;
        green)
            echo -e "\e[0;32m${@}\e[0m"
            ;;
        yellow)
            echo -e "\e[0;33m${@}\e[0m"
            ;;
        blue)
            echo -e "\e[0;34m${@}\e[0m"
            ;;
        purple)
            echo -e "\e[0;35m${@}\e[0m"
            ;;
        cyan)
            echo -e "\e[0;36m${@}\e[0m"
            ;;
        *)
            echo -e "\e[0;37m${@}\e[0m"
            ;;
    esac    # --- end of case ---
}

#=======================================================================
#检查安装包、脚本、my.cnf是否齐全
#=======================================================================

function chk_install_resource()
{
    #判断 template_install-my.cnf 是否存在
    if [ ! -f "$MYCNF" ];then
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') $MYCNF file is not exits!$(echo_warning)"
        exit 1
    fi
    #判断 MySQL Community Server 5.7.18 tar包是否存在
    if [ ! -f "$MYSQL_SOURCE_PACKAGES" ];then
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') $MYSQL_SOURCE_PACKAGES is not exits, please download it from $MYSQL_DOWNLOAD_LINK"
        exit 1
    fi
}
#=======================================================================
# 添加帐号和目录
#=======================================================================
function create_sys_user()
{
    #添加mysql用户信息
    if id mysql &> /dev/null;then
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') MySQL user is exits."
    else
        useradd -r -s /bin/false mysql && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') The system user is added to success .."
    fi

    if [ ! -d "${MYSQL_DATADIR}" ];then
        mkdir -p ${MYSQL_DATADIR} && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') MySQL data directory is created .."
        chown -R mysql:mysql ${MYSQL_DATADIR}
        chmod 750 ${MYSQL_DATADIR}
    elif [ "$(ls -A ${MYSQL_DATADIR})" = "" ];then
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') MySQL data directory is exits."
    else
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') MySQL data directory is not empty. Please check it."
        exit 1
    fi
}
#=======================================================================
#检查是否有旧的mysql/mariadb版本存在
#=======================================================================

function chk_old_mysql_version()
{
    mysqlNum=$(rpm -qa | grep -Ei 'mysql|mariadb'|wc -l)
    if [ "${mysqlNum}" -gt "0" ];then
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') The system has MySQL other version. There may be a conflict in the version!If it continues, the original database will be uninstall."
        read -p "Do you continue to install it(y/n):" cn
        case $cn in
            y|Y)
                rpm -qa | grep -Ei 'mysql|mariadb' | xargs yum remove -y &> /dev/null
                source /etc/profile
                tar_install
                ;;
            n|N)
                exit 1
                ;;
            *)
                echo_color red "$(date +'%Y-%m-%d %H:%M:%S') Input ERROR."
        esac
    else
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') No old version was found."
        source /etc/profile
        tar_install
    fi
}

#=======================================================================
# 解压安装
#=======================================================================
function installPackage()
{
count=0
package=(gcc gcc-c++ bzip2 bzip2-devel bzip2-libs python-devel libaio libaio-devel ncurses ncurses-devel cmake numactl-libs)
nums01=${#package[@]}
for((i=0;i<nums01;i++));
do
        char=${package[$i]}
        rpm -qa | grep "^$char"
        if [ $? != 0 ] ; then
                error[$count]=${package[$i]}
                count=$(($count+1))
                echo_color red "$(date +'%Y-%m-%d %H:%M:%S') The ${package[$i]} is not installed.Please check it.."

        fi
done
if [ $count -gt "0" ];then
        echo "You have $count patchs are not installed." 
        echo "the not installed patch is:" 
        nums02=${#error[@]}
        for((ii=0;ii<nums02;ii++));
        do
                echo "${error[$ii]}^" 
        done
        echo -e  "Are you sure to install the patch[yes or no]:\c" 
        read select 
        if [ $select == "yes" ]; then
                for((is=0;is<nums02;is++));
                do
                        var=${error[$is]}
                        echo $var
                        yum install -y $var
                done
        fi
else
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Check pass!.."
fi
count=0
rpm -q gcc gcc-c++ bzip2 bzip2-devel bzip2-libs python-devel libaio libaio-devel ncurses ncurses-devel cmake numactl-libs | grep "not installed"
}

function tar_install()
{
    installPackage
    echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Starting unzip $MYSQL_SOURCE_PACKAGES .."
    tar zxvf $MYSQL_SOURCE_PACKAGES -C /usr/local/ 
    echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Unzip $MYSQL_SOURCE_PACKAGES SUCCESS .."
    if [ ! -d "/usr/local/mysql" ];then
        ln -s /usr/local/${MYSQL_SOURCE_PACKAGES_NAMES}  /usr/local/mysql
        chown -R mysql:mysql /usr/local/mysql
        chown -R mysql:mysql /usr/local/${MYSQL_SOURCE_PACKAGES_NAMES}
        chmod 750 /usr/local/mysql
        chmod 750 /usr/local/${MYSQL_SOURCE_PACKAGES_NAMES}
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') MySQL package has been placed in the right position .."
        cp -f $MYCNF /etc/my.cnf
    else
        read -p "/usr/local/mysql install directory already exists, delete it, and continue(y/n):" dn
        case $dn in
            y|Y)
                rm -rf /usr/local/mysql
                ln -s /usr/local/${MYSQL_SOURCE_PACKAGES_NAMES}  /usr/local/mysql
                chown -R mysql:mysql /usr/local/mysql
                chown -R mysql:mysql /usr/local/${MYSQL_SOURCE_PACKAGES_NAMES}
                chmod 750 /usr/local/mysql
                chmod 750 /usr/local/${MYSQL_SOURCE_PACKAGES_NAMES}
                echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') MySQL package has been placed in the right position .."
                cp -f $MYCNF /etc/my.cnf
                ;;
            n|N)
                exit 1
                ;;
            *)
            echo_color red "$(date +'%Y-%m-%d %H:%M:%S') /usr/local/mysql is exits.Please check it."
        esac
    fi

    echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Starting initialization .."
    /usr/local/mysql/bin/mysqld --initialize --user=mysql  &> /dev/null && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Initialization ......SUCCESS"
}

#=======================================================================
# 修改环境变量
#=======================================================================
function add_system_profile()
{
cat >> /etc/profile <<EOF
export PATH=\$PATH:/usr/local/mysql/bin/
EOF
source /etc/profile
}


function add_mysql_ldconfig()
{
cat > /etc/ld.so.conf.d/mysql.conf <<EOF
/usr/local/mysql/lib
EOF
ldconfig
}

function add_libmysqlclient()
{
if [ -f /etc/ld.so.conf.d/mysql.conf ];then
    LDNUMS=`grep -i "/usr/local/mysql/lib" /etc/ld.so.conf.d/mysql.conf |wc -l`
    if [ $LDNUMS -eq 0 ];then
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') The configuration file is empty!"
        add_mysql_ldconfig
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Flush ldconfig done .."
    else
        LDEXISTS=`grep -i  "/usr/local/mysql/lib" /etc/ld.so.conf.d/mysql.conf |grep -e "^#" |wc -l`
        if [ $LDEXISTS -gt 0 ];then
            add_mysql_ldconfig
            echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Has been configured!"
        fi
    fi
else
    echo_color red "$(date +'%Y-%m-%d %H:%M:%S') /etc/ld.so.conf.d/mysql.conf is not exits!"
    add_mysql_ldconfig
    echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Flush ldconfig done .."
fi
}


function modify_system_env()
{
#egrep "/usr/local/mysql/bin/" /etc/profile  &> /dev/null
PROFILES=`grep -i  "/usr/local/mysql/bin/" /etc/profile |wc -l`
if [ $PROFILES -eq 0 ];then
    add_system_profile
    echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Flush profile done .."
else
    EXISTS=`grep -i  "/usr/local/mysql/bin/" /etc/profile |grep -e "^#" |wc -l`
    if [ $EXISTS -gt 0 ];then
        add_system_profile
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Flush profile done .."
    fi
fi
}

#=======================================================================
#创建MySQL服务
#=======================================================================

function el7_create_mysql_service()
{
    cat > /usr/lib/systemd/system/mysql.service <<EOF
[Unit]
Description=mysql
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
ExecStart=/usr/local/mysql/support-files/mysql.server start
ExecReload=/usr/local/mysql/support-files/mysql.server restart
ExecStop=/usr/local/mysql/support-files/mysql.server stop
LimitNOFILE = 65535
PrivateTmp=false

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Reload systemd services .."
    systemctl enable mysql.service && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Enable MySQL systemd service .."
    systemctl start mysql.service && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Starting MySQL......SUCCESS!" || echo_color red "$(date +'%Y-%m-%d %H:%M:%S') Starting MySQL......FAILED!."
}

function el6_create_mysql_service()
{
    cd /usr/local/mysql/support-files/
    cp mysql.server /etc/init.d/mysql  
    chmod +x /etc/init.d/mysql
    chkconfig --add mysql   && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Add MySQL service for management .."
    chkconfig --list mysql  && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') List MySQL service .."
    /etc/init.d/mysql start && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Starting MySQL......SUCCESS!" || echo_color red "$(date +'%Y-%m-%d %H:%M:%S') Starting MySQL......FAILED!."
}

#=======================================================================
# 添加帐号
#=======================================================================

function modify_mysql_account()
{
    password=`awk '/A temporary password/ {print $NF}' ${MYSQL_DATADIR}/error.log`
    #echo_color cyan "mysql temp password is ${password}"
    if [ "${password}" != "" ];then
    ${MYSQL} -uroot -p"${password}"  --connect-expired-password  -e "alter user root@localhost identified by 'iforgot';flush privileges;" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 系统随机密码修改成功."
    p1=$?
    else
        echo_color red  "$(date +'%Y-%m-%d %H:%M:%S') MySQL密码获取失败,请排查/清除数据目录重新安装."
        exit 1
    fi
    ${MYSQL} -uroot -piforgot -e "grant all privileges on *.* to root@'%' identified by 'iforgot';" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 授予root用户通过任意主机操作所有数据库的所有权限成功."
    p2=$?
    ${MYSQL} -uroot -piforgot -e "grant RELOAD,REPLICATION SLAVE, REPLICATION CLIENT on *.* to repl@'%' identified by 'repl';" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 授予repl用户通过任意主机对所有数据库进行主从复制的权限成功."
    p3=$?
    ${MYSQL} -uroot -piforgot -e "grant SELECT, PROCESS, REPLICATION CLIENT, SHOW DATABASES on *.* to monitor@'%' identified by 'monitor';" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 授予monitor用户通过任意主机对所有数据库的读取权限成功."
    p4=$?
    ${MYSQL} -uroot -piforgot -e "grant SELECT,RELOAD,LOCK TABLES,REPLICATION CLIENT,PROCESS,SUPER,CREATE,SHOW DATABASES,SHOW VIEW, EVENT, TRIGGER, create tablespace on *.* to dbbackup@'localhost' identified by  'dbbackup';" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 授予dbbackup用户通过localhost主机对所有数据库进行备份的权限成功."
    p5=$?
    ${MYSQL} -uroot -piforgot -e "grant insert,update,delete,select,create,drop,index,trigger,alter on *.* to producer@'%'  identified by 'iforgot';" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 授予producer用户通过任意主机对所有数据库进行常规操作的权限成功."
    p6=$?
    ${MYSQL} -uroot -piforgot -e "grant insert,update,delete,select,create,drop,index,trigger,alter on *.* to producer@'localhost' identified by 'iforgot';" &> /dev/null && echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') 授予producer用户通过localhost主机对所有数据库进行常规操作的权限成功."
    p7=$?
    ${MYSQL} -uroot -piforgot -e "flush privileges" &> /dev/null && echo_color cyan  "$(date +'%Y-%m-%d %H:%M:%S') 权限刷新成功."
    p8=$?
    if [[ "${p1}" == "0" && "${p2}" == "0" && "${p3}" == "0" && "${p4}" == "0" && "${p5}" == "0" && "${p6}" == "0" && "${p7}" == "0" && "${p8}" == "0" ]];then
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') 现在可以登录mysql数据库,root和producer用户的默认密码是\033[41;37m iforgot\033[0m."
        ${MYSQL} -uroot -piforgot -e "select user,host,authentication_string from mysql.user;"
    else
        echo_color red "$(date +'%Y-%m-%d %H:%M:%S') 授权失败,请手动执行授权操作."
    fi
}

#=======================================================================
# 开始安装mysql
#=======================================================================
function mysql_install()
{
    version=$(uname -r |awk -F '.' '{ print $(NF-1) }')
    if [ "${version}" != "el7" ];then
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Start install mysql for el6."
        chk_install_resource
        create_sys_user
        chk_old_mysql_version
        modify_system_env
        add_libmysqlclient
        el6_create_mysql_service
        sleep 5
        modify_mysql_account
    else 
        echo_color cyan "$(date +'%Y-%m-%d %H:%M:%S') Start install mysql for el7."
        chk_install_resource
        create_sys_user
        chk_old_mysql_version
        modify_system_env
        add_libmysqlclient
        el7_create_mysql_service
        sleep 5
        modify_mysql_account
    fi
}

mysql_install
echo_color blue "$(date +'%Y-%m-%d %H:%M:%S') \033[42;37m installation_of_single_mysql.sh执行完成 \033[0m"
  • template_install-my.cnf
# line          :V1.8
# mail          :gczheng@139.com
# data          :2018-07-19
# file_name     :my.cnf
# update        :调整innodb_open_files设置值,必须小于open_files_limit的设置值

#### 注意     :建议参数根据实际情况作调整
#### 本配置文件主要适用于MySQL 5.7.18版本

# ********* 以下重要参数必须修改核对 *********
# 1.innodb_flush_log_at_trx_commit=1
# 2.sync_binlog = 1
# 3.innodb_strict_mode = OFF                          #关闭InnoDB严格检查模式
# 4.innodb_flush_method = O_DIRECT
# 5.lower_case_table_names = 1                        #设置区分大小写,1表示不区分大小写,0表示区分大小写
# 6.character-set-server = utf8
# 7.sql_mode                                          #默认配置
# 8.server-id =1                                      #修改成对应数值
# 9.innodb_buffer_pool_size = 10G                     #纯mysql server 配置50%和 混合内存配置不低于10G~40%
#10.key_buffer_size=1G                                #如果有myisam表请配置为1G,没有请配置64M
#11.innodb_data_file_path = ibdata1:1G:autoextend     #确认配置是否跟原来一样,之前已配置好请维持原样,如未配置请注释掉,新版本请取消注释
#12.log_bin = /data/mysqldata/binlog                  #旧版本或者之前已配置好如:log_bin =/r2/data/mysqldata/slave-bin,请维持原样
#13.slave-parallel                                    #从库开启并行复制,并行复制参数取消注释
#14.undolog                                           #确认配置是否跟原来一样,之前已配置好请维持原样,如未配置请注释掉,新版本(包括升级版本)请取消注释并创建目录并授权
# ********************************************

[client]
port    = 3306
socket  = /data/mysqldata/mysql.sock
#=======================================================================
# # MySQL客户端配置
#=======================================================================
[mysql]
prompt="(\u@\h) \\R:\\m:\\s [\d]> "
no-auto-rehash
default-character-set = utf8mb4
#=======================================================================
# MySQL服务器全局配置
#=======================================================================
[mysqld]
user = mysql
port = 3306
server-id = 1
tmpdir = /data/mysqldata
datadir = /data/mysqldata
socket  = /data/mysqldata/mysql.sock
wait_timeout = 31536000
#interactive_timeout = 600
#sql_mode =                             #sql_mode 配置为空值
#skip_name_resolve = 1
lower_case_table_names = 1
character-set-server = utf8mb4
log_timestamps = SYSTEM
init_connect='SET NAMES utf8mb4'
max_allowed_packet = 128M
######################### 性能参数 ####################
open_files_limit = 10240
max_connections = 10000
max_user_connections=9990
max_connect_errors = 100000
table_open_cache = 1024
thread_cache_size = 64
max_heap_table_size = 32M
query_cache_type = 0
###global cache ###
key_buffer_size = 1G
query_cache_size = 0
tmp_table_size = 32M        #内存临时表
binlog_cache_size = 4M      #二进制日志缓冲
###session cache ###
sort_buffer_size = 8M       #排序缓冲
join_buffer_size = 4M       #表连接缓冲
read_buffer_size = 8M       #顺序读缓冲
read_rnd_buffer_size = 8M   #随机读缓冲
thread_stack = 256KB        #线程的堆栈的大小
######################### binlog设置 #####################
binlog_format = ROW
log_bin = /data/mysqldata/binlog
max_binlog_size = 1G
expire_logs_days = 15       #binlog比较占空间,注意磁盘空间
sync_binlog = 1                  #重要参数必须修改为1
######################### 复制设置 ########################
log_slave_updates = 1
#replicate-do-db = test
#binlog-ignore-db = mysql
### GTID 配置 ###
gtid_mode=ON
enforce-gtid-consistency=true
#****************** 开启并行复制(从库)******************
slave-parallel-type=LOGICAL_CLOCK     #基于组提交的并行复制方式
slave-parallel-workers= 8             #并行的SQL线程数量
master-info_repository=TABLE          #master信息以表的形式保存
relay_log_info_repository=TABLE       #slave信息以表的形式保存
relay_log_recovery=ON                 #relay_log自我修复
######################### innodb ##########################
default_storage_engine = InnoDB
innodb_data_file_path = ibdata1:1G:autoextend
innodb_buffer_pool_size = 12G         #系统内存50%
innodb_open_files = 5120
innodb_flush_log_at_trx_commit = 1    #线上服务器必须配置为1
innodb_file_per_table = 1
innodb_lock_wait_timeout = 5
innodb_io_capacity = 400              #根据您的服务器IOPS能力适当调整innodb_io_capacity,配SSD盘可调整到 10000 - 20000
innodb_io_capacity_max = 20000
innodb_flush_method = O_DIRECT
innodb_log_file_size = 2G
innodb_log_files_in_group = 2
innodb_large_prefix = 0
innodb_thread_concurrency = 64
innodb_strict_mode = OFF
innodb_sort_buffer_size = 4194304
#****************** undolog设置 ******************
#innodb_undo_directory = /data/mysqldata/undolog       #undolog日志目录
#innodb_undo_tablespaces = 2                      #undolog日志文件个数,mysql8之后将弃用
#innodb_undo_logs = 128                           #回滚段的数量, 至少大于等于35,默认128。
#innodb_max_undo_log_size = 1G                    #当超过这个阀值(默认是1G),会触发truncate回收(收缩)动作,truncate后空间缩小到10M。
#innodb_purge_rseg_truncate_frequency = 128       #控制回收(收缩)undolog的频率
#innodb_undo_log_truncate = 1                     #即开启在线回收undolog日志文件
######################### log 设置 #####################
log_error = /data/mysqldata/error.log
slow_query_log = 1
long_query_time = 10
slow_query_log_file = /data/mysqldata/slow.log
#=======================================================================
# MySQL mysqldump配置
#=======================================================================
[mysqldump]
quick
max_allowed_packet = 128M
#=======================================================================
# MySQL mysqld_safe配置
#=======================================================================
[mysqld_safe]
log_error = /data/mysqldata/error.log
pid_file = /data/mysqldata/mysqldb.pid