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

### 关闭 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
    rm -f /etc/localtime
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    echo -e 'ZONE="Asia/Shanghai"\nUTC=false\nARC=false' >/etc/sysconfig/clock
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/CentOS6-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-6.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

### 优化启动服务
# 关闭系统自启动服务
for service in `chkconfig --list|grep 3:on|cut -f1`
do
    chkconfig --level 3 ${service} off
done

# 指定服务自启动
for service in crond rsyslog sshd network
do
    chkconfig --level 3 ${service} on
done

### 清理 spool 计划任务
mkdir -p /data/scripts
cat >/data/scripts/spool_clean.sh<<EOF
#!/bin/bash
find /var/spool/clientmqueue/ -type f -mtime +30|xargs rm -f
EOF

echo '*/30 * * * * /bin/bash /data/scripts/spool_clean.sh >/dev/null 2>&1'>>/var/spool/cron/root

### 内核优化
cat >/etc/sysctl.d/user-define.conf<<EOF
fs.file-max = 200500
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 = 1025  65534
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
EOF

cat >/etc/security/limits.d/10-limit.conf<<EOF
* soft nofile 204800
* hard nofile 204800
EOF

### 安装并配置 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 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
/usr/sbin/ntpdate -u cn.pool.ntp.org >/dev/null 2>&1
echo 'SYNC_HWCLOCK=yes' >>/etc/sysconfig/ntpd
sed -i 's/SYNC_HWCLOCK=.*/SYNC_HWCLOCK=yes/'  /etc/sysconfig/ntpdate

cat >/etc/ntp.conf<<EOF
# filename: ntp.conf

driftfile /var/lib/ntp/drift

restrict default kod nomodify notrap nopeer noquery
restrict -6 default kod nomodify notrap nopeer noquery

# Allow Address
#restrict 10.10.0.0 mask 255.255.0.0 nomodify notrap

restrict 127.0.0.1 
restrict -6 ::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
server 1.asia.pool.ntp.org iburst
server 2.asia.pool.ntp.org iburst
server 3.asia.pool.ntp.org iburst

server  127.127.1.0
fudge   127.127.1.0 stratum 10

includefile /etc/ntp/crypto/pw

keys /etc/ntp/keys
EOF

servie ntpd start
chkconfig ntpd on

### 安装常用软件
yum install -y virt-what lrzsz wget bzip2 unzip lsof htop nc mtr ipset

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

### 优化 openssh
# 更改监听端口
#sed -i "s/.*Port .*/Port ${SSH_PORT}/" /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/.*GSSAPICleanupCredentials yes/GSSAPICleanupCredentials no/' /etc/ssh/sshd_config
# 指定使用 ipv4
sed -i 's/.*AddressFamily .*/AddressFamily inet/' /etc/ssh/sshd_config
service sshd restart

### 自定义别名
cat > /etc/profile.d/user-define.sh <<EOF
mcd() { mkdir -p "\$1"; cd "\$1";}
alias ..="cd .."
alias ...="cd ../../"
alias listen="lsof -P -i -n"
alias ll="ls -al --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
VM_TYPE=$(virt-what)       # 虚拟化类型
if [[ "${VM_TYPE}" = "vmware" ]]
then
    yum -y install  open-vm-tools --enablerepo=epel
    service vmtoolsd restart
    chkconfig vmtoolsd on
fi
