• 9 个实用 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、Linux系统发送告警脚本
    $ yum install mailx
    $ vi /etc/mail.rc
    set from=baojingtongzhi@163.com smtp=smtp.163.com
    set smtp-auth-user=baojingtongzhi@163.com smtp-auth-password=授权码
    set smtp-auth=login
    
    # 发送消息测试
    $ echo "this is test mail" |mail -s "monitor" 145429520@qq.com
    # 可以看到145429520@qq.com邮箱已经收到了刚刚配置的baojingtongzhi@163.com 作为发件人发过来的邮件。
    
    3、MySQL数据库备份单循环
    #!/bin/bash
    DATE=$(date +%F_%H-%M-%S)
    HOST=localhost
    USER=backup
    PASS=123.com
    BACKUP_DIR=/data/db_backup
    DB_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "show databases;" 2>/dev/null |egrep -v "Database|information_schema|mysql|performance_schema|sys")
    
    for DB in $DB_LIST; do
        BACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sql
        if ! mysqldump -h$HOST -u$USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null; then
            echo "$BACKUP_NAME 备份失败!"
        fi
    done
    
    4、MySQL数据库备份多循环
    #!/bin/bash
    DATE=$(date +%F_%H-%M-%S)
    HOST=localhost
    USER=backup
    PASS=123.com
    BACKUP_DIR=/data/db_backup
    DB_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "show databases;" 2>/dev/null |egrep -v "Database|information_schema|mysql|performance_schema|sys")
    
    for DB in $DB_LIST; do
        BACKUP_DB_DIR=$BACKUP_DIR/${DB}_${DATE}
        [ ! -d $BACKUP_DB_DIR ] && mkdir -p $BACKUP_DB_DIR &>/dev/null
        TABLE_LIST=$(mysql -h$HOST -u$USER -p$PASS -s -e "use $DB;show tables;" 2>/dev/null)
        for TABLE in $TABLE_LIST; do
            BACKUP_NAME=$BACKUP_DB_DIR/${TABLE}.sql
            if ! mysqldump -h$HOST -u$USER -p$PASS $DB $TABLE > $BACKUP_NAME 2>/dev/null; then
                echo "$BACKUP_NAME 备份失败!"
            fi
        done
    done
    
    5、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)
    
    6、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]}}'
    
    7、查看网卡实时流量脚本
    #!/bin/bash
    while true
    do
    
    n=1
    while (($n<=$(cat /proc/net/dev | wc -l)))
    do    # 获取当前时刻网口接收与发送的流量
        Rb_pre[$n]=$(cat /proc/net/dev | grep : | sed -n "${n}p" | awk '{print $2}')
        Rp_pre[$n]=$(cat /proc/net/dev | grep : | sed -n "${n}p" | awk '{print $3}')
        Tb_pre[$n]=$(cat /proc/net/dev | grep : | sed -n "${n}p" | awk '{print $10}')
        Tp_pre[$n]=$(cat /proc/net/dev | grep : | sed -n "${n}p" | awk '{print $11}')
        inet[$n]=$(cat /proc/net/dev | grep : | sed -n "${n}p" | sed 's/:/ /g' | awk '{print $1}')
        ((n+=1))
    done
    
    sleep 1
    
    m=1
    while (($m<=$(cat /proc/net/dev | wc -l)))
    do   # 获取1秒后网口接收与发送的流量
      Rb_next[$m]=$(cat /proc/net/dev | grep : | sed -n "${m}p" | awk '{print $2}')
        Rp_next[$m]=$(cat /proc/net/dev | grep : | sed -n "${m}p" | awk '{print $3}')
        Tb_next[$m]=$(cat /proc/net/dev | grep : | sed -n "${m}p" | awk '{print $10}')
        Tp_next[$m]=$(cat /proc/net/dev | grep : | sed -n "${m}p" | awk '{print $11}')
        ((m+=1))
    done
    clear
    
      echo -e "IP\t  RX-bytes\t   TX-bytes\t  RX-packets\t  TX-packets\t  TIME"
    
    i=1
    while (( $i<=`expr ${#Rb_pre[*]} - 2`))
    do
      RXb[i]=$((Rb_next[i]-Rb_pre[i]))  #在$取值的时候,括号里面只需要跟变量即可(变量可自行进行计算)
      TXb[i]=$((Tb_next[i]-Tb_pre[i]))
    
      RXp[i]=$((Rp_next[i]-Rp_pre[i]))
      TXp[i]=$((Tp_next[i]-Tp_pre[i]))
    
    ipadd[i]=$(ifconfig ${inet[i]} | grep "inet " | awk '{print $2}')    #获取网卡IP地址
    
      if [ ${RXb[i]} -lt 1024 ];then
        RXb[i]="${RXb[i]}B/s"
      elif [ ${RXb[i]} -gt 1048576 ];then
        RXb[i]=$(echo ${RXb[i]} | awk '{print $1/1048576 "MB/s"}')
      else
        RXb[i]=$(echo ${RXb[i]} | awk '{print $1/1024 "KB/s"}')
      fi
     # 判断接收流量如果大于MB数量级则显示MB单位,否则显示KB数量级
      if [ ${TXb[i]} -lt 1024 ];then
        TXb[i]="${TXb[i]}B/s"
      elif [ ${TXb[i]} -gt 1048576 ];then
        TXb[i]=$(echo ${TXb[i]} | awk '{print $1/1048576 "MB/s"}')
      else
        TXb[i]=$(echo ${TXb[i]} | awk '{print $1/1024 "KB/s"}')
      fi
      
      if [ ${RXp[i]} -lt 1000 ];then
       RXp[i]=${RXp[i]}
      else
       RXp[i]=$(echo ${RXp[i]} | awk '{print $1/1000 "K"}')
       fi
    
      if [ ${TXp[i]} -lt 1000 ];then
       TXp[i]=${TXp[i]}
      else
       TXp[i]=$(echo ${TXp[i]} | awk '{print $1/1000 "K"}')
      fi
    
      echo -e "${ipadd[i]} \t ${RXb[i]} \t  ${TXb[i]} \t  ${RXp[i]} \t  ${TXp[i]} \t  `date +%k:%M:%S` "
    
      let "i++"
    done
    done
    
    8、服务器系统配置初始化脚本
    #/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 if
    
    9、监控100台服务器磁盘利用率脚本
    #!/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_RATE in $USE_RATE_LIST; do
            PART_NAME=${USE_RATE%=*}
            USE_RATE=${USE_RATE#*=}
            if [ $USE_RATE -ge 80 ]; then
                echo "Warning: $PART_NAME Partition usage $USE_RATE%!"
            fi
        done
    done
    
  • 相关阅读:
    Android Studio基本使用
    convlstm学习资料
    Java重写与重载
    Java继承的缺点
    long转int
    解决RubyMine中puts中文显示乱码的问题
    Ruby入门1
    Ruby学习笔记
    matplotlib绘制饼状图
    python强大的绘图模块matplotlib示例讲解
  • 原文地址:https://www.cnblogs.com/lvzhenjiang/p/16251352.html
Copyright © 2020-2023  润新知