Centos6&7 初始化脚本

#!/bin/bash

# 获取系统信息
function get_centos_info(){
    centos_info=$(cat /etc/redhat-release)
    centos_version_main=$(echo $centos_info | awk -F ' ' '{print $4 }'|awk -F . '{print $1}')
}
get_centos_info

# 获取ip信息
function get_ip(){
    if [[ $centos_version_main == "7" ]]; then
        # 网络设备号需要自行修改
        lan_ip=$(/sbin/ifconfig ens192 | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addrs")
    elif [[ $centos_version_main == "6" ]]; then
        lan_ip=$(/sbin/ifconfig ens192 | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addrs")
    fi
}
get_ip

# 设置主机名
function set_hostname(){
    read -p "请设置主机名: " var_hostname
    hostnamectl set-hostname  $var_hostname
    if  [[ $centos_version_main == "7" ]]; then
        echo $var_hostname > /etc/hostname
    elif  [[ $centos_version_main == "6" ]]; then
        sed -i "/^HOSTNAME=/ c\HOSTNAME=$var_hostname" /etc/sysconfig/network  # centos6
    fi
}

# 设置软件源
function set_yum_repos(){
    if  [[ $centos_version_main == "7" ]]; then
    # Base源
        curl -s -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    # epel源
        yum install -y epel-release
        curl -s -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
    elif [[ $centos_version_main == "6" ]]; then
        # base
        curl -s -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
        # epel
        yum install -y epel-release
        curl -s -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-6.repo
    fi
}

# 更新系统及安装常用软件
function install_software(){
    yum remove firewalld python-firewall  python-firewall -y
    yum upgrade -y
    yum install -y \
    sysstat lsof \
    psmisc \
    expect \
    wget tree vim dos2unix jq bash-completion \
    ntp ntpdate crontabs
}

# 设置selinux,完成后需手动重启服务器
function set_selinux(){
    getenforce | grep -i 'enforcing' && setenforce 0
    sed -i '/^SELINUX=/ c\SELINUX=disabled' /etc/selinux/config
    sed -i '/^SELINUX=/ c\SELINUX=disabled' /etc/sysconfig/selinux
}

# 关闭防火墙
function set_firewall(){
    if [[ $centos_version_main == "7" ]]; then
        systemctl stop firewalld
        systemctl disable firewalld
    elif [[ $centos_version_main == "6" ]]; then
        service iptables stop
        chkconfig iptables off
    fi
}

# 设置语言,自定义命令提示符,和histroy日志格式
function set_public(){
echo "\
HISTTIMEFORMAT='[%F %T] '
HISTSIZE=10000
HISTCONTROL=ignoredups
LANG=en_US.UTF8
PS1='\n\e[1;37m[\e[m\e[1;32m\u\e[m\e[1;33m@\e[m\e[1;35m\H\e[m:\e[4m\$(pwd)\e[m\e[1;37m]\e[m\e[1;36m\e[m\n> '
" >> /etc/bashrc

#PS1='\[\033[38;5;87m\]\u\[$(tput bold)\]\[$(tput sgr0)\]\[\033[38;5;15m\]@\[$(tput sgr0)\]\[$(tput sgr0)\]\[\033[38;5;119m\]\h\[$(tput sgr0)\]\[\033[38;5;15m\] [\[$(tput sgr0)\]\[\033[38;5;198m\]\t\[$(tput sgr0)\]\[\033[38;5;15m\]] {\[$(tput sgr0)\]\[\033[38;5;81m\]\w\[$(tput sgr0)\]\[\033[38;5;15m\]}\n\[$(tput sgr0)\]\[\033[38;5;2m\]--\[$(tput sgr0)\]\[\033[38;5;118m\]>\[$(tput sgr0)\]\[\033[38;5;15m\]\\$ \[$(tput sgr0)\]'
# 参考地址 http://bashrcgenerator.com/
}


# 设置时区为 +8
function set_timezone(){
    cp -f /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
}

# crond
function set_crond(){
    if [[ $centos_version_main == "7" ]]; then
        systemctl start crond
        systemctl enable crond
    elif [[ $centos_version_main == "6" ]]; then
        service crond start
        chkconfig crond on
    fi
}

# ntpd
function set_ntpd(){
  # 添加阿里云的时间服务器
echo "\
restrict ntp1.aliyun.com nomodify notrap nopeer noquery
server ntp1.aliyun.com iburst minpoll 4 maxpoll 10
" >> /etc/ntp.conf

    if [[ $centos_version_main == "7" ]]; then
        systemctl start ntpd
        systemctl enable ntpd
    elif [[ $centos_version_main == "6" ]]; then
        service ntpd start
        chkconfig ntpd on
    fi
}

# auto_start
function set_auto_start(){
    if [[ $centos_version_main == "7" ]]
    then
        chmod +x /etc/rc.local
    fi
}

# sshd
function set_sshd(){
    # sshd_config
    # 1. 关闭远程连接时 DNS 的IP反向解析请求
    # 2. 远程会话时,保持连接
    cfg_file_sshd='/etc/ssh/sshd_config'
    cfg_cmd_nodns='UseDNS no'
    # 主替换命令
    sed -i '/UseDNS/ c\UseDNS no' $cfg_file_sshd
    # 备用替换命令
    # 配置文件,只检索 'UseDNS' 而不是'UseDNS no' , 因为UseDNS 和no可以不止一个空格
    grep "UseDNS" $cfg_file_sshd >/dev/null || echo "$cfg_cmd_nodns" >> $cfg_sshd
    # ssh客户端保持连接
    sed -i "/^#ClientAliveInterval 0/ c\ClientAliveInterval 60" $cfg_file_sshd
    sed -i "/^#ClientAliveCountMax 3/ c\ClientAliveCountMax 3" $cfg_file_sshd

    # 6 7 都通用的
    service sshd reload
    # if [[ $centos_version_main == "7" ]]; then
    #     systemctl reload sshd
    # elif [[ $centos_version_main == "6" ]]; then
    #     service sshd reload
    # fi
}

# limits
function set_limits(){
    # 阿里云 和 本地机房 都要优化
echo "\
# Default limit for number of user's processes to prevent
# accidental fork bombs.
# See rhbz #432903 for reasoning.

*          soft    nofile    65535
root       soft    nofile    unlimited
*          hard    nofile    100000
*          soft    nproc     65535
root       soft    nproc     unlimited
*          hard    nproc     200000\
" > /etc/security/limits.d/20-nproc.conf

    # CentOS6 的默认是 90-nproc.conf
    # CentOS7 的默认是 20-nproc.conf
}

# kernel
function set_kernel(){
cat >> /etc/sysctl.conf << EOF
net.ipv4.ip_forward = 1                     # 允许网卡之间的数据包转发
net.ipv4.tcp_syncookies = 1                 # 启用syncookies, 可防范少量syn攻击
net.ipv4.tcp_tw_reuse = 1                   # 允许重用time_wait的tcp端口
net.ipv4.tcp_tw_recycle = 1                 # 启用time_wait快速回收机制
net.ipv4.tcp_fin_timeout = 3                # fin_wait_2超时时间
net.ipv4.ip_local_port_range = 10000 65535  # 动态分配端口的范围
net.ipv4.tcp_max_tw_buckets = 5000          # time_wait套接字最大数量,高于该值系统会立即清理并打印警告信息
net.ipv4.tcp_max_syn_backlog = 10240        # syn队列长度
net.core.netdev_max_backlog = 10240         # 最大设备队列长度
net.core.somaxconn = 10240                  # listen()的默认参数, 等待请求的最大数量
net.ipv4.tcp_syn_retries = 2                # 放弃建立连接前内核发送syn包的数量
net.ipv4.tcp_synack_retries = 2             # 放弃连接前内核发送syn+ack包的数量
net.ipv4.tcp_max_orphans = 3276800          # 设定最多有多少个套接字不被关联到任何一个用户文件句柄上
net.ipv4.tcp_keepalive_time = 120           # keepalive idle空闲时间
net.ipv4.tcp_keepalive_intvl = 30           # keepalive intvl间隔时间
net.ipv4.tcp_keepalive_probes = 3           # keepalive probes最大探测次数
net.core.rmem_default = 8388608             # socket默认读buffer大小
net.core.wmem_default = 8388608             # socket默认写buffer大小
net.core.rmem_max = 16777216                # socket最大读buffer大小
net.core.wmem_max = 16777216                # socket最大写buffer大小
net.ipv4.tcp_rmem = 32768 436600 873200     # tcp_socket读buffer大小
net.ipv4.tcp_wmem = 8192 436600 873200      # tcp_socket写buffer大小
net.ipv4.tcp_mem = 177945 216076 254208     # 确定tcp栈应该如何反映内存使用
net.ipv4.tcp_fastopen = 3                   # 开启tcp_fastopen(内核 3.7 +)
fs.file-max = 500000000                     # 最大允许的文件描述符数量
kernel.core_uses_pid = 1                    # core文件名中添加pid作为扩展名
kernel.sysrq = 0                            # 关闭sysrq功能
kernel.msgmnb = 65536                       # 修改消息队列长度
kernel.msgmax = 65536
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-arptables = 1
EOF
modprobe br_netfilter
sysctl -p
}

# set vim
function set_vim(){
cat >> ~/.vimrc << EOF
set history=1000
autocmd InsertLeave * se cul
autocmd InsertLeave * se nocul
set nu
set bs=2
syntax on
set laststatus=2
set tabstop=4
set go=
set ruler
set showcmd
set cmdheight=1
hi CursorLine   cterm=NONE ctermbg=blue ctermfg=white guibg=blue guifg=white
set hls
set cursorline
set ignorecase
set hlsearch
set incsearch
set helplang=cn


inoremap ( ()<ESC>i
inoremap [ []<ESC>i
inoremap { {}<ESC>i
inoremap < <><ESC>i
inoremap " ""<ESC>i
inoremap ' ''<ESC>i
EOF
}

# 设置初始化状态,执行完毕之后,状态为1
function set_init_status(){
    echo "export INIT_STATUS=1" > /etc/profile.d/init_statu.sh
}

# 主函数
function main(){
    echo "本机系统为: ${centos_info}. ip为: ${lan_ip}."
    sleep 1

    set_hostname
    set_yum_repos # 阿里云不需
    install_software
    set_selinux  # 阿里云不需
    set_firewall
    set_public
    set_timezone  # 阿里云不需
    set_crond
    set_ntpd   # 阿里云不需
    set_auto_start
    set_sshd
    set_limits
    set_kernel
    set_vim
    set_init_status

    echo "\
    +-------------------------------------------------+
    |               optimizer is done                 |
    |   it's recommond to restart this server !       |
    +-------------------------------------------------+
    "
}
main

猜你喜欢

转载自www.cnblogs.com/knmax/p/9212465.html