#!/bin/bash
# 文件名: CentOS-7_init.sh
# 功能: CentOS-7系列 系统初始化脚本
# 作者: shuhui

### 定义变量
PC_TYPE=$(hostnamectl | awk '/Chassis/{print $2}')              # 系统底层类型
#VM_TYPE=$(hostnamectl | awk '/Virtualization/{print $2}')       # 虚拟化类型
VM_TYPE=$(systemd-detect-virt)                                  # 虚拟化类型


### 关闭 Selinux
if [[ "$(/usr/sbin/getenforce)" != "Disable" ]]
then
    /usr/sbin/setenforce 0 >/dev/null 2>&1
    sed -i 's/SELINUX=.*/SELINUX=disabled/' /etc/selinux/config
fi

### 设置时区
if [[ "$(date -R|awk '{print $NF}')" != "+0800" ]]
then
    timedatectl set-timezone "Asia/Shanghai"
fi

### 设置 yum 仓库源
cd /etc/yum.repos.d/
mkdir /etc/yum.repos.d/save >/dev/null 2>&1
mv *.repo ./save >/dev/null 2>&1
curl -s -L http://mirrors.163.com/.help/CentOS7-Base-163.repo -o ./CentOS-Base.repo;
#curl -s -L http://mirrors.aliyun.com/repo/Centos-7.repo -o ./CentOS-Base.repo ;
curl -s -L http://mirrors.aliyun.com/repo/epel-7.repo -o ./epel.repo;
# 删除epel 中的阿里云ECS 内部链接, 若是阿里云ECS，可以注释
sed -i "/aliyuncs/d" /etc/yum.repos.d/epel.repo
yum clean all && yum makecache fast && yum -y update

### 安装并配置 vim
yum -y install vim-enhanced
cat > /etc/vimrc <<end
" 设置编码
set encoding=utf-8
" 设置文件编码
set fileencodings=utf-8,cp936,ucs-bom
" 显示行号
set number
" 语法高亮
syntax on
" 自动缩进
"set autoindent
"set cindent
" 为程序提供自动缩进
"set smartindent
" 侦测文件类型
filetype on
" 最大历史数
set history=1000
" tab 宽度
set tabstop=4
" 统一缩进为4
set shiftwidth=4
" 显示标尺
set ruler
"搜索逐字符高亮
set hlsearch
set incsearch
" 不使用兼容模式 
set nocompatible
" 设置颜色模式
colorscheme desert
" 允许折叠
set foldenable
" 不使用空格代替tab
set expandtab
" 在行段与开始处使用制表符
set smarttab
" 搜索忽略大小写
set ignorecase
" 不生成临时文件
set noswapfile
" 不生成备份文件
set nobackup
end

### 配置 NTP
yum -y install ntp
cat >/etc/ntp.conf <<EOF
# filename: ntp.conf

driftfile  /var/lib/ntp/drift
pidfile   /var/run/ntpd.pid
logfile /var/log/ntp.log

interface ignore wildcard
interface listen lo

restrict default nomodify notrap nopeer noquery

# Allow Address
restrict 192.168.0.0 mask 255.255.0.0 nomodify notrap nopeer noquery
restrict 172.16.0.0 mask 255.240.0.0 nomodify notrap nopeer noquery
restrict 10.0.0.0 mask 255.0.0.0 nomodify notrap nopeer noquery
restrict 127.0.0.1 
restrict ::1

# NTP Server Address [Data From: http://www.ntp.org.cn/ http://www.pool.ntp.org/zone/asia]
server 0.asia.pool.ntp.org iburst minpoll 4 maxpoll 10
server 1.asia.pool.ntp.org iburst minpoll 4 maxpoll 10
server 2.asia.pool.ntp.org iburst minpoll 4 maxpoll 10
server 3.asia.pool.ntp.org iburst minpoll 4 maxpoll 10

server 127.127.1.0
fudge 127.127.0 stratum 10

includefile /etc/ntp/crypto/pw
keys /etc/ntp/keys
EOF

systemctl restart ntpd
systemctl enable ntpd

### 安装常用软件
yum install -y lrzsz wget bash-completion bzip2 unzip lsof htop mtr sysstat ipset lvm2

### 使用iptables 替代 firewalld
yum -y install iptables-services
/usr/bin/systemctl enable iptables
/usr/bin/systemctl start iptables
/usr/bin/systemctl disable firewalld

### 关闭 不必要的服务
#systemctl disable postfix.service lvm2-monitor.service auditd.service irqbalance.service
#systemctl stop postfix.service lvm2-monitor.service auditd.service irqbalance.service
systemctl disable postfix.service irqbalance.service
systemctl stop postfix.service irqbalance.service

### 设置日志历史数量及格式
echo -en "\n# Histroy log config\nexport HISTFILESIZE=10000\nexport HISTSIZE=10000\nexport PROMPT_COMMAND=\"history -a\"\nexport HISTTIMEFORMAT=\"\$(whoami) %F %T \"" > /etc/profile.d/logFormat.sh

### 登录终端的操作超时锁定策略
grep 'TMOUT' /etc/profile && sed -i 's/TMOUT.*/readonly TMOUT=600/' /etc/profile || echo -en '\n# Terminal Timeout\nreadonly TMOUT=600\n' >>/etc/profile

### 优化 openssh

# 更改监听端口
#sed -i "s/.*Port .*/Port ${SSH_PORT}/" /etc/ssh/sshd_config

# 安全策略
sed -i  -e 's/.*ClientAliveInterval.*/ClientAliveInterval 120/' \
        -e 's/.*ClientAliveCountMax.*/ClientAliveCountMax 3/' \
        -e 's/.*IgnoreRhosts.*/IgnoreRhosts yes/' \
        -e 's/.*HostbasedAuthentication.*/HostbasedAuthentication no/' /etc/ssh/sshd_config

# 添加免责声明
cat >/etc/issue.net<<EOF

*************************** DISCLAIMER *****************************
*                                                                  *
* This system is for the use of authorized users only.  Usage of   *
* this system may be monitored and recorded by system personnel.   *
*                                                                  *
* Anyone using this system expressly consents to such monitoring   *
* and is advised that if such monitoring reveals possible          *
* evidence of criminal activity, system personnel may provide the  *
* evidence from such monitoring to law enforcement officials.      *
*                                                                  *
********************************************************************
EOF

grep '^Banner' /etc/ssh/sshd_config || echo 'Banner /etc/issue.net' >>/etc/ssh/sshd_config

# 优化连接速度
sed -i -e 's/.*UseDNS yes/UseDNS no/' \
       -e 's/.*GSSAPIAuthentication yes/GSSAPIAuthentication no/' \
       -e 's/.*GSSAPICleanupCredentials yes/GSSAPICleanupCredentials no/' /etc/ssh/sshd_config

# 指定使用 ipv4
sed -i 's/.*AddressFamily .*/AddressFamily inet/' /etc/ssh/sshd_config

/usr/bin/systemctl restart sshd

### 安全策略
# 登录失败处理

sed -i -e '4aauth        required      pam_tally2.so deny=5 unlock_time=60' \
       -e '10aaccount     required      pam_tally2.so' /etc/pam.d/system-auth

sed -i -e '4aauth        required      pam_tally2.so deny=5 unlock_time=60' \
       -e '10aaccount     required      pam_tally2.so' /etc/pam.d/password-auth

# 密码策略
sed -i -e 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS   180/' \
       -e 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS   1/' \
       -e 's/^PASS_MIN_LEN.*/PASS_MIN_LEN   10/' \
       -e 's/^PASS_WARN_AGE.*/PASS_WARN_AGE   28/' /etc/login.defs

# 密码规则
cat >/etc/security/pwquality.conf<<EOF
minlen = 9
dcredit = -4
ucredit = -2
lcredit = -1
ocredit = -1
EOF

### DNS 配置

chattr -i /etc/resolv.conf
# 不使用NetworkManager控制DNS
grep "dns=none" /etc/NetworkManager/NetworkManager.conf >/dev/null || sed -i -e '/\[main\]/a\dns=none' /etc/NetworkManager/NetworkManager.conf

# 配置DNS
cat >/etc/resolv.conf<<EOF
options timeout:2 attempts:3 rotate single-request-reopen
### 参数注解
# timeout             　查询的最大的超时时间[缺省5秒，上限30秒]
# attempts            　尝试的次数[缺省2次，上限５秒]
# rotate　            　在nameserver 中进行轮循请求
# single-request-reopen 解析器为A和AAAA请求使用相同的套接字

nameserver 114.114.114.114
nameserver 114.114.115.115
EOF

# 保护DNS配置文件
chattr +i /etc/resolv.conf

### 设定终端历史记录
cat <<EOF>/etc/profile.d/history_command
export HISTFILE=\$HOME/.bash_history
export HISTSIZE=1200
export HISTFILESIZE=1200
export HISTCONTROL=ignoredups
export HISTTIMEFORMAT="`whoami` %F %T "
shopt -s histappend
typeset -r HISTIMEFORMAT
EOF

### 自定义别名
cat <<EOF>/etc/profile.d/user-define.sh
mcd() { mkdir -p "\$1"; cd "\$1";}
alias ..="cd .."
alias ...="cd ../../"
alias listen="lsof -P -i -n"
alias ll="ls -l --color=auto"
alias dstat='dstat -cdlmnpsy'
alias curld='curl -s -o /dev/null -w \
"
              请求时间:  '\$(date +%y-%m-%dT%T+08:00)'
            HTTP状态码:  %{http_code}
           DNS解析时间:  %{time_namelookup} s
          建立连接时间:  %{time_connect} s
          连接完成时间:  %{time_appconnect} s
          准备传输时间:  %{time_pretransfer} s
            重定向时间:  %{time_redirect} s
          传输开始时间:  %{time_starttransfer} s
        请求数据包大小:  %{size_request} Bytes
        下载数据包大小:  %{size_download} Bytes
          平均下载速度:  %{speed_download} Bytes/s
                         --------------
            消耗总时长:  %{time_total} s \n
"'
alias curlb='curl -s -o /dev/null -w \
"'\$(date +%y-%m-%dT%T+08:00)' %{http_code} %{time_namelookup} %{time_connect} %{time_appconnect} %{time_pretransfer} %{time_redirect} %{time_starttransfer} %{size_request} %{size_download} %{speed_download} %{time_total}\n"'
EOF

### 判断虚拟机类型为 vmware 时，安装 vm-tools
if [ "${VM_TYPE}" = "vmware" ]
then
    yum -y install  open-vm-tools --enablerepo=epel
    systemctl start vmtoolsd.service 
    systemctl enable vmtoolsd.service
fi
