Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # Copyright: ME!
- # License: The latest version of GPL as posted on the EFF website at the time
- # you copy this file. As of 2008, that is GPLv3.
- import re, sys
- from collections import defaultdict
- SE = sys.stderr
- "DOES NOT STRICTLY CHECK FOR SIMILARITIES LIKE 127.1 vs 127.0.0.1"
- comment_re = re.compile( r'^[ \t]*#.*$' )
- valid_re = re.compile( r'^(\d+\S+)[ \t]+(\w.*)+$' )
- alias_re = re.compile( r'^\w+(\.\w+)*$' )
- alias_mapping = defaultdict( list )
- #for noLine, line in enumerate( sys.stdin ):
- for noLine, line in enumerate( open('/tmp/hosts', 'rb') ):
- noLine += 1 # Humans think from 1, apparently.
- # To catch variances in frickin' whitespace. Fix your damn text editors,
- # people, and show your EOL whitespace!
- line = line.rstrip('\n')
- if not line:
- continue
- if comment_re.match( line ):
- continue
- match = valid_re.match( line )
- if match:
- ip4, aliases = match.groups()
- ip4 = ip4.split('.')
- if len( ip4 ) > 4:
- msg = "Line {}: Bad IPv4 address '{}'\n"
- SE.write( msg.format( noLine, ip4 ))
- else:
- for i in ip4:
- try:
- i = int( i );
- if not ( 0 <= i and i < 255 ):
- msg = "Line {}: Bad IPv4 address '{}'\n"
- SE.write( msg.format( noLine, ip4 ))
- break
- except:
- msg = "Line {}: Bad IPv4 address '{}'\n"
- SE.write( msg.format( noLine, ip4 ))
- break
- aliases = aliases.split()
- for alias in aliases:
- if not alias_re.match( alias ):
- msg = "Line {}: Invalid host alias name '{}'\n"
- SE.write( msg.format( noLine, alias ))
- elif alias.lower() != alias:
- msg = ('Line {}: Please use company standard lower case domain '
- "name in alias '{}'\n")
- SE.write( msg.format( noLine, alias ))
- alias_mapping[ alias ].append( '.'.join(ip4) )
- continue
- SE.write( "Line {}: Invalid syntax\n".format( noLine ))
- for alias, ip_addresses in sorted( alias_mapping.iteritems() ):
- if len( ip_addresses ) > 1:
- if len( set( ip_addresses )) == 1:
- msg = "Multiple definitions of alias '{}' to IP '{}'\n"
- SE.write( msg.format( alias, ip_addresses[0] ))
- else:
- msg = "Multiple IPs assigned to alias '{}': {}\n"
- SE.write( msg.format( alias, ', '.join( ip_addresses )))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement