2015년 8월 11일 화요일

리눅스 netstat 현재 접속 된 나라 확인.

#!/bin/bash

kisa_key="111111111111111111111";


IPLIST=`netstat -ant |grep "tcp" | awk '{print $5}' | cut -d: -f1 | sort | uniq`

for ip in $IPLIST
do
case "$ip" in
"0.0.0.0"|"127.0.0.1"|"8.8.8.8")
continue;;
*)
return_tmp_xml=`curl -s "http://whois.kisa.or.kr/openapi/ipascc.jsp?key=$kisa_key&query=$ip&answer=xml"`
countryCode=$(grep -oP "(?<=<countryCode>)[^<]+" <<< "$return_tmp_xml")
echo $ip : $countryCode
esac
done

예전에 위와 같이 KISA WHOIS 를 가지고 현재 접속된 나라를 찾았었는데,

geoiplookup 란 명령어가 있었다.

 

geoiplookup 명령어를 사용하려면 YUM 설치 하면 됨.

yum install GeoIP GeoIP-data

 

아래 처럼 하면 KISA KEY 받을 필요도 없고 좋다.
다만 몇몇개 IP는 'IP Address not found' 가 나온다.
#!/bin/bash



IPLIST=`netstat -ant |grep "tcp" | awk '{print $5}' | cut -d: -f1 | sort | uniq`

for ip in $IPLIST
do
case "$ip" in
"0.0.0.0"|"127.0.0.1"|"8.8.8.8")
continue;;
*)
geoiplookup $ip
esac
done

 

 

count 기능을 추가. 해당 아이피가 몇개가 접속해 있는 지 파악. (최종)
#!/bin/bash

#v2
#netstat -ant |grep "tcp" | awk '{print $5}' | cut -d: -f1 | grep -v "^$" | grep -v "0.0.0.0" | sort | uniq -c
netstat -ant |grep "tcp" | awk '{print $5}' | cut -d: -f1 | grep -v "^$" | grep -v "0.0.0.0" | grep -v "127.0.0.1" | sort | uniq -c > output.txt
while read -r line; do
count=$(echo $line | cut -f1 -d " ");
ip=$(echo $line | cut -f2 -d " ");
echo "count: $count, $ip : $(geoiplookup $ip)";
done < output.txt;
rm -rf output.txt

[root@mail foreignIp]# sh netstatIpCountryV2.sh 
count: 1, 108.168.211.204 : GeoIP Country Edition: IP Address not found
count: 1, 109.66.88.75 : GeoIP Country Edition: IP Address not found
count: 1, 112.173.207.169 : GeoIP Country Edition: IP Address not found
count: 3, 112.175.145.4 : GeoIP Country Edition: IP Address not found
count: 3, 112.221.136.253 : GeoIP Country Edition: IP Address not found
count: 1, 113.172.120.40 : GeoIP Country Edition: VN, Vietnam
...

 

참고

댓글 없음:

댓글 쓰기