• Shell 脚本常用案例示例!


    1.Dos攻击防范(自动屏蔽攻击IP)

    #!/bin/bash
    DATE=$(date +%d/%b/%Y:%H:%M)
    LOG_FILE=/usr/local/nginx/logs/demo2.access.log
    ABNORMAL_IP=$(tail -n5000 $LOG_FILE |grep $DATE |awk '{a[$1]++}END{for(i in a)if(a[i]>10)print i}')
    for IP in $ABNORMAL_IP; do
        if [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; then
            iptables -I INPUT -s $IP -j DROP
            echo "$(date +'%F_%T') $IP" >> /tmp/drop_ip.log
        fi
    done

    2.Nginx 访问访问日志按天切割

    #!/bin/bash
    LOG_DIR=/usr/local/nginx/logs
    YESTERDAY_TIME=$(date -d "yesterday" +%F)
    LOG_MONTH_DIR=$LOG_DIR/$(date +"%Y-%m")
    LOG_FILE_LIST="default.access.log"
     
    for LOG_FILE in $LOG_FILE_LIST; do
        [ ! -d $LOG_MONTH_DIR ] && mkdir -p $LOG_MONTH_DIR
        mv $LOG_DIR/$LOG_FILE $LOG_MONTH_DIR/${LOG_FILE}_${YESTERDAY_TIME}
    done
     
    kill -USR1 $(cat /var/run/nginx.pid)

    3.Nginx访问日志分析脚本

    #!/bin/bash
    # 日志格式: $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"
    LOG_FILE=$1
    echo "统计访问最多的10个IP"
    awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10
    echo "----------------------"
     
    echo "统计时间段访问最多的IP"
    awk '$4>="[01/Dec/2018:13:20:25" && $4<="[27/Nov/2018:16:20:49"{a[$1]++}END{for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr|head -10
    echo "----------------------"
     
    echo "统计访问最多的10个页面"
    awk '{a[$7]++}END{print "PV:",length(a);for(v in a){if(a[v]>10)print v,a[v]}}' $LOG_FILE |sort -k2 -nr
    echo "----------------------"
     
    echo "统计访问页面状态码数量"
    awk '{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}' $LOG_FILE |sort -k3 -nr

    4.查看网卡实时流量脚本

    #!/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

    5.服务器系统配置初始化脚本

    #/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 -i '/SELINUX/{s/permissive/disabled/}' /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_syncookies = 1
    net.ipv4.tcp_max_tw_buckets = 20480
    net.ipv4.tcp_max_syn_backlog = 20480
    net.core.netdev_max_backlog = 262144
    net.ipv4.tcp_fin_timeout = 20  
    EOF
     
    # 减少SWAP使用
    echo "0" > /proc/sys/vm/swappiness
     
    # 安装系统性能分析工具及其他
    yum install gcc make autoconf vim sysstat net-tools iostat iftop iotp lrzsz -y

    6.监控MySQL主从同步状态是否异常脚本

    #!/bin/bash  
    HOST=localhost
    USER=root
    PASSWD=123.com
    IO_SQL_STATUS=$(mysql -h$HOST -u$USER -p$PASSWD -e 'show slave status\G' 2>/dev/null |awk '/Slave_.*_Running:/{print $1$2}')
    for i in $IO_SQL_STATUS; do
        THREAD_STATUS_NAME=${i%:*}
        THREAD_STATUS=${i#*:}
        if [ "$THREAD_STATUS" != "Yes" ]; then
            echo "Error: MySQL Master-Slave $THREAD_STATUS_NAME status is $THREAD_STATUS!" |mail -s "Master-Slave Staus" [url=mailto:xxx@163.com]xxx@163.com[/url]
        fi
    done

    7.目录文件变化监控和实时文件同步

    #!/bin/bash
     
    MON_DIR=/opt
    inotifywait -mqr --format %f -e create $MON_DIR |\
    while read files; do
       rsync -avz /opt /tmp/opt
       #echo "$(date +'%F %T') create $files" | mail -s "dir monitor" [url=mailto:xxx@163.com]xxx@163.com[/url]
    done

    8.一键查看服务器资源利用率

    #!/bin/bash
    function cpu() {
        NUM=1
        while [ $NUM -le 3 ]; do
            util=`vmstat |awk '{if(NR==3)print 100-$15"%"}'`
            user=`vmstat |awk '{if(NR==3)print $13"%"}'`
            sys=`vmstat |awk '{if(NR==3)print $14"%"}'`
            iowait=`vmstat |awk '{if(NR==3)print $16"%"}'`
            echo "CPU - 使用率: $util , 等待磁盘IO响应使用率: $iowait"
            let NUM++
            sleep 1
        done
    }
     
    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"
    }
     
    function disk() {
        fs=$(df -h |awk '/^\/dev/{print $1}')
        for p in $fs; do
            mounted=$(df -h |awk '$1=="'$p'"{print $NF}')
            size=$(df -h |awk '$1=="'$p'"{print $2}')
            used=$(df -h |awk '$1=="'$p'"{print $3}')
            used_percent=$(df -h |awk '$1=="'$p'"{print $5}')
            echo "硬盘 - 挂载点: $mounted , 总大小: $size , 使用: $used , 使用率: $used_percent"
        done
    }
     
    function tcp_status() {
        summary=$(ss -antp |awk '{status[$1]++}END{for(i in status) printf i":"status[i]" "}')
        echo "TCP连接状态 - $summary"
    }
     
    cpu
    memory
    disk
    tcp_status

    转载至这里:点击进入

  • 相关阅读:
    tp5 -- 微信公众号支付
    tp5对接支付宝支付简单集成
    tp5 -- 腾讯云cos简单使用
    PHP 递归无限极下级
    PHP 头部utf-8
    ThinkPHP5.0-多语言切换
    MySQL插入SQL语句后在phpmyadmin中注释显示乱码
    C#中练级orcle数据查询
    sql中递归查询
    sql server数据类型与其他数据库数据类型对应关系
  • 原文地址:https://www.cnblogs.com/maohedashu/p/15839564.html
Copyright © 2020-2023  润新知