WHOIS.PY

2016년 북한 관련 IP주소를 찾기 위하여 파이썬으로 처음 작성해본 코드입니다.

과거 python2로 작성된 코드를 최신 python3에서 동작하도록 일부 내용을 수정하고, 위치 정보를 얻기 위하여 사용한 freegeoip.net이 더 이상 동작하지 않는 관계로 일단 주석 처리해 놓았습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/python3
 
import sys
import os
import urllib.request
import json
import socket
 
def whois(ip):
    query = "http://whois.kisa.or.kr/openapi/whois.jsp?query=%s&key=2016042014355041149161&answer=json" % (ip)
 
    f = urllib.request.urlopen(query)
    r = f.read()
    f.close()
 
    return json.loads(r)
 
def whois2(ip, nic):
    if nic=="ARIN": srv = "whois.arin.net"
    elif nic=="APNIC": srv = "whois.apnic.net"
    elif nic=="LACNIC": srv = "whois.lacnic.net"
    elif nic=="RIPENCC": srv = "whois.ripe.net"
    elif nic=="AFRINIC": srv = "whois.afrinic.net"
    ip = ip + "\r\n"
 
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((srv, 43))
    s.send(ip.encode())
 
    r = ""
    while True:
        data = s.recv(4096)
        r += data.decode('utf-8')
        if not data:
            break
    s.close()
    
    t = r.replace(':''').upper().split()
 
    if "NETNAME" in t:
        ret = t[t.index("NETNAME"+ 1]
    elif "OWNERID" in t:
        ret = t[t.index("OWNERID"+ 1]
    else:
        ret = ""
 
    return ret
 
def geoip(ip):
    query = "http://freegeoip.net/json/%s" % (ip)
 
    f = urllib.request.urlopen(query)
    r = f.read()
    f.close()
 
    return json.loads(r)
 
 
line = sys.argv[1:]
 
if not line:
    line = sys.stdin.read().splitlines() 
else:
    if os.path.isfile(sys.argv[1]):
        f = open(sys.argv[1])
        line = f.read().splitlines()
        f.close()
    else:
        line=sys.argv[1].splitlines()
 
for ip in line:
    try:
        ip = socket.gethostbyname(ip)
        js = whois(ip)
        cc = js["whois"]["countryCode"]
        reg = js["whois"]["registry"]
 
        if reg=="KRNIC":
            if 'ISP' in js["whois"]["english"]:
                on = js["whois"]["english"]["ISP"]["netinfo"]["orgName"]
            elif 'PI' in js["whois"]["english"]:
                on = js["whois"]["english"]["PI"]["netinfo"]["orgName"]
 
            if 'user' in js["whois"]["korean"]:
                on = on + " : " + js["whois"]["korean"]["user"]["netinfo"]["orgName"]
 
        elif reg in ("ARIN""APNIC""LACNIC""RIPENCC""AFRINIC"):
            on = whois2(ip, reg)
        else:
            on = ""
 
#        if cc in ("CN", "JP"):
#            gjs = geoip(ip)
#            on = on + " : " + gjs["city"]
 
        print ("%s\t%s\t%s" % (ip, cc, on))
 
    except:
        print ("%s" % ip)


나스에 접근한 IP주소를 확인해보니, 불필요한 해외 접속 시도가 확인되네요.



댓글

이 블로그의 인기 게시물

mrjh76.run 도메인 등록

블로그 이전