17 个实用 shell 脚本,建议收藏( 三 )

12、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=$1echo "统计访问最多的10个IP"awk '{a[$1]++}END{print "UV:",length(a);for(v in a)print v,a[v]}' $LOG_FILE |sort -k2 -nr |head -10echo "----------------------" 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 -10echo "----------------------" 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 -nrecho "----------------------" echo "统计访问页面状态码数量"awk '{a[$7" "$9]++}END{for(v in a){if(a[v]>5)print v,a[v]}}' $LOG_FILE |sort -k3 -nr13、Nginx访问日志自动按天(周、月)切割#!/bin/bash#nginx日志目录LOG_DIR=/www/server/nginx/logs#获取到上一天的时间YESTERDAY_TIME=$(date -d "yesterday" +%F)#归档日志取时间LOG_MONTH_DIR=$LOG_DIR/$(date +"%Y-%m")#归档日志的名称LOG_FILE_LIST="access.log" for LOG_FILE in $LOG_FILE_LIST; do[ ! -d $LOG_MONTH_DIR ] && mkdir -p $LOG_MONTH_DIRmv $LOG_DIR/$LOG_FILE $LOG_MONTH_DIR/${LOG_FILE}_${YESTERDAY_TIME}done kill -USR1 $(cat $LOG_DIR/nginx.pid)14、自动发布JAVA项目(Tomcat)#!/bin/bashDATE=$(date +%F_%T) TOMCAT_NAME=$1TOMCAT_DIR=/usr/local/$TOMCAT_NAMEROOT=$TOMCAT_DIR/webapps/ROOT BACKUP_DIR=/data/backupWORK_DIR=/tmpPROJECT_NAME=tomcat-java-demo # 拉取代码cd $WORK_DIRif [ ! -d $PROJECT_NAME ]; thengit clone https://github.com/lizhenliang/tomcat-java-democd $PROJECT_NAMEelsecd $PROJECT_NAMEgit pullfi # 构建mvn clean package -Dmaven.test.skip=trueif [ $? -ne 0 ]; thenecho "maven build failure!"exit 1fi # 部署TOMCAT_PID=$(ps -ef |grep "$TOMCAT_NAME" |egrep -v "grep|$$" |awk 'NR==1{print $2}')[ -n "$TOMCAT_PID" ] && kill -9 $TOMCAT_PID[ -d $ROOT ] && mv $ROOT $BACKUP_DIR/${TOMCAT_NAME}_ROOT$DATEunzip $WORK_DIR/$PROJECT_NAME/target/*.war -d $ROOT$TOMCAT_DIR/bin/startup.sh15、自动发布PHP项目#!/bin/bash DATE=$(date +%F_%T) WWWROOT=/usr/local/nginx/html/$1BACKUP_DIR=/data/backupWORK_DIR=/tmpPROJECT_NAME=php-demo# 拉取代码cd $WORK_DIRif [ ! -d $PROJECT_NAME ]; thengit clone https://github.com/lizhenliang/php-democd $PROJECT_NAMEelsecd $PROJECT_NAMEgit pullfi# 部署if [ ! -d $WWWROOT ]; thenmkdir -p $WWWROOTrsync -avz --exclude=.git $WORK_DIR/$PROJECT_NAME/* $WWWROOTelsersync -avz --exclude=.git $WORK_DIR/$PROJECT_NAME/* $WWWROOTfi16、DOS攻击防范(自动屏蔽攻击IP)#!/bin/bashDATE=$(date +%d/%b/%Y:%H:%M)#nginx日志LOG_FILE=/usr/local/nginx/logs/demo2.access.log#分析ip的访问情况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; doif [ $(iptables -vnL |grep -c "$IP") -eq 0 ]; theniptables -I INPUT -s $IP -j DROPecho "$(date +'%F_%T') $IP" >> /tmp/drop_ip.logfidone17、目录入侵检测与告警#!/bin/bash MON_DIR=/optinotifywait -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" xxx@163.comdone





推荐阅读