python compare ip range to host file

185 views Asked by At

I have a simple python script that compares a range using netaddr with the host file. I need to print the whole range and the matches. This as far as I can go. Snippet below:

ip_range = sys.argv[1]
host_file = open('/etc/hosts')
for ip in IPNetwork(ip_range).iter_hosts():
    ip_results.append('%s' % ip)

for Z in ip_results:
    for X in host_file:
        if Z in X:
            print Z, X

Something like this:

192.168.1.1 192.168.1.1 host1

192.168.1.2 192.168.1.2 host2

192.168.1.3

I would like to still print the IP even if there is no match. Any assistance would be greatly appreciated!

1

There are 1 answers

2
Paul Gowder On BEST ANSWER

Easy solution would be to initialize a match variable and then print the ip once if it doesn't turn on. For example:

for Z in ip_results:
    matching = 0
    for X in host_file:
        if Z in X:
            print Z, X
            matching = 1
    if matching == 0:
        print Z