[python]Use logging in your script

Adding logging in your script might be easy for you to troubleshoot or do maintenance. The logging module is a built-in module in Python.

I have extended the previous script to include logging on some points of events.

See below sample code.

import ipaddress,logging

# To log on level information. To include date/time, log level and the message. Save to a log file.
logging.basicConfig(filename="validate_ip_address.log",
                    format="%(asctime)s %(levelname)s:%(message)s",
                    level=logging.INFO)


def response_processor(response,ip,count):
    network = ipaddress.ip_network(ip, False)
    if response.lower() == 'y':
        logging.info("Listing hosts from {}".format(network))
        for host in network.hosts():
            print(host)
        if count == 0:
            logging.info("Correct response on first attempt.")
            response = 'n'
    elif response.lower() == 'n':
        logging.info("User does not want to list addresses, back to main menu.")
        pass
    else:
        print("Please use y or n.")
        count += 1 # to keep track how many times user has been asked to enumerate address.
        # logged invalid response.
        logging.warning("{} is an invalid response.".format(response))
    return response.lower()


def check_address(ip):
    if '/' in ip:
        count = 0  # to check how many times user has been asked to enumerate network.
        prefix = ip.split('/')
        if prefix[1] != '32':  # skip subnet check if it is a host address i.e. /32
            try:
                # ip is the original user's input. network has host bit reset by ipaddress.ip_network(ip,Strict=False)
                network = ipaddress.ip_network(ip,False)
                logging.info("retrieving information of {} subnet".format(network))
                print("{} is part of {} and this subnet has {} host addresses, broadcast is {}\n".format(ip,network,network.num_addresses,network.broadcast_address))
                response = input("Enumerate the address?(y or n):\n")
                response = response_processor(response,network,count)
                if response != 'n' or response != 'y':  #  if user enters an invalid option goes to a loop to keep asking user's choice.
                    while response != 'n':
                        response = input("Enumerate the address?(y or n):\n")
                        response = response_processor(response,network,count)  #  note the response variable here has changed.
            except ValueError as errorCode:
                logging.error(errorCode)
                print(errorCode)
        else:
            try:
                ipaddress.ip_address(prefix[0])
                print("{} is a valid host address.".format(ip))
            except ValueError as errorCode:
                logging.error(errorCode)
                print(errorCode)
    else:
        try:
            ipaddress.ip_address(ip)
            print("{} is a valid ip address.".format(ip))
        except ValueError as errorCode:
            logging.error(errorCode)
            print(errorCode)


def main():
    ip = input("Please enter an address:(q to quit)\n")
    while ip.lower() != 'q':
        check_address(ip)
        ip = input("Please enter an address:(q to quit)\n")
    logging.info("User has quitted the script.")


if __name__ == '__main__':
    main()

Here’s an example on what you will see:

Cyruss-MBP:lab cyruslok$ tail -F validate_ip_address.log
2018-04-11 14:59:02,293:ERROR:'a' does not appear to be an IPv4 or IPv6 address
2018-04-11 14:59:41,731:ERROR:'2.2.2.3/40' does not appear to be an IPv4 or IPv6 network
2018-04-11 14:59:53,478:WARNING:User has entered an invalid response.
2018-04-11 15:00:49,990:WARNING:User has entered an invalid response.
2018-04-11 15:00:54,539:WARNING:User has entered an invalid response.
2018-04-11 15:04:02,798 ERROR:'a' does not appear to be an IPv4 or IPv6 address
2018-04-11 15:05:22,991 ERROR:'Q' does not appear to be an IPv4 or IPv6 address
2018-04-11 15:05:25,374 INFO:User has quitted the script.
2018-04-11 15:05:51,702 INFO:User has quitted the script.
2018-04-11 15:16:09,108 INFO:User has quitted the script.
2018-04-11 15:16:17,716 INFO:User has quitted the script.
2018-04-11 15:17:33,319 INFO:retrieving information of 1.1.1.0/30 subnet
2018-04-11 15:17:35,230 INFO:Listing hosts from 1.1.1.0/30
2018-04-11 15:17:35,230 INFO:Correct response on first attempt.
2018-04-11 15:17:36,917 INFO:User has quitted the script.
2018-04-11 15:29:18,022 INFO:retrieving information of 1.1.1.0/30 subnet
2018-04-11 15:29:19,575 INFO:Listing hosts from 1.1.1.0/30
2018-04-11 15:29:19,575 INFO:Correct response on first attempt.
2018-04-11 15:29:24,761 INFO:retrieving information of 1.1.1.0/30 subnet
2018-04-11 15:29:26,788 WARNING:asdasd is an invalid response.
2018-04-11 15:29:27,597 WARNING:a is an invalid response.
2018-04-11 15:29:28,170 WARNING:a is an invalid response.
2018-04-11 15:29:28,902 WARNING: is an invalid response.
2018-04-11 15:29:29,046 WARNING: is an invalid response.
2018-04-11 15:29:29,204 WARNING: is an invalid response.
2018-04-11 15:29:31,354 INFO:Listing hosts from 1.1.1.0/30
2018-04-11 15:29:31,354 INFO:Correct response on first attempt.
2018-04-11 15:29:33,977 INFO:User has quitted the script.

Advertisements
This entry was posted in General stuffs. 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 )

Connecting to %s