synology surveillance 用户连接实时推送 来访者IP信息

首页 / 默认分类 / 正文

job.sh

#!/bin/bash

# 设置日志文件路径和Bark API Key
LOG_FILE="/volume1/homes/langke/Connoutput.txt"
BARK_API_KEY="xxxxxxxxxx"//修改为你的BARK_API_KEY
SENT_IPS_FILE="/volume1/homes/langke/sent_ips.txt"
NOTIFICATION_INTERVAL=60  # 30分钟(单位:秒)

# 初始化文件
touch "$SENT_IPS_FILE"
# 本地IP段正则表达式(新增部分)
LOCAL_IPS_REGEX='^(::ffff:(10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|127\.)|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|127\.0\.0\.1|::1|fe80:|fc00:|fd00:)'

while true; do
    CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
    CURRENT_TIMESTAMP=$(date +%s)
     
    # 获取当前连接的IP并过滤本地地址(关键修改)
    IPS=$(sudo netstat -atnpW | grep ESTABLISHED | grep ':5001' | awk '{print $5}' | sed 's/:[0-9]*$//' | sort | uniq | grep -vE "$LOCAL_IPS_REGEX")
    for IP in $IPS; do
        NEED_NOTIFY=true
        if grep -q "^$IP " "$SENT_IPS_FILE"; then
            LAST_SENT=$(grep "^$IP " "$SENT_IPS_FILE" | awk '{print $2}')
            TIME_DIFF=$((CURRENT_TIMESTAMP - LAST_SENT))
            if [ $TIME_DIFF -lt $NOTIFICATION_INTERVAL ]; then
                NEED_NOTIFY=false
            fi
        fi

        LOCATION=$(/volume1/homes/langke/get_ip_location.sh <<< "$IP")
        echo "[$CURRENT_TIME] IP: $IP, Location: $LOCATION" >> "$LOG_FILE"
        
        if $NEED_NOTIFY; then
            MESSAGE="Time: $CURRENT_TIME, $LOCATION"
            curl -s -X POST https://api.day.app/$BARK_API_KEY/ \
                 -d "title=群晖连接通知" \
                 -d "group=nas_alert" \
                 -d "body=$MESSAGE" >/dev/null 
            # 更新记录
            sed -i "/^$IP /d" "$SENT_IPS_FILE"
            echo "$IP $CURRENT_TIMESTAMP" >> "$SENT_IPS_FILE"
        fi
    done
    
    # 清理超过30分钟未连接的记录
    while read -r RECORD; do
        RECORD_IP=$(echo "$RECORD" | awk '{print $1}')
        RECORD_TIME=$(echo "$RECORD" | awk '{print $2}')
        TIME_DIFF=$((CURRENT_TIMESTAMP - RECORD_TIME))
        if [ $TIME_DIFF -gt $NOTIFICATION_INTERVAL ]; then
            sed -i "/^$RECORD_IP /d" "$SENT_IPS_FILE"
        fi
    done < <(cat "$SENT_IPS_FILE")
    
    sleep 5
done

get_ip_location

#!/bin/bash

# API URL for querying IP location https://ip.zxinc.org/api.php?type=json&ip=
API_URL="http://ip.mir6.com/api/api_json.php?ip="

query_ip_location() {
    local ip=$1
    # Fetch the JSON response from the API
    local response=$(curl -s "$API_URL$ip&token=mir6.com")
    
    # Extract country and city information using jq
    local country=$(echo "$response" | jq -r '.data.country')
    local isp=$(echo "$response" | jq -r '.data.isp')
    local location=$(echo "$response" | jq -r '.location')
    # Output the result
    echo "IP: $ip, $isp Location: $location"
}

# Read IPs from input and query their locations
while read -r ip; do
    query_ip_location "$ip"
done < /dev/stdin

https://img.gzmiyue.cn/20250815081935832.sh
https://img.gzmiyue.cn/20250815081950102.sh

无标签
评论区
头像