千家信息网

CentOS一键安装LNMP的脚本分享

发表于:2025-12-02 作者:千家信息网编辑
千家信息网最后更新 2025年12月02日,本篇内容主要讲解"CentOS一键安装LNMP的脚本分享",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"CentOS一键安装LNMP的脚本分享"吧!分享一个
千家信息网最后更新 2025年12月02日CentOS一键安装LNMP的脚本分享

本篇内容主要讲解"CentOS一键安装LNMP的脚本分享",感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习"CentOS一键安装LNMP的脚本分享"吧!

分享一个自己写的一键安装LNMP的脚本。

CentOS6安装效果:

#!/bin/bash# Author:      Zhangbin# Website:     http://qicheng0211.blog.51cto.com/# Description: CentOS6/7一键安装lnmp(基于yum)PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/binexport PATHerr_echo() {    echo -e "\e[31m[ Error ]\033[0m $@"    exit 1}info_echo() {    echo -e "\e[32m[ Info ]\033[0m $@"    sleep 1}# 检查是否root用户if [ $EUID -ne 0 ]; then    err_echo "please run this script as root user."fi# 检查操作系统版本if egrep "CentOS release 6" /etc/redhat-release > /dev/null 2>&1; then    OS=CentOS6elif egrep "CentOS Linux release 7" /etc/redhat-release > /dev/null 2>&1; then    OS=CentOS7else    err_echo "This script is used for CentOS 6.x or 7.x only."fi# 检查网络ping -c 1 mirrors.163.com &>/dev/null[ $? != 0 ] && err_echo "Network does not work."which wget &>/dev/null || yum install wget -y# CentOS6安装yum的axel插件,使yum支持多线程下载:if [ "$OS" == "CentOS6" ];then    wget https://mirrors.tuna.tsinghua.edu.cn/repoforge/redhat/el6/en/x86_64/rpmforge/RPMS/axel-2.4-1.el6.rf.x86_64.rpm    rpm -ivh axel-2.4-1.el6.rf.x86_64.rpm    axelget_conf_start=$(grep -n 'axelget.conf start_line' "$0" | grep -v grep | awk -F: '{print $1}')    axelget_conf_end=$(grep -n 'axelget.conf end_line' "$0" | grep -v grep | awk -F: '{print $1}')    ((axelget_conf_start++))    ((axelget_conf_end--))    sed -n "${axelget_conf_start},${axelget_conf_end}p" "$0" > /etc/yum/pluginconf.d/axelget.conf    axelget_py_start=$(grep -n 'axelget.py start_line' "$0" | grep -v grep | awk -F: '{print $1}')    axelget_py_end=$(grep -n 'axelget.py end_line' "$0" | grep -v grep | awk -F: '{print $1}')    ((axelget_py_start++))    ((axelget_py_end--))    sed -n "${axelget_py_start},${axelget_py_end}p" "$0" > /usr/lib/yum-plugins/axelget.pyfi# 安装163 yum源:if [ "$OS" == "CentOS6" ];then    wget http://mirrors.163.com/.help/CentOS6-Base-163.repo -O CentOS-Base.repoelse    wget http://mirrors.163.com/.help/CentOS7-Base-163.repo -O CentOS-Base.repoficp -p /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bakmv -f CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repoyum clean allyum makecache# 安装epel yum源:yum -y install epel-releasesed -i 's/^mirrorlist=https/mirrorlist=http/' /etc/yum.repos.d/epel.repo# CentOS7安装yum的axel插件,依赖epel源if [ "$OS" == "CentOS7" ];then    yum -y install yum-axelget    sed -i '/^maxconn=/c\maxconn=10' /etc/yum/pluginconf.d/axelget.conffi# nginx的yum源:cat > /etc/yum.repos.d/nginx.repo << 'EOF'[nginx]name=nginx repobaseurl=http://nginx.org/packages/centos/$releasever/$basearch/enabled=1gpgcheck=0EOF# 关闭selinux:setenforce 0sed -i '/^SELINUX=/c\SELINUX=disabled' /etc/selinux/config # 安装nginx、php:yum -y install nginx php-fpm php-soap php-bcmath php-xml php-opcache php-gd php-mcrypt php-pdo php-mysql php-mbstring php-xmlrpc# 修改/etc/nginx/nginx.confcp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bakcat > /etc/nginx/nginx.conf << 'EOF'user  nginx;worker_processes auto;error_log  /data/logs/nginx_error.log  crit;worker_rlimit_nofile 65535;events{    use epoll;    worker_connections 65535;}http {    include       mime.types;    default_type  application/octet-stream;    server_names_hash_bucket_size 128;    client_header_buffer_size 32k;    large_client_header_buffers 4 32k;    client_max_body_size 8m;    sendfile on;    tcp_nopush     on;    keepalive_timeout 15;    tcp_nodelay on;    proxy_buffer_size 16k;    proxy_buffering on;    proxy_buffers  4 64k;    proxy_busy_buffers_size 128k;    fastcgi_connect_timeout 300;    fastcgi_send_timeout 300;    fastcgi_read_timeout 300;    fastcgi_buffer_size 64k;    fastcgi_buffers 4 64k;    fastcgi_busy_buffers_size 128k;    fastcgi_temp_file_write_size 128k;    gzip on;    gzip_min_length  1k;    gzip_buffers     4 16k;    gzip_http_version 1.0;    gzip_comp_level 2;    gzip_types       text/plain application/x-javascript text/css application/xml;    gzip_vary on;    gzip_disable msie6;    log_format  access   '$remote_addr - $remote_user [$time_local] "$request"  '     '$status $body_bytes_sent "$http_referer"  '     '"$http_user_agent" $http_x_forwarded_for ';    access_log /data/logs/access.log access;        include conf.d/*.conf;    server_tokens off;    reset_timedout_connection on;}EOFmkdir -p /data/logschown -R nginx. /data/logs# 修改php-fpm运行用户为nginxsed -i 's/^user = apache/user = nginx/' /etc/php-fpm.d/www.confsed -i 's/^group = apache/group = nginx/' /etc/php-fpm.d/www.confchown -R nginx /var/log/php-fpm/mkdir /var/lib/php/sessionchown -R nginx /var/lib/php/# 启动php-fpm:service php-fpm start[ $? -eq 0 ] && info_echo "php-fpm start OK."# 启动nginx:nginx -t && service nginx start[ $? -eq 0 ] && info_echo "nginx start OK."# 设置nginx、php-fpm开机启动:if [ "$OS" == "CentOS6" ];then    chkconfig php-fpm on    chkconfig nginx onelse    systemctl enable php-fpm    systemctl enable nginxfi# 安装Mysql的yum源:if [ "$OS" == "CentOS6" ];then    rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpmelse    rpm -Uvh http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpmfi# 安装mysql:yum -y install mysql mysql-server mysql-devel# 修改/etc/my.cnfcat > /etc/my.cnf << 'EOF'# Example MySQL config file. mysql5.6 RAM 1G zhangbin[client]port            = 3306socket          = /var/lib/mysql/mysql.sock[mysqld]user = mysqlport = 3306datadir = /var/lib/mysql/socket = /var/lib/mysql/mysql.socksql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USERbind-address = 0.0.0.0server-id = 1skip-name-resolveskip-external-lockingback_log = 600max_connections = 512max_connect_errors = 6000open_files_limit = 65535table_open_cache = 512max_allowed_packet = 4Mmax_heap_table_size = 8Mtmp_table_size = 16Mread_buffer_size = 2Mread_rnd_buffer_size = 8Msort_buffer_size = 8Mjoin_buffer_size = 8Mthread_cache_size = 8query_cache_size = 2Mquery_cache_limit = 2Mkey_buffer_size = 64Minteractive_timeout = 28800wait_timeout = 28800# myisambulk_insert_buffer_size = 8Mmyisam_sort_buffer_size = 8Mmyisam_max_sort_file_size = 10Gmyisam_repair_threads = 1# bin loglog_bin = /var/lib/mysql/mysql-bin.logbinlog_cache_size = 2Mbinlog_format = MIXEDexpire_logs_days = 7# slow logslow_query_log = 1slow_query_log_file = /var/lib/mysql/mysql-slow.loglong_query_time = 3log_queries_not_using_indexes = 1# innodbdefault-storage-engine = InnoDBinnodb_data_home_dir = /var/lib/mysql/innodb_data_file_path = ibdata1:10M:autoextendinnodb_log_group_home_dir = /var/lib/mysql/innodb_buffer_pool_size = 512Minnodb_log_file_size = 128Minnodb_log_files_in_group=3innodb_log_buffer_size = 8Minnodb_flush_log_at_trx_commit = 2innodb_lock_wait_timeout = 120innodb_file_per_table = 1innodb_open_files = 500innodb_read_io_threads = 4innodb_write_io_threads = 4innodb_thread_concurrency=0innodb_purge_threads = 1innodb_max_dirty_pages_pct = 90[mysqldump]quickmax_allowed_packet = 16M[mysql]no-auto-rehash[myisamchk]key_buffer = 20Msort_buffer_size = 20Mread_buffer = 2Mwrite_buffer = 2M[mysqlhotcopy]interactive-timeoutEOF# 启动mysql:service mysqld start[ $? -eq 0 ] && info_echo "mysqld start OK."# 安全设置:#mysql_secure_installation# 设置mysqld开机启动:if [ "$OS" == "CentOS6" ];then    chkconfig mysqld onelse    systemctl enable mysqldfiexit 0# axelget.conf start_line[main]enabled=1onlyhttp=1enablesize=54000cleanOnException=1# axelget.conf end_line# axelget.py start_linefrom yum.plugins import PluginYumExit, TYPE_CORE, TYPE_INTERACTIVEfrom urlparse import urljoinimport os,timerequires_api_version = '2.3'plugin_type = (TYPE_CORE, TYPE_INTERACTIVE)enablesize=300000trymirrornum=-1maxconn=10httpdownloadonly=FalsecleanOnException=0def init_hook(conduit):        global enablesize,trymirrornum,maxconn,cleanOnException,httpdownloadonly        enablesize = conduit.confInt('main','enablesize',default=30000)        trymirrornum = conduit.confInt('main','trymirrornum',default=-1)        maxconn = conduit.confInt('main','maxconn',default=10)        httpdownloadonly=conduit.confBool('main','onlyhttp',default=False)        cleanOnException=conduit.confInt('main','cleanOnException',default=0)        returndef predownload_hook(conduit):        global enablesize,cleanOnException,httpdownloadonly        preffermirror=""        PkgIdx=0        TotalPkg=len(conduit.getDownloadPackages())        for po in (conduit.getDownloadPackages()):                PkgIdx+=1                if hasattr(po, 'pkgtype') and po.pkgtype == 'local':                        continue                totsize = long(po.size)                ret = False                if totsize <= enablesize:                        conduit.info(2, "Package %s download size %d less than %d,Skip plugin!"  % (po.repo.id,totsize,enablesize))                        continue                else:                        conduit.info(2, "[%d/%d]Ok,we will try to use axel to download this big file:%d" % (PkgIdx,TotalPkg,totsize))                local = po.localPkg()                if os.path.exists(local):                        if not os.path.exists(local+".st"):                                fstate=os.stat(local)                                if totsize == fstate.st_size:                                        conduit.info(2,"Target already exists,skip to next file!")                                        continue                localall = "%s %s" % (local,local+".st")                rmcmd = "rm -f %s" % (localall)                curmirroridx = 0                conduit.info(2,"Before we start,clean all the key files")                os.system(rmcmd)                connnum = totsize / enablesize                if connnum*enablesize maxconn:                        connnum = maxconn                mirrors=[]                mirrors[:0]=po.repo.urls                if preffermirror != "":                        mirrors[:0] = [preffermirror]                for url in mirrors:                        if url.startswith("ftp://") and httpdownloadonly:                                print "Skip Ftp Site:",url                                continue                        if url.startswith("file://"):                                print "Skip Local Site:",url                                continue                        curmirroridx += 1                        if (curmirroridx > trymirrornum) and (trymirrornum != -1):                                conduit.info(2, "Package %s has tried %d mirrors,Skip plugin!" % (po.repo.id,trymirrornum))                                break                        remoteurl =  "%s/%s" % (url,po.remote_path)                        syscmd = "axel -a -n %s %s -o %s" % (connnum,remoteurl,local)                        conduit.info(2, "Execute axel cmd:\n%s"  % syscmd)                        os.system(syscmd)                        time.sleep(2)                        if os.path.exists(local+".st"):                                conduit.info(2,"axel exit by exception,let's try another mirror")                                if cleanOnException:                                        conduit.info(2,"because cleanOnException is set to 1,we do remove key file first")                                        os.system(rmcmd)                                continue                        elif not os.path.exists(local):#this mirror may not update yet                                continue                        else:                                ret = True                                preffermirror=url                                break                if not ret:                        conduit.info (2,"try to run rm cmd:%s"  % rmcmd)                        os.system(rmcmd)# axelget.py end_line

到此,相信大家对"CentOS一键安装LNMP的脚本分享"有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

0