#!/s/bin/python -- # -*- python -*- # $Id: ipcat,v 1.6 2002-01-16 12:36:20-06 annis Exp $ # $Source: /u/annis/scripts/RCS/ipcat,v $ # # Copyright (c) 1998 - 2002 William S. Annis. All rights reserved. # This is free software; you can redistribute it and/or modify it # under the same terms as Perl (the Artistic Licence). Developed at # the Department of Biostatistics and Medical Informatics, University # of Wisconsin, Madison. """Cat stdout through a filter looking up IP addresses. """ import socket, sys, re, fileinput, string from signal import signal, alarm, SIGALRM # Register our timeout signal handler. class Timeout(Exception): pass def throw_timeout(sig, frame): raise Timeout(sig) signal(SIGALRM, throw_timeout) # Dictionary to cache addresses in. ips = {} # Return the resolved address if it exists, otherwise, just give back # the IP version. def lookup(addr): # If this address has been cached, use it; otherwise lookup into cache. if not ips.has_key(addr): # Assign the default first, which is just the IP. That is, # if this lookup fails, assume it will fail for the rest of # the run of the script. ips[addr] = addr try: # Don't wait too long for an answer. alarm(5) (ips[addr], more, ip) = socket.gethostbyaddr(addr) alarm(0) except socket.error: # Lookup failed. Reset alarm. alarm(0) except Timeout: # Lookup took too long. Move on. pass return ips[addr] # Use this precompiled regular expression to match IP addresses. ipregexp = re.compile(r"(?:.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))", re.DOTALL) def filter(line): """Filter a line's IP addresses into named addresses.""" splits = ipregexp.split(line) # This is very tricky: keep track of everything we split at. for splitpat in splits[:-1]: ip = string.strip(splitpat) newaddr = lookup(ip) if newaddr != ip: line = re.sub(re.escape(ip), newaddr, line) return line for line in fileinput.input(): print filter(line), # EOF