countconn: add per-day count and optimize
authorgit <redacted>
Wed, 13 May 2026 11:56:43 +0000 (07:56 -0400)
committergit <redacted>
Wed, 13 May 2026 11:56:43 +0000 (07:56 -0400)
countconn

index f6d910522a59d353a2c2780d17178c6fb646ba4a..f79f791d838dc2f1678e2305dd6f8be20d369494 100755 (executable)
--- a/countconn
+++ b/countconn
@@ -1,17 +1,40 @@
 #!/bin/sh
 
-trap "exit 2" USR1
+trap "exit 1" USR1
+
+USAGE="usage: ${0} [-dm] [-l #]"
+
+usage() {
+       printf "%s\n" "$USAGE" >&2; exit 2
+}
 
 err() {
         printf "error: server not detected, needs to be set manually\n" >&2
         printf "set \$SERVER or modify the script itself\n" >&2
-        kill -USR1 "$$"
+       kill -USR1 "$$"
 }
 
+CUTCMD="-d: -f2,3"
+TAILN=30
+
+while getopts "dl:m" flag; do
+       case "$flag" in
+       d) CUTCMD="-d/ -f1,2" ;;
+       m) CUTCMD="-d: -f2,3" ;;
+       l)
+               if [ "$OPTARG" -eq "$OPTARG" ]; then
+                       TAILN="$OPTARG"
+               else
+                       usage
+               fi ;;
+       *) usage ;;
+       esac
+done
+
 # ... && ... || is not an if-then-else, but this works because
 # there's no way for only one printf to fail
 [ -z "$SERVER" ] && SERVER=$(which > /dev/null 2>&1 apache2 && printf "apache2" || which > /dev/null 2>&1 nginx && printf "nginx" || err)
 
-[ "$1" -eq "$1" ] 2>/dev/null && NUM="$1" || NUM=30
+CURDAY=$(tail -n1 /var/log/"$SERVER"/access.log | grep -oE "[0-9]{2}/.*/[0-9]{4}:")
 
-grep -o "\[.*\]" /var/log/"$SERVER"/access.log | cut -d: -f2,3 | uniq -c | tail -n"$NUM"
+{ cat /var/log/"$SERVER"/access.log /var/log/"$SERVER"/access.log.1; gzip -cd /var/log/"$SERVER"/access.log.*.gz; } | awk -v curday="$CURDAY" '$0 ~ curday { if (match($0, /[0-9]{2}\/.*\/[0-9]{4}:[0-9]{2}:[0-9]{2}:[0-9]{2}/)) { print substr($0, RSTART, RLENGTH) } next } { exit }' | cut $CUTCMD | uniq -c | tail -n"$TAILN"