AI智能
改变未来

shell脚本和awk实践


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

#!/bin/bash[ $# -ne 1 ] && {echo \'Useage: selinux on | off | enable | disable\'exit}case $1 inon)setenforce 1 && echo \"SELinux has been turn on temporary.\";;off)setenforce 0 && echo \"SELinux has been turn off temporary.\";;enable)setenforce 1sed -i \'s/SELINUX=disabled/SELINUX=enforcing/\' /etc/selinux/configecho \"SELinux has been enabled,you need reboot mechine to make it work.\";;disable)setenforce 0sed -i \'s/SELINUX=enforcing/SELINUX=disabled/\' /etc/selinux/configecho \"SELinux has been disabled,you need reboot mechine to make it work.\";;*)echo \'Useage: selinux on | off | enable | disable\'esac

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

# 第一种方法egrep -v \'^#|^$\' /etc/fstab | awk \'{print $3}\' | sort -r | uniq -c# 第二种方法awk -F\" \" \'/^UUID|^\\/dev/{print $3}\' /etc/fstab | uniq -c | sort -r

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

echo \"Yd$C@M05MB%9&Bdh7dq+YVixp3vpw\" | awk \'{gsub(/[^0-9]/,\"\"); print $0}\'

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

# blockip.sh#! /bin/bashss -tan | awk -F \" +|:\" \'/ESTAB/{ip[$(NF-2)]++}END{for(i in ip)if(ip[i]>99) print i}\' > /tmp/BlockIP.logwhile read IP;doiptables -A INPUT -j REJECT -s $IPecho \"`date +\'%F %T\'`    $IP reject\" >> /tmp/BlockList.txtdone < /tmp/BlockIP.log# 给脚本添加执行权限chmod u+x blockip.sh# 添加计划任务echo \'* */12 * * 1-5 /root/blockip.sh\' >> /var/spool/cron/root
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » shell脚本和awk实践