shell脚本案例

一.服务器系统配置初始化

背景:新购买10台服务器并已安装linux操作

需求:

1)设置时区并同步时间

2)禁用selinux

3)清空防火墙默认策略

4)历史命令显示操作时间

5)禁止root远程登录

6)禁止定时任务发送邮件

7)设置最大打开文件数

8)减少Swap使用

9)系统内核参数优化

10)安装系统性能分析工具及其他

[root@shell ~]# mkdir shell_scripts
[root@shell ~]# cd shell_scripts/
[root@shell shell_scripts]# vim 1.sh
#!/bin/bash
#设置时区并同步时间
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
if ! crontab -l |grep ntpdate &>/dev/null ; then
    (echo " * 1 * * * ntpdate time.windows.com >/dev/null 2>&1";crontab -l)|crontab
fi
#禁用selinux
sed 's#SELINUX=enforcing#SELINUX=disabled#g' /etc/selinux/config
#关闭防火墙
if egrep "7.[0-9]" /etc/redhat-release &>/dev/null; then
    systemctl stop firewalld
    systemctl disable firewalld
elif egrep "6.[0-9]" /etc/redhat-release &>/dev/null; then
    service iptables stop
    chkconfig iptables off
fi
#历史命令显示操作时间
if ! grep HISTTIMEFORMAT /etc/bashrc; then
  echo 'export HISTTIMEFORMAT="%F %T `whoami` "' >>/etc/bashrc
fi
# SSH超时时间
if ! grep "TMOUT=600" /etc/profile &>/dev/null; then
  echo "export TMOUT=600" >> /etc/profile
fi
#禁止root远程登录(按公司规定)
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
#禁止定时任务向发送邮件
sed -i 's/^MAILTO=root/MAILTO=""/' /etc/crontab
#设置最大打开文件数
if ! grep "* soft nofile 65535" /etc/security/limits.conf &>/dev/null; then
  cat >> /etc/security/limits.conf << EOF
  * soft nofile 65535
  * hard nofile 65535
  EOF
fi
#系统内核优化
cat >>/etc/sysctl.conf <<EOF
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 = 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.ipv4.ip_forward = 1
EOF
#减少SWAP使用
echo "0" > /proc/sys/vm/swappiness 
#安装系统性能分析工具及其他
yum install -y gcc make autoconf vim sysstat net-tools iostat iotp lrzse

#如果有一些语法错误,可以先转换unix
[root@shell shell_scripts]# yum install -y dos2unix
[root@shell shell_scripts]# dos2unix 1.sh 
[root@shell shell_scripts]# ./1.sh
[root@shell shell_scripts]# source /etc/profile

二.发送告警邮件

外部邮箱服务器

[root@shell shell_scripts]# yum install mailx -y
[root@shell shell_scripts]# vim /etc/mail.rc 
... ...末尾添加
set from=cdaneee@163.com smtp=smtp.163.com
set smtp-auth-user=cdaneee@163.com smtp-auth-password=caodan20!
set smtp-auth=login

[root@shell shell_scripts]# echo "this is test mail."|mail -s "monitor" 757294876@qq.com

三.批量创建100个用户并设置密码

[root@shell shell_scripts]# cat 3.sh 
#!/bin/bash
USER_LIST=$@
USER_FILE=./user.info
for USER in $USER_LIST; do
 if ! id $USER &>/dev/null; then
   PASS=$(echo $RANDOM |md5sum |cut -c 1-8)
   useradd $USER
   echo $PASS | passwd --stdin $USER &>/dev/null
   echo "$USER  $PASS" >> $USER_FILE
   echo "$USER User create sucessful!"
 else
   echo "$USER User already exists!"
 fi
done

[root@shell shell_scripts]# sh 3.sh zhangsan lisi
Changing password for user zhangsan.
passwd: all authentication tokens updated successfully.
zhangsan User create sucessful!
Changing password for user lisi.
passwd: all authentication tokens updated successfully.
lisi User create sucessful!
[root@shell shell_scripts]# sh 3.sh zhangsan lisi
zhangsan User already exists!
lisi User already exists!

四.一键查看服务器利用率

cpu,内存,硬盘,tcp连接状态,

[root@shell shell_scripts]# cat 4.sh 
#!/bin/bash
function cpu() {
	util=$(vmstat |awk '{if(NR==3)print $13+$14}')
	iowait=$(vmstat |awk '{if(NR==3)print $16}')
	echo "CPU-使用率:${util}%,等待磁盘IO响应使用率:${iowait}%"
}
function memory() {
	total=$(free -m |awk '{if(NR==2)printf "%.1f",$2/1024}')
    used=$(free -m |awk '{if(NR==2)printf "%.1f",($2-$NF)/1024}')
    available=$(free -m |awk '{if(NR==2)printf "%.1f",$NF/1024}')
	echo "内存-总大小:${total}G,已使用:${used}G,剩余:${available}G"
}
disk() {
	fs=$(df -h |awk '/^\/dev/{print $1}')
    for p in $fs; do
		mounted=$(df -h |awk -v p=$p '$1==p{print $NF}')
		size=$(df -h |awk -v p=$p '$1==p{print $2}')
		used=$(df -h |awk -v p=$p '$1==p{print $3}')
        used_percent=$(df -h |awk -v p=$p '$1==p{print $5}')
        echo "硬盘-挂载点:$mounted,总大小:$size,已使用:$used,使用率:$used_percent"
    done
}
tcp_status() {
	summary=$(netstat -antp |awk '{a[$6]++}END{for(i in a)printf i":"a[i]" "}')
    echo "TCP连接状态-$summary"
}
cpu
memory
disk
tcp_status

[root@shell shell_scripts]# chmod +x 4.sh 
[root@shell shell_scripts]# sh 4.sh 
CPU-使用率:2%,等待磁盘IO响应使用率:0%
内存-总大小:1.9G,已使用:1.2G,剩余:0.7G
硬盘-挂载点:/,总大小:18G,已使用:12G,使用率:64%
硬盘-挂载点:/home,总大小:1014M,已使用:33M,使用率:4%
TCP连接状态-LISTEN:11 ESTABLISHED:2 established):1 Foreign:1 

五、找出占用cpu/内存过高的进程

[root@node ~]# cat cpu.sh 
#!/bin/bash
echo "----------------cpu top 10----------------"
ps -eo pid,pcpu,pmem,args --sort=-pcpu |head -n 10
echo "----------------memory top 10-------------"
ps -eo pid,pcpu,pmem,args --sort=-pmem |gead -n 10

六、查看网卡实时流量

[root@node ~]# cat 3.sh 
#!/bin/bash
NIC=$1
echo -e " In ------ Out"
while true; do
  OLD_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
  OLD_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
  sleep 1
  NEW_IN=$(awk '$0~"'$NIC'"{print $2}' /proc/net/dev)
  NEW_OUT=$(awk '$0~"'$NIC'"{print $10}' /proc/net/dev)
  IN=$(printf "%.1f%s" "$((($NEW_IN-$OLD_IN)/1024))" "KB/s")
  OUT=$(printf "%.1f%s" "$((($NEW_OUT-$OLD_OUT)/1024))" "KB/s")
  echo "$IN $OUT"
  sleep 1
done

七、监控100台服务器磁盘利用率

[root@node ~]# vim host.info      #把机器信息写进
192.168.15.54 root 22
192.168.15.55 root 22

[root@node ~]# vim 4.sh
#!/bin/bash
HOST_INFO=host.info
for IP in $(awk '/^[^#]/{print $1}' $HOST_INFO); do      
        USER=$(awk -v ip=$IP 'ip=$1{print $2}' $HOST_INFO)
        PORT=$(awk -v ip=$IP 'ip=$1{print $3}' $HOST_INFO)
        TMP_FILE=/tmp/disk.tmp
        ssh -p $PORT $USER@$IP 'df -h' > $TMP_FILE
        USE_RATE_LIST=$(awk 'BEGIN{OFS="="}/^\/dev/{print $NF,int($5)}' $TMP_FILE)
        for USE_PATE in $USE_PATE_LIST; do
          PART_NAME=${USE_PATH%=*}
          USE_PATE=${USE_PATE#*=}
          if [ $USE_PATE -ge 80 ]; then
             echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
          fi
        done
done

八、查看进程杀死重启

#!/bin/bash
#/restart.sh
 
echo [INFO] ===========1.cd 启动目录============
 
cd /work/linux64
 
pwd
 
echo [INFO] ===========2.赋值进程ID号===========
 
i=`ps -ef|grep -v grep|grep java|grep appadmin|awk '{print $2}'`
n=`ps -ef|grep -v grep|grep java|grep appadmin|wc -l`
echo $i
 
echo [INFO] ==========3.杀进程=========== 

while [[ $n -ne 0 ]];do
    echo [INFO] 杀进程中...
    pid=`ps -ef|grep -v grep|grep java|grep appadmin|awk '{print $2}'`
    sleep 1
    kill -9 ${pid}
    sleep 1
    n=`ps -ef|grep -v grep|grep java|grep appadmin|wc -l`
done;

procn=`ps -ef|grep -v grep|grep java|grep appadmin|wc -l`
if [ $procn -eq 0 ]
 then
  echo [INFO] ============$i已杀死=========
  echo [INFO] ===========4.start============
  echo "restart process: $1 and date is: `date`"
  exec ./start-normal64.sh&
  sleep 50
  cd ../onesearch
  exec ./start.sh&
  sleep 1
  cd ../AsposeConverter/Linux
  exec ./run.sh&
  echo [INFO] ===========启动成功===========
  else
  echo [INFO] ===========$i未杀死===========
fi

exit
posted @ 2021-09-21 20:45  小绵  阅读(117)  评论(0编辑  收藏  举报