OS/Solaris

Server TCP Connection Monitoring, Logging - Client IP, Count (w/ netstat, awk)

Lawmin 2014. 7. 14. 17:38

문서가 없는 상태에서 연동 시스템 조사가 필요하여 임시방편으로 만들어본 스크립트입니다.


tcp trace 를 설정해도 되겠지만, 시스템을 변경하기 부담될 때 쓸만할 것 같습니다.


아래 collect.sh 를 cron job 으로 걸어두면 주기적으로 netstat 실행해서 /oracle/netstat/result.txt 파일에 연결 정보를 저장합니다.


스크립트에는 영어로 간략히 usage를 적어보았지만, 대략 하는 일은 아래와 같습니다.


결과 형태 => ServerIP:ServerPORT,ClientIP=ConnectionCount


ServerIP:ServerPORT,ClientIP 를 키 값으로,

1) Key 값이 없었는데 새로 나타나면 추가

2) 마지막 ConnectionCount 보다 더 ConnectionCount 가 크면 수정합니다.


결국, 어디서 내 서버에 얼마나 많은 연결을 해오는지 알수 있습니다.

collect.sh 스크립트를 수정하여 시간대별로 남기도록 할 수 있습니다.


collect.sh

#!/usr/bin/bash

netstat -n -f inet | tail +5 | sort | /usr/xpg4/bin/awk -f /oracle/netstat/p2.awk > /oracle/netstat/result2.txt

sort /oracle/netstat/result2.txt > /oracle/netstat/result.txt

rm /oracle/netstat/result2.txt


p2.awk

BEGIN {

    while ((getline < "/oracle/netstat/result.txt") > 0) {

        split($1, piece, "=")

        lastCnt[piece[1]] = piece[2]

    }

}

{

    # last result sample

    # 192.168.2.173:22,192.168.2.109=1

    # 192.168.2.173:22,192.168.8.212=1


    # input format (sample format is below here, netstat )

    # 192.168.2.173.22   192.168.2.109.53551 15248     35 49640      0 ESTABLISHED

    # 192.168.2.173.22   192.168.8.212.53551 15248     45 49640      0 ESTABLISHED

    # 192.168.2.173.22   192.168.8.212.53551 15248     55 49640      0 ESTABLISHED

    # 192.168.2.173.23   192.168.2.172.37153 49640      0 49640      0 CLOSE_WAIT


    # need the result sorted after this ends (/usr/bin/awk borken)

    # $ netstat -n -f inet | tail +5 | sort | /usr/xpg4/bin/awk -f /oracle/netstat/p2.awk > /oracle/netstat/result.txt


    # this result sample

    # 192.168.2.173:22,192.168.2.109=1

    # 192.168.2.173:22,192.168.8.212=2

    # 192.168.2.173:23,192.168.2.172=1


    split($1, piece, ".")

    sIp = piece[1]"."piece[2]"."piece[3]"."piece[4]

    sPort = piece[5]

    split($2, piece, ".")

    cIp = piece[1]"."piece[2]"."piece[3]"."piece[4]

    scCnt[sIp":"sPort","cIp]++

}

END {

    for(key in scCnt) {

        if(lastCnt[key] == 0 || lastCnt[key] < scCnt[key]) {

            lastCnt[key] = scCnt[key]

        }

    }

    for (i in lastCnt) {

        print i"="lastCnt[i]

    }

}