whois.py 1.72 KB
Newer Older
1 2 3
#!/usr/bin/env python
#
# ULG - Universal Looking Glass
4
# (C) 2012 CZ.NIC, z.s.p.o.
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
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Imports
import os, sys
import re
import subprocess

import defaults

ASNAME_REGEX = '^\s*(as-name|ASName):\s*([^\s].*)\s*'
asname_regex = re.compile(ASNAME_REGEX)

asname_cache = {}

def lookup(key):
33 34 35
    os.environ['PYTHONIOENCODING'] = 'utf-8'
    s = subprocess.Popen([defaults.bin_whois, '-H', key],
                         stdout=subprocess.PIPE)
36 37 38 39 40 41 42

    res=''
    begin = False
    for l in s.stdout.readlines():
        if(re.match('^\s*$',l) and not begin):
            continue
        if(l[0] != '%'):
43
            res=res+l.decode('utf-8')
44 45 46 47 48 49 50 51
            begin = True

    return res

def lookup_as_name(asn):
    if asn in asname_cache:
        return asname_cache[asn]

52 53 54
    os.environ['PYTHONIOENCODING'] = 'utf-8'
    s = subprocess.Popen([defaults.bin_whois, '-H', asn],
                         stdout=subprocess.PIPE)
55 56 57 58 59

    for l in s.stdout.readlines():
        m = asname_regex.match(l)
        if(m):
            asname_cache[asn] = m.group(2)
60
            return m.group(2).decode('utf-8')
61 62

    return defaults.STRING_UNKNOWN