实用脚本实例

1、编写脚本selinux.sh,实现开启或禁用SELinux功能

~]# cat selinux.sh 
#!/bin/bash
script=$(basename $0)
function usage(){
    echo -e "\nUSAGE: $SCRIPT [on | off] \n"
    exit 1
}

if [ $# -ne 1 ];then 
    usage
fi

if [ $1 == 'off' ];then 
    setenforce 0
    sed -i 's/^SELINUX=enforcing$/SELINUX=disabled/' /etc/selinux/config
fi

if [ $1 == 'on' ];then 
    setenforce 1
    sed -i 's/^SELINUX=disabled$/SELINUX=enforcing/' /etc/selinux/config
fi

echo -n "SELinux status: "
getenforce

~]# sh selinux.sh 
USAGE:  [on | off] 
~]# sh selinux.sh off
SELinux status: Permissive
~]# sh selinux.sh on
SELinux status: Enforcing

2、统计/etc/fstab文件中每个文件系统类型出现的次数

~]# cat fstab_stat.sh 
#!/bin/bash
declare -A fs_dict
while read LINE
do
   if [[ $LINE =~ ^#.* ]];then
      continue
   fi
   if [ -n "$LINE" ];then
      fs_type=$(echo $LINE | cut -d ' ' -f3)
      let fs_dict[$fs_type]++
   fi
done < /etc/fstab

for fs in ${!fs_dict[@]}
do
  echo "$fs=${fs_dict[$fs]}"
done

~]# cat /etc/fstab 
#
# /etc/fstab
# Created by anaconda on Thu Jul 18 04:17:15 2019
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root                        /        xfs     defaults        0 0
UUID=0cb71780-8808-412d-b756-1a1b9931af93      /boot    xfs     defaults        0 0
/dev/mapper/centos-swap                        swap     swap    defaults        0 0

~]# sh fstab_stat.sh 
swap=1
xfs=2

3、提取出字符串Yd$C@M05MB%9&Bdh7dq+YVixp3vpw中的所有数字

~]# cat str_seq.sh 
#!/bin/bash
str="Yd$C@M05MB%9&Bdh7dq+YVixp3vpw"
for i in `seq ${#str}`
do
   let idx=$i-1;
   charx=${str:$idx:1}
   if echo $charx | grep '[0-9]' &> /dev/null;then
      echo $charx
   fi
done

~]# sh str_seq.sh 
0
5
9
7
3

4、解决DOS攻击生产案例:根据web日志或者或者网络连接数,监控当某个IP 并发连接数或者短时内PV达到100,即调用防火墙命令封掉对应的IP,监控频 率每隔5分钟。防火墙命令为:iptables -A INPUT -s IP -j REJECT

~]# cat dos_filter.sh 
#!/bin/bash
 
iplist=`ss -tan state established '( sport = :80 )' | awk '{print $4}'| cut -d':' -f1 | sort | uniq -c | awk '{if($1>10)print $2}'`
for ip in $iplist
do
    iptables -A INPUT -s $ip -j REJECT
    echo "$ip is REJECT!"
done

# 定时每5分钟执行一次,对本地的http服务进行监控
~]# crontab -e
*/5 * * * * /bin/bash /root/dos_filter.sh 

# 在另外一台机器上,使用 apache 自带的压力测试工具 ab 模拟 http 并发请求
~]# ab -c 50 -n 100000 http://192.168.58.129/index.html  

你可能感兴趣的:(实用脚本实例)