#!/bin/sh
# ---------------------------------------------
# user:zyx,shichao
# email:642652602@qq.com,shichao@scajy.cn
# mobile:15201097336
# date:2019.5.10
# ---------------------------------------------



function Basics(){

echo 'gcc-c++,gcc,make等工具安装中，请稍等......'
yum install epel-release -y >/dev/null 
yum -y install gcc gcc-c++ gd cmake patch  automakemake autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devellibxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-develkrb5 krb5-devel libidn libtools-libs libidn-devel openssl openssl-developenldap openldap-devel nss_ldap openldap-clients openldap-servers pcre-devel libmcrypt-devel readline-devellibcap-devel ntpdate iftop lsof telnet net-tools vim lrzsz which zip unzip libXrender libXext > /dev/null 2>&1 
if [ $? -eq 0 ] ; then
    echo 'gcc-c++,gcc,make等工具安装完成!'
fi

#系统基本设置，包括时间同步设置，firewalld，root禁止登陆等
#系统时间及时区设置
/usr/bin/timedatectl set-timezone  Asia/Shanghai  
echo  '正在同步网络时间......'
/usr/sbin/ntpdate cn.pool.ntp.org > /dev/null 2>&1 && echo  "网络时间同步完成！" || echo  "网络时间同步失败"
/sbin/hwclock --systohc  

#设置为每天同步网络时间
if [ ! -f /var/spool/cron/root ]
  then
    touch /var/spool/cron/root 
fi
is_ntpdate=$(grep "ntpdate" /var/spool/cron/root |wc -l)
if [ $is_ntpdate -eq 0 ] ; then
cat >> /var/spool/cron/root <<EOF 
59  23 * * * /usr/sbin/ntpdate cn.pool.ntp.org > /dev/null
EOF
fi

#禁用selinux和firewalld
/usr/bin/sed -i 's/^SELINUX=.*$/SELINUX=disabled/' /etc/selinux/config > /dev/null 2>&1  && echo  '已禁用系统selinux'
setenforce 0
/usr/bin/systemctl  stop firewalld  > /dev/null 2>&1
/usr/bin/systemctl disable firewalld >  /dev/null 2>&1
echo '已禁用firewalld'


#系统升级
#echo '系统正在升级中......该过程可能需要十几分钟或更久，请稍等！'
#yum update -y > /dev/null 2>&1
#if [ $? -eq 0 ] ; then
#    echo '系统升级成功'
#fi


#系统参数优化
echo '正在优化系统参数......'
sed -i '5,$d' /etc/security/limits.d/20-nproc.conf
cat >> /etc/security/limits.d/20-nproc.conf <<EOF 
*          soft    nproc     655350
*          soft    nofile    655350
*          hard    nofile    655350
*          hard    nproc     655350
root       soft    nproc     unlimited
*          hard    memlock   unlimited
*          soft    memlock   unlimited
EOF

echo 10240 >  /proc/sys/net/core/somaxconn

echo never > /sys/kernel/mm/transparent_hugepage/enabled  &&  echo never > /sys/kernel/mm/transparent_hugepage/defrag

sysctl vm.overcommit_memory=1 > /dev/null 2>&1 

sed -i '10,$d' /etc/sysctl.conf
cat >> /etc/sysctl.conf <<EOF 
vm.overcommit_memory = 1
net.ipv4.tcp_syncookies = 0
net.ipv4.ip_local_port_range = 1024 65535
net.core.rmem_max=16777216
net.core.wmem_max=16777216
net.ipv4.tcp_rmem=4096 87380 16777216
net.ipv4.tcp_wmem=4096 65536 16777216
net.ipv4.tcp_fin_timeout = 10
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_window_scaling = 0
net.ipv4.tcp_sack = 0
net.core.netdev_max_backlog = 30000
net.ipv4.tcp_no_metrics_save=1
net.core.somaxconn = 65535
net.ipv4.tcp_max_orphans = 262144
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_retries2 = 5
net.ipv4.tcp_keepalive_time = 40
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_keepalive_intvl = 10
net.ipv4.tcp_max_tw_buckets = 5000
fs.file-max = 655360
fs.nr_open=100000000
vm.max_map_count = 2000000
EOF
echo  '系统参数已经优化!'


#配置开机启动项
echo '' > /etc/init.d/optimizing
cat >> /etc/init.d/optimizing <<EOF 
#!/bin/bash
### BEGIN INIT INFO
# Provides:          optimizing
# Required-Start:    \$local_fs
# Required-Stop:
# X-Start-Before:    redis mongod mongodb-mms-automation-agent
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Optimizing script
# Description:       Optimizing script.
### END INIT INFO

case \$1 in
  start)
    # transparent hugepage
    thp_path=/sys/kernel/mm/transparent_hugepage
    echo 'never' > \${thp_path}/enabled
    echo 'never' > \${thp_path}/defrag

    # somaxconn
    echo '10240' > /proc/sys/net/core/somaxconn  
    ulimit -f unlimited
    ulimit -t unlimited
    ulimit -v unlimited
    ulimit -n 655350
    ulimit -m unlimited
    ulimit -l unlimited
    ulimit -c unlimited
    ulimit -u 655350
    unset thp_path
    ;;
esac
EOF
if [ $? -eq 0 ] ;then 
   chmod 755 /etc/init.d/optimizing 
   chkconfig optimizing on 
   /etc/init.d/optimizing  start
fi

}

#######################系统初始化模块######################

#######################随机密码生成模块######################

#随机密码模块
function in_srt()
{
pwd=`openssl rand -base64 18|cut -c 1-16`
for ((j=1;j<=3;j++))
  do 
    string='[]{}%&*()_+@!#'
    str_length=${#string}
    num=$(date +%s+10#%N);
    ((retnum=num%str_length+1));
    let out_num=retnum-1
    pw_length=${#pwd}
    for((i=1;i<=${pw_length};i++))
      do
        if [ $i -eq 1 ]
          then
            srt_tmp=`echo ${pwd}|cut -c $i`
          else
            if [ $i -eq ${retnum} ]
              then
                srt_tmp=${srt_tmp}${string:$out_num:1}
              else
                srt_tmp=${srt_tmp}$(echo ${pwd}|cut -c $i)
            fi
        fi
      done
    pwd=${srt_tmp}
  done
echo ${pwd}
}

#######################随机密码生成模块######################


#######################磁盘挂载初始化模块######################
#磁盘挂载模块
DK_CH()
{
if [ "${1}x" == "x" ]
  then
    mount_home=/data
  else
    mount_home=${1}
fi
for DK in `lsblk |grep disk |awk '{print $1}'`
  do
    if [ "$(lsblk -f --output NAME,KNAME,TYPE,UUID /dev/${DK}|grep disk|awk '{print $4}'|head -n 1)x" == "x" ]
      then
        if [ "$(lsblk -f --output NAME,KNAME,TYPE,UUID /dev/${DK}|grep part|awk '{print $4}'|head -n 1)x" == "x" ]
          then
            echo y |mkfs.ext4 /dev/${DK}
            if [ $? -eq 0 ]
              then
                sleep 2
                UUID=$(lsblk -f --output TYPE,UUID  /dev/${DK}|grep disk|awk '{print $2}')
            fi
            if [ ! -d ${mount_home} ]
              then
                mkdir -p ${mount_home}
            fi
            if [ "$(cat /etc/fstab |awk '{print $2}'|grep /${mount_home})x" == "x" ]
              then
                if [ "${UUID}x" != "x" ]
                  then
                    echo "UUID=${UUID} ${mount_home}                    ext4    defaults        0 0">>/etc/fstab
                    mount -a
                fi
            fi
            break
        fi
      else
        if [ $(cat /etc/fstab|awk '{print $1}' |grep -E "/dev/${DK}|$(lsblk -f --output NAME,KNAME,TYPE,UUID /dev/${DK}|grep disk|awk '{print $4}'|head -n 1)"|wc -l) -eq 0 ]
          then
            if [ ! -d ${mount_home} ]
              then
                mkdir -p ${mount_home}
            fi
            if [ "$(cat /etc/fstab |awk '{print $2}'|grep /${mount_home})x" == "x" ]
              then
                UUID=$(lsblk -f --output TYPE,UUID  /dev/${DK}|grep disk|awk '{print $2}')
                FSTYPE=$(lsblk -f --output FSTYPE,TYPE,UUID  /dev/${DK}|grep disk|awk '{print $1}')
                echo "UUID=${UUID} ${mount_home}                    ${FSTYPE}    defaults        0 0">>/etc/fstab
                mount -a
            fi
        fi
    fi
  done
}

#######################磁盘挂载初始化模块######################

#######################用户权限始化模块######################
#创建用户


#创建数据目录和权限


#######################用户登陆限制模块######################

function ROOT(){
#禁止root登录
    is_permitrootlogin=$(/usr/bin/sed -ne '/^PermitRootLogin.*$/p' /etc/ssh/sshd_config |wc -l)
    is_allowusers=$(/usr/bin/sed -ne '/^AllowUsers.*$/p' /etc/ssh/sshd_config | wc -l)
    if [ $is_permitrootlogin -eq 0 ] ; then 
        sed -i '/#MaxSessions 10/a\PermitRootLogin no' /etc/ssh/sshd_config
    else 
        sed -i 's/^PermitRootLogin.*$/PermitRootLogin no/' /etc/ssh/sshd_config
    fi
    if [ $is_allowusers -eq 0 ] ; then 
        sed -i '/PermitRootLogin no/a\AllowUsers *@218.6.242.42 *@182.150.28.2 *@111.231.205.90' /etc/ssh/sshd_config
    else 
        sed -i 's/^AllowUsers.*$/AllowUsers *@218.6.242.42 *@182.150.28.2 *@111.231.205.90/' /etc/ssh/sshd_config
    fi
    if [ "$(grep '.*staff.*NOPASSWD.*' /etc/sudoers)x" == "x" ]
      then
        sed -i '/# %wheel\tALL=(ALL)\tNOPASSWD: ALL/a\staff\t\tALL=(ALL)\tNOPASSWD: ALL' /etc/sudoers
    fi
    systemctl restart sshd.service
    LOG ${LOG_RUN} '已禁用root登陆,且其他用户只能从218.6.242.42登录'
}

#######################用户登陆限制模块######################

#######################主程序入口模块######################

main()
{
    Basics
#    DK_CH '/data'
#    USER
#    ROOT
}

main
#######################主程序入口模块######################

