生产实践:
用于Cobbler批量装机初始化脚本(centos6x可以直接使用)
学习技巧:
shell选择菜单 函数应用
脚本内容:
#!/bin/bash ############################################################ # $Name: system_init.sh # $Version: v1.0 # $Function: For System Init # $Author: Zhihe An # $Copyright (c) https://chegva.com # $Create Date: 2017-07-01 ############################################################ #Source function library. . /etc/init.d/functions #date DATE=`date +%Y-%m-%d_%H:%M:%S` #ip IPADDR=`ifconfig eth0 | awk -F "[ :]+" 'NR==2 {print $4}'` #hostname HOSTNAME=`hostname -s` #user USER=`whoami` #disk_check DISK_SDA=`df -h |grep -w "/" |awk '{print $5}'` #cpu_average_check cpu_uptime=`cat /proc/loadavg|awk '{print $1,$2,$3}'` #Require root to run this script. uid=`id | cut -d "=" -f2|cut -d "(" -f1` if [ $uid -ne 0 ];then action "Please run this script as root." /bin/false exit 1 fi #Config Yum CentOS-Bases.repo initYum(){ echo "================更新为国内YUM源==================" cd /etc/yum.repos.d/ cp CentOS-Base.repo CentOS-Base.repo.$(date +%F) ping -c 1 mirrors.aliyun.com > /dev/null if [ $? -eq 0 ];then wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo else echo "无法连接网络!" exit $? fi yum clean all yum makecache yum -y update #echo "==============保存YUM源文件======================" #sed -i 's#keepcache=0#keepcache=1#g' /etc/yum.conf #grep keepcache /etc/yum.conf #sleep 5 action "配置国内YUM完成" /bin/true echo "=================================================" echo "" sleep 2 } initTools(){ echo "#####安装系统补装工具(选择最小化安装minimal)#####" yum install -y epel-release yum-fastestmirror lrzsz jwhois screen net-tools vim wget tree pstree lsof telnet dos2unix yum install -y rpmforge-release yum install -y htop iotop iftop minicom cronolog sysstat iostat tcpdump yum install -y net-snmp-libs net-snmp-devel net-snmp net-snmp-util yum update -y action "安装系统补装工具完成" /bin/true echo "=================================================" echo "" sleep 2 } #Charset zh_CN.UTF-8 initI18n(){ echo "================更改为中文字符集=================" cp /etc/sysconfig/i18n /etc/sysconfig/i18n.$(date +%F) >/etc/sysconfig/i18n cat >>/etc/sysconfig/i18n<<EOF LANG="zh_CN.UTF-8" LANG="en_US.UTF-8" SYSFONT="latarcyrheb-sun16" EOF source /etc/sysconfig/i18n echo '#cat /etc/sysconfig/i18n' grep LANG /etc/sysconfig/i18n action "更改字符集zh_CN.UTF-8完成" /bin/true echo "=================================================" echo "" sleep 2 } initFirewall(){ echo "============禁用SELINUX及关闭防火墙==============" cp /etc/selinux/config /etc/selinux/config.$(date +%F) /etc/init.d/iptables stop sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config /bin/sed -i 's/^ca::ctrlaltdel:/#ca::ctrlaltdel:/' /etc/inittab setenforce 0 /etc/init.d/iptables status echo '#grep SELINUX=disabled /etc/selinux/config ' grep SELINUX=disabled /etc/selinux/config echo '#getenforce ' getenforce action "禁用selinux及关闭防火墙完成" /bin/true echo "=================================================" echo "" sleep 2 } #Init Auto Startup Service initAutoService(){ echo "===============精简开机自启动====================" 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 '+----------------------------------+' action "精简开机自启动完成" /bin/true echo "=================================================" echo "" sleep 2 } initNetwork(){ echo "===============配置DNS====================" case $dns in bj) echo "nameserver 202.106.46.151 nameserver 202.106.46.152" > /etc/resolv.conf action "BJ DNS配置配置完成" /bin/true ;; sjz) echo "nameserver 202.106.46.151 nameserver 202.106.46.152" > /etc/resolv.conf action "SJZ DNS配置配置完成" /bin/true ;; dg) echo "nameserver 202.96.128.86 nameserver 202.96.128.96" > /etc/resolv.conf action "DG DNS配置配置完成" /bin/true ;; *) echo "none $dns choice" exit;; esac } #Removal system and kernel version login before the screen display initRemoveVer(){ echo "======去除系统及内核版本登录前的屏幕显示=======" #must use root user run scripts if [ $UID -ne 0 ];then echo This script must use the root user ! ! ! sleep 2 exit 0 fi >/etc/redhat-release >/etc/issue action "去除系统及内核版本登录前的屏幕显示" /bin/true echo "=================================================" echo "" sleep 2 } #Change sshd default port and prohibit user root remote login. initSsh(){ echo "========修改ssh默认端口及相关参数==========" cp /etc/ssh/sshd_config /etc/ssh/sshd_config.$(date +%F) sed -i 's/#Port 22/Port 22288/g' /etc/ssh/sshd_config sed -i 's/#PermitEmptyPasswords no/PermitEmptyPasswords no/g' /etc/ssh/sshd_config #sed -i 's/#PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config sed -i 's/#UseDNS yes/UseDNS no/g' /etc/ssh/sshd_config sed -i 's/GSSAPIAuthentication yes/#GSSAPIAuthentication yes/g' /etc/ssh/sshd_config sed -i 's/GSSAPICleanupCredentials yes/#GSSAPICleanupCredentials yes/g' /etc/ssh/sshd_config echo '+-------modify the sshd_config-------+' echo 'Port 22288' echo 'PermitEmptyPasswords no' #echo 'PermitRootLogin no' echo 'GSSAPIAuthentication no' echo 'UseDNS no' echo '+------------------------------------+' /etc/init.d/sshd reload && action "修改ssh默认参数完成" /bin/true || action "修改ssh参数失败" /bin/false echo "=================================================" echo "" sleep 2 } #add init user initUser(){ for username in software upload do PWD=`openssl rand 32 -base64` useradd -m -d /data/$username $username echo ${PWD} | passwd --stdin $username echo "$username --> ${PWD}" >> ./users.log action "创建用户$username完成" /bin/true done #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 } initNTP(){ echo "================配置时间同步=====================" cp /var/spool/cron/root /var/spool/cron/root.$(date +%F) 2>/dev/null NTPDATE=`grep ntpdate /var/spool/cron/root 2>/dev/null |wc -l` if [ $NTPDATE -eq 0 ];then echo "#times sync by lee at $(date +%F)" >>/var/spool/cron/root echo "*/20 * * * * /usr/sbin/ntpdate pool.ntp.org >/dev/null 2>&1" >> /var/spool/cron/root /etc/init.d/ntpd restart hwclock --systohc hwclock -w fi echo '#crontab -l' crontab -l action "配置时间同步完成" /bin/true echo "=================================================" echo "" sleep 2 } #function set_snmp #{ ### build conf file ### #} initHistory(){ cat >>/etc/profile<<EOF PS1="[`whoami`@`hostname` "'$PWD]# ' history USER_IP=`who -u am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'` if [ "$USER_IP" = "" ] then USER_IP=`hostname` fi if [ ! -d /tmp/his ] then mkdir /tmp/his chmod 777 /tmp/his fi if [ ! -d /tmp/his/${LOGNAME} ] then mkdir /tmp/his/${LOGNAME} chmod 300 /tmp/his/${LOGNAME} fi export HISTSIZE=4096 export HISTFILESIZE=4096 #export HISTCONTROL=erasedups export HISTCONTROL=ignoredups #export HISTCONTROL=ignorespace export HISTIGNORE="pwd:ls:ls -al:ll:ls -a:" HISTTIMEFORMAT="%F %T `whoami` [$PWD] " export HISTTIMEFORMAT DT=`date +%Y-%m-%d_%H:%M:%S` export HISTFILE="/tmp/his/${LOGNAME}/${USER_IP}_his.${DT}" chmod 600 /tmp/his/${LOGNAME}/*his* 2>/dev/null # Set Alias Vi to Vim alias cp='cp -i' alias egrep='egrep --color' alias fgrep='fgrep --color' alias grep='grep --color' alias l='ls -AFhlt' alias l.='ls -d .* --color=auto' alias lh='l | head' alias ll='ls -l --color=auto' alias ls='ls --color=auto' alias mv='mv -i' alias rm='rm -i' alias vi='vim' EOF action "添加历史操作记录完成" /bin/true source /etc/profile } ##system optimize initOptimize(){ echo -e "ulimit -cunlimited" >> /etc/profile echo -e "ulimit -sunlimited" >> /etc/profile echo -e "ulimit -SHn 65535" >> /etc/profile source /etc/profile sed -i "s/net.ipv4.ip_forward = 0/net.ipv4.ip_forward = 1/g" '/etc/sysctl.conf' echo "================优化内核参数=====================" SYSCTL=`grep "net.ipv4.tcp" /etc/sysctl.conf |wc -l` if [ $SYSCTL -lt 10 ];then cp /etc/sysctl.conf /etc/sysctl.conf.$(date +%F) cat >>/etc/sysctl.conf<<EOF net.ipv6.conf.all.disable_ipv6 =1 fs.file-max = 12553500 fs.nr_open = 12453500 net.ipv4.tcp_fin_timeout = 2 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_tw_recycle = 0 net.ipv4.tcp_timestamps = 1 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_keepalive_time = 600 net.ipv4.ip_local_port_range = 4000 65000 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 net.netfilter.nf_conntrack_max = 25000000 net.netfilter.nf_conntrack_tcp_timeout_established = 180 net.netfilter.nf_conntrack_tcp_timeout_time_wait = 120 net.netfilter.nf_conntrack_tcp_timeout_close_wait = 60 net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 120 net.core.somaxconn =262144 net.core.netdev_max_backlog =262144 net.core.wmem_default =8388608 net.core.rmem_default =8388608 net.core.rmem_max =16777216 net.core.wmem_max =16777216 net.ipv4.netfilter.ip_conntrack_max = 131072 net.ipv4.netfilter.ip_conntrack_tcp_timeout_established = 180 net.ipv4.tcp_keepalive_time =120" net.ipv4.tcp_keepalive_probes= 3" net.ipv4.tcp_keepalive_intvl= 15" net.ipv4.tcp_max_tw_buckets =36000" net.ipv4.tcp_max_orphans =3276800" net.ipv4.tcp_max_syn_backlog= 262144" net.ipv4.tcp_wmem = 8192131072 16777216" net.ipv4.tcp_rmem = 32768131072 16777216" net.ipv4.tcp_mem = 94500000915000000 927000000" EOF fi cp /etc/rc.local /etc/rc.local.$(date +%F) modprobe nf_conntrack echo "modprobe nf_conntrack">> /etc/rc.local modprobe bridge echo "modprobe bridge">> /etc/rc.local sysctl -p ### limit ### echo " * soft nofile 50000 * hard nofile 65536 * soft nproc 50000 * hard nproc 50000 " >> /etc/security/limits.conf echo " * soft nproc 50000 root soft nproc unlimited " >> /etc/security/limits.d/90-nproc.conf action "内核调优完成" /bin/true echo "=================================================" echo "" sleep 2 } #install & config salt-minion initSaltMinion(){ cd /usr/local/src/ wget http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm rpm -ivh epel-release-6-8.noarch.rpm wget http://apt.sw.be/redhat/el6/en/x86_64/rpmforge/RPMS/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm rpm -Uvh rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm yum install python-jinja2 -y yum -y install salt-minion --enablerepo=epel-testing IP=`ifconfig eth0 | grep -i bcast | awk '{print $2}'| awk -F : '{print $2}'` HOSTNAME=`hostname` ID=$IP MASTER=xxx echo "master: $MASTER" >>/etc/salt/minion echo "id: $HOSTNAME" >> /etc/salt/minion service salt-minion restart chkconfig salt-minion on } #chattr file system initChattr(){ echo "======更改危险文件(命令)权限======" chmod 700 /bin/ping chmod 700 /usr/bin/who chmod 700 /usr/bin/w chmod 700 /usr/bin/{last,lastb,lastlog} chmod 700 /usr/bin/whereis chmod 700 /sbin/ifconfig chmod 700 /usr/bin/pico chmod 700 /usr/bin/{vi,vim} chmod 700 /usr/bin/which chmod 700 /usr/bin/gcc chmod 700 /usr/bin/make chmod 700 /bin/rpm chmod 700 /usr/bin/wget action "更改危险文件(命令)权限完成" /bin/true echo "=================================================" echo "======锁定关键文件系统======" chattr +i /etc/inittab chattr +i /etc/passwd chattr +i /etc/group chattr +i /etc/shadow chattr +i /etc/gshadow chattr +i /etc/hosts chattr +i /etc/resolv.conf chattr +i /etc/fstab chattr +i /etc/sudoers chattr +i /etc/inittab chattr +a /var/log/messages chattr +a /var/log/wtmp chattr +a /var/log/secure /bin/mv /usr/bin/chattr /usr/bin/lock /bin/mv /usr/bin/lsattr /usr/bin/unlock chattr -R +i /bin /boot /lib /sbin chattr -R +i /usr/bin /usr/include /usr/lib /usr/sbin action "锁定关键文件系统" /bin/true echo "=================================================" echo "" sleep 2 } #menu2 menu2(){ while true do clear cat <<EOF ---------------------------------------- |****Please Enter Your Choice:[0-13]****| ---------------------------------------- (1) 新建用户并将其加入visudo (2) 配置为国内YUM源镜像和保存YUM源文件 (3) 安装系统补装工具(选择最小化安装minimal) (4) 配置中文字符集 (5) 禁用SELINUX及关闭防火墙 (6) 精简开机自启动 (7) 去除系统及内核版本登录前的屏幕显示 (8) 修改ssh默认端口及禁用root远程登录/GSSAPI认证/DNS解析 (9) 设置时间同步 (10) 系统内核调优 (11) 锁定关键文件系统及更改危险文件(命令)权限 (12) 记录所有登录用户终端操作命令记录 (13) 安装并配置salt-minion (0) 返回上一级菜单 EOF read -p "Please enter your Choice[0-13]: " input2 case "$input2" in 0) clear break ;; 1) initUser ;; 2) initYum ;; 3) initTools ;; 4) initI18n ;; 5) initFirewall ;; 6) initAutoService ;; 7) initRemoveVer ;; 8) initSsh ;; 9) initNTP ;; 10) initOptimize ;; 11) initChattr ;; 12) initHistory ;; 13) initSaltMinion ;; *) echo "----------------------------------" echo "| Warning!!! |" echo "| Please Enter Right Choice! |" echo "----------------------------------" for i in `seq -w 3 -1 1` do echo -ne "\b\b$i"; sleep 1; done clear esac done } #menu while true do clear echo "===============================================" echo ' Linux System Optimization ' echo "===============================================" cat << EOF |-----------System Infomation----------- | DATE :$DATE | HOSTNAME :$HOSTNAME | USER :$USER | IP :$IPADDR | DISK_USED :$DISK_SDA | CPU_AVERAGE:$cpu_uptime ---------------------------------------- |****Please Enter Your Choice:[1-3]****| ---------------------------------------- (1) 一键优化 (2) 自定义优化 (3) 退出 EOF #choice read -p "Please enter your choice[0-3]: " input1 case "$input1" in 1) initUser initYum initTools initI18n initFirewall initAutoService initRemoveVer initSsh initNTP initOptimize initChattr initHistory initSaltMinion ;; 2) menu2 ;; 3) clear break ;; *) echo "----------------------------------" echo "| Warning!!! |" echo "| Please Enter Right Choice! |" echo "----------------------------------" for i in `seq -w 3 -1 1` do echo -ne "\b\b$i"; sleep 1; done clear esac done
◎查看效果
◎生产应用参考:
2.自动化安装部署一
3.自动化安装部署二