11、SELinux与文本处理之awk

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

#!/bin/bash
status=`getenforce`
if [ $status == "Disabled" ];then
    echo "selinux当前状态为禁用状态"
    echo "selinux启动中..."
    sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
    echo "selinux已开启,请重启生效"
else
    echo "selinux当前状态不为禁用状态"
    echo "selinux禁用中"
    sed -i 's/^SELINUX=.*/SELINUX=Disabled/' /etc/selinux/config
    echo "selinux已禁用,请重启生效"
fi

执行结果:

[root@centos7 data]# ./selinux.sh 
selinux当前状态为禁用状态
selinux启动中...
selinux已开启,请重启生效
[root@centos7 data]# cat /etc/selinux/config 

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.
#     permissive - SELinux prints warnings instead of enforcing.
#     disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected. 
#     mls - Multi Level Security protection.
SELINUXTYPE=targeted 

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

awk '/^[^#]/ {print $3}' /etc/fstab|uniq -c

执行结果:

[root@centos7 data]# awk '/^[^#]/ {print $3}' /etc/fstab|uniq -c
      3 xfs
      1 swap
      1 ext4

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

[root@centos7 ~]# echo 'Yd$C@M05MB%9&Bdh7dq+YVixp3vpw'|tr -cd "[0-9]"

执行结果:

[root@centos7 ~]# echo 'Yd$C@M05MB%9&Bdh7dq+YVixp3vpw'|tr -cd "[0-9]"
05973

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

[root@centos7 data]# vim listenIP.sh
 #!/bin/bash
 netstat -ant|awk -F' ' '/ESTABLISHED/{print $5}'|awk -F: '{print $1}'|uniq -c > /data/access.log
 while read line
 do
     Num=`echo $line|awk '{print $1}'`
     IP=`echo $line|awk '{print $2}'`
     if ($Num >= 100);then
         iptables -A INPUT -s $IP -j REJECT
         echo "$IP is rejected."
     fi 
 done < /data/access.log

增加执行权限:chmod +x listenIP.sh
添加定时任务:vim /etc/crontab

[root@centos7 data]# vim /etc/crontab 
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
*/5 * * * * root /bin/bash /data/listenIP.sh

你可能感兴趣的:(11、SELinux与文本处理之awk)