Linux脚本合集

1.1 初始化系统
#!/bin/bash
#auth:fanweicong
#time:2019-02-12
#mail:15813280924@163.com
#function:Centos system Initialization


#安装常用的系统工具
if [ $UID -eq 0 ];then
 yum install -y vim wget ntpdate net-tools rsync openssh-clients bind-utils nfs-utils >/dev/null 2<&1
 echo "system tools Successful installation...."
else
 echo "The current execution user is not root!!!"
 exit 127
fi


#添加网络源
system=`cat /etc/redhat-release|sed -r 's/.* ([0-9]+)\..*/\1/'`
if [ $system == "6" ];then
 rm -rf /etc/yum.repos.d/*.repo
 wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo > /dev/null 2<&1
 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo > /dev/null 2<&1
 yum clean all && yum makecache > /dev/null 2<&1
 echo "CentOS-Base yum Set Successful..."
else
 rm -rf /etc/yum.repos.d/*.repo
 wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo > /dev/null 2<&1
 wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo > /dev/null 2<&1
 yum clean all > /dev/null 2<&1 && yum makecache > /dev/null 2<&1
 echo "CentOS-Base yum Set Successful..." 
fi


#关闭SELINUX
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config 2>&1
echo "selinux off Successful..."



#关闭firewalld 和 iptables
if [ $system == "7" ];then
 systemctl stop firewalld && systemctl disable firewalld
 yum install iptables-services iptables iptables-devel -y >/dev/null 2>&1
 cp /usr/libexec/iptables/iptables.init /etc/init.d/iptables
 systemctl stop iptables.service && systemctl disable iptables.service
 echo "firewalld off Successful..."
else
 /etc/init.d/iptables stop >/dev/null
 chkconfig iptables off >/dev/null && echo "iptables set Successful..."
fi


#调整文件描述符数量
if [ "`cat /etc/security/limits.conf | grep 'soft nproc 65535'`" = "" ]; then
cat >> /etc/security/limits.conf << EOF
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535
EOF
echo "limits set Successful..."
fi


#内核参数优化
[ -f /etc/sysctl.conf.bak ] && /bin/cp /etc/sysctl.conf.bak /etc/sysctl.conf.bak.$(date +%F-%H%M%S) ||/bin/cp /etc/sysctl.conf /etc/sysctl.conf.bak
cat >> /etc/sysctl.conf <<EOF
net.ipv4.ip_forward = 1
net.ipv4.tcp_fin_timeout = 2
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.ip_local_port_range = 4000 65000
net.ipv4.tcp_max_syn_backlog = 16384
net.ipv4.tcp_max_tw_buckets = 36000
net.ipv4.route.gc_timeout = 100
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_synack_retries = 1
net.core.somaxconn = 16384
net.core.netdev_max_backlog = 16384
net.ipv4.tcp_max_orphans = 16384
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0

net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.core.wmem_default = 87380
net.core.wmem_max = 16777216
net.core.rmem_default = 87380
net.core.rmem_max = 16777216

net.ipv4.tcp_keepalive_time = 120
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3

net.ipv4.conf.all.promote_secondaries = 1
net.ipv4.conf.default.promote_secondaries = 1
net.ipv6.neigh.default.gc_thresh3 = 4096
net.ipv4.neigh.default.gc_thresh3 = 4096

kernel.core_uses_pid = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.softlockup_panic = 1
kernel.sysrq = 1
kernel.numa_balancing = 0
kernel.shmmax = 68719476736
kernel.printk = 5
EOF
sysctl -p >/dev/null 2>&1 && echo "kenel set Successful...."


#同步网络时间
/usr/sbin/ntpdate ntp1.aliyun.com > /dev/null && echo "update time Successful....."
echo "############### auto update time ###############" >> /var/spool/cron/root
echo "00 01 * * * /usr/sbin/ntpdate ntp1.aliyun.com >/dev/null 2>&1" >> /var/spool/cron/root


#优化ssh连接(默认的ssh服务端口,禁止root用户远程连接,禁止空密码连接)
/bin/cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
#sed -i 's/\#Port 22/Port 52113/' /etc/ssh/sshd_config
#sed -i 's/\#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/\#PermitEmptyPasswords no/PermitEmptyPasswords no/' /etc/ssh/sshd_config
sed -i 's/\#UseDNS yes/UseDNS no/' /etc/ssh/sshd_config
service sshd restart > /dev/null 2<&1 && echo "sshd_config Successful....."



#美化登陆界面
cat > /etc/motd <<eof

 **************************************************************
 *                                                            *
 *   .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-.       *
 *    |                     ______                     |      *
 *    |                  .-"      "-.                  |      *
 *    |                 /            \                 |      *
 *    |     _          |              |          _     |      *
 *    |    ( \         |,  .-.  .-.  ,|         / )    |      *
 *    |     > "=._     | )(__/  \__)( |     _.=" <     |      *
 *    |    (_/"=._"=._ |/     /\     \| _.="_.="\_)    |      *
 *    |           "=._"(_     ^^     _)"_.="           |      *
 *    |               "=\__|IIIIII|__/="               |      *
 *    |              _.="| \IIIIII/ |"=._              |      *
 *    |    _     _.="_.="\          /"=._"=._     _    |      *
 *    |   ( \_.="_.="     `--------`     "=._"=._/ )   |      *
 *    |    > _.="                            "=._ <    |      *
 *    |   (_/                                    \_)   |      *
 *    |                                                |      *
 *    '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-='      *
 *                                                            *
 *           LASCIATE OGNI SPERANZA, VOI CH'ENTRATE           *
 **************************************************************

eof
/bin/cp /etc/issue /etc/issue.bak
>/etc/issue && echo "Terminal beautification Successful..."
echo -e "System initialization complete!!!"
1.2 安装数据库
#!/bin/bash
# install glib mysql
# version: 5.7


DB_USER=mysql
DB_PORT=3306
DB_PATH=/usr/local/mysql
DB_DATA=/usr/local/mysql/data
DB_PACK=$1
DB_DEMO=`echo ${DB_PACK%%.tar*}`

# set root running
if [ $UID -ne 0 ]
then
   echo -e "\033[31merror: must be root runnig install\033[0m"
   exit 1
else
   id ${DB_USER} > /dev/null 2<&1
   if [ $? -ne 0 ]
   then
      echo "create mysql running user..."
      useradd -M -s /sbin/nologin ${DB_USER}
   fi
fi

# tar install package
echo "tar mysql package..."
if [ -e ${DB_PACK} -a -f ${DB_PACK} ]
then
   tar xf ${DB_PACK}
else
   echo -e "\033[31mNo such file or directory\033[0m"
   exit 127
fi

# install mysql db
echo "install mysql db basedir..."
mv ./${DB_DEMO} ${DB_PATH}
mkdir ${DB_DATA}
chown ${DB_USER}:${DB_USER} -R ${DB_PATH}
chown ${DB_USER}:${DB_USER} -R ${DB_DATA}

# set mysql path
echo "set mysql path..."
cat >> /etc/profile <<eof
export PATH=${DB_PATH}/bin:$PATH
eof
source /etc/profile

# init mysql db(no password)
echo "initialize mysql db..."
mysqld --initialize-insecure \
--user=${DB_USER} \
--basedir=${DB_PATH} \
--datadir=${DB_DATA}

# configure mysql server
cat > /etc/my.cnf <<eof
[client]
port=${DB_PORT}
socket=/tmp/mysql.sock
[mysqld_safe]
pid-file=${DB_DATA}/mysqld.pid
log-error=${DB_DATA}/mysql-error.log
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
port=${DB_PORT}
user=${DB_USER}
basedir=${DB_PATH}
datadir=${DB_DATA}
server_id=1
socket=/tmp/mysql.sock
#设置忽略大小写,1忽略 0不忽略
lower_case_table_names=1
sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO ,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
[mysql]
socket=/tmp/mysql.sock
eof

# copy init scripts
echo "copy mysql init start scripts..."
cp ${DB_PATH}/support-files/mysql.server /etc/init.d/mysqld
service mysqld start && chkconfig mysqld on

# configure mysql root user password
[ $? -eq 0 ] && echo -e "\033[32minstall finished...\033[0m"
echo -e "\033[32mPlease execute "mysqladmin-uroot-p password xxxxx" to change the password...\033[0m"
1.3 升级tomcat版本
#!/bin/bash
#说明: 请进入当前tomcat安装根路径执行

#变量定义
tomcat_pkg=apache-tomcat-9.0.41.tar.gz  #你要升级的版本包名
down_url=https://mirrors.bfsu.edu.cn/apache/tomcat/tomcat-9/v9.0.41/bin
down_dir=/tmp
tomcat_dir=$(echo ${tomcat_pkg%%.tar.gz})  #新版本解压后的路径

#下载新包
if [ ! -f $down_dir/$tomcat_pkg ];then
   wget -P $down_dir/ $down_url/$tomcat_pkg
fi

#解压文件
if [ -f $down_dir/$tomcat_pkg ];then
   tar xf $down_dir/$tomcat_pkg -C $down_dir/
else
   echo "file not exists"
   exit 127
fi

#停止服务(如果有运行)
run_pid=$(ps -ef |grep "[=]$PWD" |awk '{print $2}' |xargs)
if [ $run_pid ];then
    ./bin/shutdown.sh
    sleep 10
    old_pid=$(ps -ef |grep "[=]$PWD" |awk '{print $2}' |xargs)
    [ $old_pid ] && kill -9 $old_pid || echo "Service aleardy stop!!!"
fi

#开始升级
mv ./bin ./bin.bak
mv ./lib ./lib.bak
mv $down_dir/$tomcat_dir/lib .
mv $down_dir/$tomcat_dir/bin .
./bin/version.sh
echo "update tomcat version success!!!"

#清除文件
rm -rf $down_dir/$tomcat_dir*
1.4 jar包发布
#!/bin/bash

# 变量定义
BUILD_ID=DONTKILLME
dev_runs=/Data/application/nwsmz_auth
dev_dirs=/Data/packages/nwsmz_auth
dev_pack=$1

#UAT拿包
if [ ! -f "${dev_dirs}/${dev_pack}" ];then
   wget -P ${dev_dirs}/  http://193.112.156.95:15900/nwsmz_auth/${dev_pack}
fi


# 发布流程定义
if [[ ! -z ${dev_pack} && -f ${dev_dirs}/${dev_pack} ]];then

   # 1.停止服务
   run_pid=$(ps -ef |grep "nwsmz[_]auth.jar" |awk '{print $2}')
   [ ${run_pid} ] && kill -9 ${run_pid}

   # 2.加载配置
   cd ${dev_dirs}/
   jar -uf ./${dev_pack} ./BOOT-INF/classes/{application-prod.yml,application.yml}

   # 3.更新版本
   if [ -L "${dev_runs}/nwsmz_auth.jar" ];then
      ln -snf ${dev_dirs}/${dev_pack} ${dev_runs}/nwsmz_auth.jar
   else
      ln -s ${dev_dirs}/${dev_pack} ${dev_runs}/nwsmz_auth.jar
   fi

   # 4.启动服务
   cd ${dev_runs}/
   nohup java -javaagent:${dev_runs}/jspAgent/JSPAgent.jar -jar ${dev_runs}/nwsmz_auth.jar >> nwsmz_auth.log &
   sleep 10

   # 5.检查服务
   new_pid=$(ps -ef |grep "nwsmz[_]auth.jar" |awk '{print $2}')
   if [ ${new_pid} ];then
      echo "nwsmz_auth start success!"
   else
      echo "nwsmz_auth start faild!"
      exit 128  
   fi

else
   echo "error: value is null or file does not exist!"
   echo "pack_name: $pack_name"
   exit 127
fi
1.5 war包发布
#!/bin/bash

#
dev_path=/Data/nw_smz/smzos/web  # 发布目录
dev_pack=/Data/nw_smz/devops/web # 包目录
dev_name=$1                      # 包名

#
if [[ ! -z ${dev_name} && -f ${dev_pack}/${dev_name} ]];then

    # 1.停止服务
    cur_pid=$(ps -ef |grep "[=]${dev_path}" |awk '{print $2}')

    if [ ${cur_pid} ];then
        ${dev_path}/bin/shutdown.sh
        sleep 10
        old_pid=$(ps -ef |grep "[=]${dev_path}" |awk '{print $2}')
        [ ${old_pid} ] && kill ${old_pid} || echo "Service aleardy stop!!!"
    else
        echo "Service Not Running!!!"
        echo "Start devops Application...."
    fi

    # 2.修改配置
    cd ${dev_pack}/
    jar -uf ./${dev_name} ./WEB-INF/classes/{config.properties,jdbc.properties,redis.properties,serverWhiteList.txt}

    # 3.移除版本
    if [ -d "${dev_path}/webapps/ROOT" ];then
        cd ${dev_path}/webapps/
        rm -rf ./ROOT
    fi

    # 4.发布版本
    if [ -L "${dev_path}/webapps/ROOT.war" ];then
        ln -snf ${dev_pack}/${dev_name} ${dev_path}/webapps/ROOT.war
    else
        ln -s ${dev_pack}/${dev_name} ${dev_path}/webapps/ROOT.war
    fi

    # 5.启动服务
    ${dev_path}/bin/startup.sh
    sleep 10
    new_pid=$(ps -ef |grep "[=]${dev_path}" |awk '{print $2}')
    [ ${new_pid} ] && echo "Service start success" || echo "Service start failed" && exit 127

else
   echo "Error: File not exists or Value is null!!!"
   exit 127
fi
1.6 前端发布
#!/bin/bash

# 变量定义
#BUILD_ID=DONTKILLME
pkg_runs=/data/application              #发布目录
pkg_dirs=/data/packages/nwsmz_html      #包目录
pkg_name=$1                             #发布包

#测试环境拿包
#if [ ! -f "${pkg_dirs}/${pkg_name}" ];then
#   wget -P ${pkg_dirs}/  http://106.52.208.27:15900/nwsmz_html-pro/${pkg_name}
#fi

#用户权限控制
if [ $UID -ne 0 ];then
    echo "请切换到root用户执行脚本发布!!!"
    exit 127
fi

#发布流程
if [[ ! -z ${pkg_name} && -f ${pkg_dirs}/${pkg_name} ]];then

    if [ -d "${pkg_runs}/nwsmz_html" ];then
        cd ${pkg_runs}/
        chattr -i -R nwsmz_html
        rm -rf nwsmz_html
        mkdir nwsmz_html
        unzip ${pkg_dirs}/${pkg_name} -d ${pkg_runs}/nwsmz_html/
        cd ${pkg_runs}/
        chown www.www -R nwsmz_html
                setfacl -m u:nginx:rwx -R nwsmz_html
        chattr +i -R nwsmz_html
    else
        cd ${pkg_runs}/
        mkdir nwsmz_html
        unzip ${pkg_dirs}/${pkg_name} -d ${pkg_runs}/nwsmz_html/
        cd ${pkg_runs}/
        chown www.www -R nwsmz_html
                setfacl -m u:nginx:rwx -R nwsmz_html
        chattr +i -R nwsmz_html
    fi

else
   echo "Error: File not exists or Value is null!!!"
   exit 127
fi
1.7 Redis启动脚本
#!/bin/bash

#
redis_host=172.16.0.16
redis_port=26379
serexec=/usr/local/redis/bin/redis-server
cliexec=/usr/local/redis/bin/redis-cli
pidfile=/var/run/redis_26379.pid
confile="/home/nw_nyy/redis/redis_26379.conf"

#
start_redis(){
    pid=$(ps -ef |grep "[:]${redis_port}" |awk '{print $2}')
    if [ ${pid} ];then
       echo -e "\033[32mredis already running...\033[0m"
    else
       ${serexec} ${confile} && echo -e "\033[32mredis start success!!!\033[0m"
    fi
}

#
stop_redis(){
    pid=$(ps -ef |grep "[:]${redis_port}" |awk '{print $2}')
    if [ ${pid} ];then
           ${cliexec} -h ${redis_host} -p ${redis_port} shutdown && echo -e "\033[31mredis stop success!!!\033[0m" || echo "stop error!!!"
    else
       echo "redis not running..."
    fi    
}


# 
case $1 in
'start')
    start_redis
    ;;
'stop')
    stop_redis
    ;;
*)
    echo "useage: $0 start|stop"
esac
1.8 Py37编译安装
#!/bin/bash
# desc: Make install python37

Python_PAG=$1
Python_MAK=$(echo ${Python_PAG%%.tar*})
Python_DIR=/usr/local/python3

if [ $UID -eq 0 ];then
    echo "start installation..."
    yum -y install wget zlib-devel bzip2-devel openssl-devel \
    ncurses-devel sqlite-devel readline-devel tk-devel \
    gdbm-devel db4-devel libpcap-devel xz-devel \
    gcc gcc-c++ zlib zlib-devel libffi-devel gcc \
    kernel-devel kenel-headers make bzip2  >/dev/null 2<&1    
    if [ $? -eq 0 ];then
        tar xf ./${Python_PAG} && cd ${Python_MAK} \
        && ./configure --prefix=${Python_DIR} \
        && make && make install \
        && ln -s ${Python_DIR}/bin/python3.7 /usr/bin/python3 \
        && ln -s ${Python_DIR}/bin/pip3.7 /usr/bin/pip3 \
        && python3 -V && echo "installation successfully..." || echo "error!!!"
    else
        echo "Please check if the dependency installation is correct!!!"
        exit 128
    fi
else
    echo "Please use root to perform the installation..."
    exit 127
fi
1.9 Openssl升级操作
#!/bin/bash

#
install_dir=/usr/local/openssl
install_url=https://www.openssl.org/source
install_pkg=openssl-1.1.1i.tar.gz
install_mke=$(echo ${install_pkg%%.tar*})

#
yum install -y zlib zlib-devel \
gcc gcc-c++ make perl perl-devel

#
if [ ! -f "/tmp/${install_pkg}" ];then
   wget -P /tmp/ ${install_url}/${install_pkg}
fi

#
cd /tmp
tar xf ${install_pkg}
cd /tmp/${install_mke}/
./config --prefix=${install_dir}
make && make install

#
if [ -f "/usr/bin/openssl" ];then
   mv /usr/bin/openssl /usr/bin/openssl.bak
   ln -sf ${install_dir}/bin/openssl /usr/bin/openssl
   echo "/usr/local/openssl/lib" >> /etc/ld.so.conf
   ldconfig -v
   openssl version
fi