Home > coding, python > IP WHOIS query via python

IP WHOIS query via python

this is a simple example (based on some 2006 rwhois code) how to get further information about an IP address:

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
import os, sys, string, time, getopt, socket, select, re, errno, copy, signal

def queryWhois(query, server='whois.ripe.net'):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    while 1:
        try:
            s.connect((server, 43))
        except socket.error, (ecode, reason):
            if ecode==errno.EINPROGRESS:
                continue
            elif ecode==errno.EALREADY:
                continue
            else:
                raise socket.error, (ecode, reason)
            pass
        break

    ret = select.select ([s], [s], [], 30)

    if len(ret[1])== 0 and len(ret[0]) == 0:
        s.close()
        raise TimedOut, "on data"

    s.setblocking(1)

    s.send("%s\n" % query)
    page = ""
    while 1:
        data = s.recv(8196)
        if not data: break
        page = page + data
        pass

    s.close()
   
    if string.find(page, "IANA-BLK") != -1:
        raise 'no match'
       
    if string.find(page, "Not allocated by APNIC") != -1:
        raise 'no match'
   
    return page
   
if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "usage: %s <IP address>" % sys.argv[0]
        sys.exit(1)
    ip = sys.argv[1]
   
    for server in ['whois.arin.net', 'whois.ripe.net', 'whois.apnic.net', 'whois.lacnic.net', 'whois.afrinic.net']:
        try:
            res = queryWhois(ip, server)
            print '======', server
            print res
            break # we only need the info once
        except:
            pass

just run it with the IP as argument

Categories: coding, python Tags:
  1. November 1st, 2012 at 15:39 | #1

    that's work great! thank you!

  1. No trackbacks yet.


five × 4 =