#! /bin/sh
################################################
#Author:rolin
# qqinfo:992975991
# Date: 2021-1122
#version:1.0
#实现功能:一键系统优化17项脚本,适用于Centos8.x
################################################

#ConfigYum #配置阿里云YUM源
#initTools #安装常用工具
#installManChinese #安装man中文版本
#initCN_UTF8 #设置语言为中文
#initFirewall #关闭selinux,安装iptables
#initService  #精简化开机启动
#initSsh #ssh安全设置
#addSAUser  #增加管理员用户
#syncSystemTime #同步系统时间加入定时任务
#initHistory   #指定历史记录条数
#initChattr  #锁定文件系统
#openFiles #修改文件打开数
#optimizationKernel #优化系统内核参数
#init_safe #ctrl+alt+del 取消重启
#init_rc_local #centos7 rc.local文件执行权限设置
#disableIPV6 #关闭IPV6
#swapoff  #关闭交换分区
#set env
export PATH=$PATH:/bin:/sbin:/usr/sbin
export LANG=zh_CN.UTF-8
echo "welcome to server" >/etc/issue
 
#Require root to run this scripts.
if [[ "$(whoami)" != "root"  ]]; then
    echo "Please run this scripts as root." >&2
    exit 1
fi
 
#define cmd var
SERVICE=`which service`
CHKCONFIG=`which chkconfig`
 
#Source function library
. /etc/rc.d/init.d/functions
 
#Config Yum CentOS-Base.repo and epel-release
ConfigYum(){
    echo "####开始指定yum源####"
    cd /etc/yum.repos.d/
    \cp CentOS-Base.repo CentOS-Base.repo.$(date +%F)
    ping -c 1 baidu.com >/dev/null
    [ ! $? -eq 0  ] && echo $"Networking not configured - exiting" && exit 1
    wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo
 >/dev/null 2>&1
    yum -y install epel-release >/dev/null 2>&1
    yum clean all >/dev/null 2>&1
    yum makecache >/dev/null 2>&1
    sleep 1
}
 
#Install Init Packages
initTools(){
    echo "#####安装系统补装工具(选择最小化安装minimal)#####"
    ping -c 2 mirrors.aliyun.com
    sleep 2
    yum install tree nmap sysstat lrzsz dos2unix ipvsadm conntrack-tools libseccomp libtool-ltdl -y
    sleep 2
    rpm -qa tree nmap sysstat lrzsz dos2unix
    sleep 2
action "安装系统补装工具(选择最小化安装minimal)" /bin/true
echo "================================================="
echo ""
  sleep 2
}
 
#Install man chinese Packages
installManChinese(){
    echo "###安装中文语言包###"
    yum install man-pages-zh-CN.noarch  -y >/dev/null 2>&1
    [ $? -eq 0  ]&&action $"安装中文语言包:" /bin/true||action $"Install man chinese Packages:" /bin/false
    sleep 1
}
 
#Set Charset CN_UTF8
initCN_UTF8(){
    echo "####设置utf8 LANG="zh_CN.UTF-8"####"
    \cp /etc/locale.conf /etc/locale.conf.$(date +%F)
    sed -i 's#LANG="en_US.UTF-8"#LANG="zh_CN.UTF-8"#' /etc/locale.conf
    source /etc/locale.conf
    [ `grep zh_CN.UTF-8 /etc/locale.conf|wc -l` -eq 1  ]&&action $"设置utf8  Set Charset CN_UTF8:" /bin/true||action $"Set Charset CN_UTF8:" /bin/false
    sleep 1
}
 
#Close Selinux and Iptables
initFirewall(){
    echo "####关闭selinux和防火墙####"
    \cp /etc/selinux/config /etc/selinux/config.`date +"%Y-%m-%d_%H:%M:%S"`
    sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
    setenforce 0
    systemctl stop firewalld.service
    systemctl disable firewalld.service
    systemctl stop iptables.service
    systemctl status iptables.service
    grep SELINUX=disabled /etc/selinux/config
    echo "关闭selinux和防火墙完成!!!"
    sleep 1
}
 #Init Auto Startup Service
initService(){
echo "===============精简开机自启动===================="
  export LANG="en_US.UTF-8"
  for A in `chkconfig --list |grep 3:on |awk '{print $1}' `;do chkconfig $A off;done
  for B in rsyslog network sshd crond;do chkconfig $B on;done
  echo '+--------which services on---------+'
  chkconfig --list |grep 3:on
  echo '+----------------------------------+'
  export LANG="zh_CN.UTF-8"
echo "精简开机自启动完成"
echo "================================================="
echo ""
  sleep 2
}
#setting history and login timeout
initHistory(){
echo "======设置默认历史记录数和连接超时时间======"
echo "TMOUT=300" >>/etc/profile
echo "HISTSIZE=5" >>/etc/profile
echo "HISTFILESIZE=5" >>/etc/profile
tail -3 /etc/profile
source /etc/profile
action "设置默认历史记录数和连接超时时间" /bin/true
echo "================================================="
echo ""
sleep 2
}
initSsh(){
    echo "####初始化sshConfig配置####"
    \cp /etc/ssh/sshd_config /etc/ssh/sshd_config.$(date +%F%T)
    sed -i 's%#Port 22%Port 51020%' /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
    sed -i 's/^GSSAPIAuthentication yes$/GSSAPIAuthentication no/' /etc/ssh/sshd_config
	sed -i 's/#UseDNS yes/UseDNS no/' /etc/ssh/sshd_config
    egrep "UseDNS|1020|^PermitRootLogin|^PermitEmptyPasswords" /etc/ssh/sshd_config
    systemctl restart sshd && action $"--sshConfig--" /bin/true||action $"--sshConfig--" /bin/false
    sleep 1
}
 
#add user and give sudoers
addSAUser(){
echo "===================新建用户======================"
#add user
while true
do  
    read -p "请输入新用户名:" name
    NAME=`awk -F':' '{print $1}' /etc/passwd|grep -wx $name 2>/dev/null|wc -l`
    if [ ${#name} -eq 0 ];then
       echo "用户名不能为空,请重新输入。"
       continue
    elif [ $NAME -eq 1 ];then
       echo "用户名已存在,请重新输入。"
       continue
    fi
useradd $name
break
done
#create password
while true
do
    read -p "为 $name 创建一个密码:" pass1
    if [ ${#pass1} -eq 0 ];then
       echo "密码不能为空,请重新输入。"
       continue
    fi
    read -p "请再次输入密码:" pass2
    if [ "$pass1" != "$pass2" ];then
       echo "两次密码输入不相同,请重新输入。"
       continue
    fi
echo "$pass2" |passwd --stdin $name
break
done
sleep 1

#add visudo
echo "#####add visudo#####"
\cp /etc/sudoers /etc/sudoers.$(date +%F)
SUDO=`grep -w "$name" /etc/sudoers |wc -l`
if [ $SUDO -eq 0 ];then
    echo "$name  ALL=(ALL)       NOPASSWD: ALL" >>/etc/sudoers
    echo '#tail -1 /etc/sudoers'
    grep -w "$name" /etc/sudoers
    sleep 1
fi
action "创建用户$name并将其加入visudo完成"  /bin/true
echo "================================================="
echo ""
sleep 2
}
 
syncSystemTime(){
    echo "####同步系统时间####"
    if [ `grep /usr/sbin/ntpdate /var/spool/cron/root |grep -v grep |wc -l` -lt 1  ]; then
        echo "*/5 * * * * /sbin/ntpdate cn.pool.ntp.org >/dev/null 2>&1" >> /var/spool/cron/root
    fi
}

 
openFiles(){
    echo "####设置打开文件数限制####"
    \cp /etc/security/limits.conf /etc/security/limits.conf.$(date +%F_%T)
    if [ `grep -P "\*\t\t-\tnofile\t\t65535" /etc/security/limits.conf|wc -l` -lt 1 ]; then
    sed -i '/# End of file/i\*\t\t-\tnofile\t\t65535' /etc/security/limits.conf
    ulimit -HSn 65535
    fi
    echo "set maxnum openfiles successful"
    sleep 1
}
#chattr file system
initChattr(){
echo "======锁定关键文件系统======"
chattr +i /etc/passwd
chattr +i /etc/inittab
chattr +i /etc/group
chattr +i /etc/shadow
chattr +i /etc/gshadow
/bin/mv /usr/bin/chattr /usr/bin/lock
action "锁定关键文件系统" /bin/true
echo "================================================="
echo ""
sleep 2
}
 
#OPT system kernel
optimizationKernel(){
    echo "####优化系统内核####"
    \cp /etc/sysctl.conf /etc/sysctl.conf.$(date +%F_%T)
    if [ `grep "net.ipv4.ip_local_port_range = 1024 65535" /etc/sysctl.conf |wc -l` -lt 1 ]; then
cat >>/etc/sysctl.conf <<EOF
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_max_orphans = 3276800
net.core.wmem_default = 8288608
net.core.rmem_default = 8388608
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.core.netdev_max_backlog = 32768
net.core.somaxconn = 32768
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
#net.ipv4.tcp_tw_recycle = 1  #新版本内核不需要
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.ip_local_port_range = 10240 65000
#关于k8s
net.ipv4.ip_forward = 1
net.bridge.bridge-nf-call-ip6tables =1
net.bridge.bridge-nf-call-iptables =1
EOF
    fi
    modprobe bridge
    echo "modprobe bridge" >> /etc/rc.local
    #k8s需要开启
    modprobe br_netfilter
    modprobe ip_vs
    modprobe ip_vs_rr
    modprobe ip_vs_wrr
    modprobe ip_vs_sh
    modprobe nf_conntrack_ipv4
	echo "modprobe br_netfilter" >> /etc/rc.local
	echo "modprobe ip_vs" >> /etc/rc.local
	echo "modprobe ip_vs_rr" >> /etc/rc.local
	echo "modprobe ip_vs_wrr" >> /etc/rc.local
	echo "modprobe ip_vs_sh" >> /etc/rc.local
	echo "modprobe nf_conntrack_ipv4" >> /etc/rc.local
    sysctl -p >/dev/null 2>&1
    /sbin/sysctl -p && action $"Kernel OPT:" /bin/true ||action $"Kernel OPT:" /bin/false
    sleep 1
}
init_safe(){
    echo "####阻止ctrl+alt+del reboot system####"
    \rm -f /usr/lib/systemd/system/ctrl-alt-del.target
    /sbin/init q
    [ $? -eq 0  ]&&action $"forbid ctrl+alt+del reboot system:" /bin/true||action $"forbid ctrl+alt+del reboot system" /bin/false
    sleep 1
}
 
init_rc_local(){
    echo "#####添加--to /etc/rc.local execute permissions---####"
    chmod +x /etc/rc.d/rc.local
    [ $? -eq 0  ]&&action $"to /etc/rc.local execute permissions:" /bin/true||action $"to /etc/rc.local execute permissions:" /bin/false
    sleep 1
}
 
disableIPV6(){
    echo "####禁止--forbid use IPV6--使用"
    \cp  /etc/sysctl.conf /etc/sysctl.conf.$(date +%F_%T)
    cat >>/etc/sysctl.conf <<EOF
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
EOF
    [ $? -eq 0  ]&&action $"forbid use IPV6:" /bin/true||action $"forbid use IPV6:" /bin/false
    sysctl -p
    sleep 1
}
disableSwap(){
	echo "####关闭交换分区####"
	swapoff -a
	sed -ri '/^[^#]*swap/s@^@#@' /etc/fstab
}
cat <<EOF 
----------------------------------------
|****Please Enter Your Choice:[0-100]****|
----------------------------------------
(1) 指定YUM源
(2) 初始化安装包
(3) 安装中文字符包
(4) 修改字符设置
(5) 关闭防火墙和禁用selinux
(6) 精简开机启动选项
(7) 修改历史保留记录
(8) 修改ssh设置
(9) 添加SA用户
(10)  添加时间同步
(11) 加大文件描述符
(12) 锁定文件系统
(13) 优化内核
(14) 防止误操作
(15) 添加rc.local执行权限
(16) 禁止IPV6
(17) 关闭交换分区
(100) 安装所有
EOF

read -p "Please enter your Choice[0-15]: " option
echo -e "\nyour choose is: $option\n"
echo "after 5s start install......"
sleep 5
case $option in
    0)
      clear
  	  break
    ;;
    1)
      ConfigYum
    ;;
    2)
      initTools
    ;;
    3)
      installManChinese
    ;;
    4)
      initCN_UTF8
    ;;
    5)
     initFirewall
    ;;
    6)
      initService
    ;;
    7)
      initHistory
    ;;
    8)
      initSsh
    ;;
    9)
      addSAUser
    ;;
    10)
      syncSystemTime
    ;;
    11)
      openFiles
    ;;
    12)
      initChattr
    ;;
    13)
      optimizationKernel
    ;;
    14)
      init_safe
    ;;
    15)
      init_rc_local
    ;;
    16)
      disableIPV6
    ;;
    17)
      disableSwap
    ;;
      
    100)
      ConfigYum
	  initTools
	  installManChinese
	  initCN_UTF8
	  initFirewall
	  initService
	  initHistory
	  initSsh
	  addSAUser
	  syncSystemTime
	  openFiles
	  initChattr
	  optimizationKernel
	  init_safe
	  init_rc_local
	  disableIPV6
	  disableSwap
    ;;
    Q|q)
      exit
    ;;
    *)
      echo "Please input 1-100,thank you!"
      exit 1
    ;;
esac