[python] resolve a list of items from file

The list can be ip address, ip address range, ip subnet, firewall objects or hostname.
The objective:

  • If item is resolvable, resolve it and collect the ip address.
  • If item is unresolvable, will collect it as it is.

The list of items must be separated by commas else it will not work.

import socket


def host_processing(host):
    # Initialize to nothing, if hostname is not resolvable answer will at least contain a null string.
    answer = ""
    try:
        answer = socket.gethostbyname(host)
    except Exception:
        # If not resolvable, dun care.
        pass

    # if answer is not null string, or host is an ip address
    # gethostbyname will return the same ip address you put in.
    if answer:
        return answer
    else:  # if there is no answer, or if host is a subnet or range
        return host


if __name__ == '__main__':
    processed_data = []
    with open('host.txt', 'r') as file:
        datas = file.read().split(',')

    for data in datas:
        processed_data.append(host_processing(data))

    print(processed_data)
Advertisements
This entry was posted in Python, Scripting and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s