Resolving IP to hostname in Python 2 This piece of script will take one argument (file which contain list of ip, one per line) and convert it to its hostname. For now this will only work with IPv4.

This definitely doesn't look good and I want experts to review it and suggest some good ways of coding it in Python.

#!/usr/bin/python

import socket
import sys

BLUE='\033[34m'
RED='\033[31m'
NORMAL='\033[0m'

def check_ip():
        try:
                socket.inet_aton(ip)
        except Exception, e:
                print RED+"Invalid ip addresss = "+NORMAL + str(ip)

file = sys.argv[1]
with open(file) as ipfile:
        for iplist in ipfile:
                for IP in iplist.split():
                        ip = IP.strip(' \t\n\r')
                        if ip == '':
                                pass
                        else:
                                check_ip()
                                host = socket.getfqdn(ip)
                                print BLUE+ip+NORMAL + " hostname is " + BLUE+host+NORMAL
The standard indentation in Python is 4 spaces, as specified in PEP 8.  This is a pretty strong convention, since Python is very sensitive to indentation.

To process a file specified on the command line, use the fileinput module.  It supports multiple filenames, and it also falls back to reading standard input if there is no filename given.

Instead of for iplist in ipfile, I would say for line in ipfile — because it's not a list until you have split it.  It's also odd that you wrote the code to expect a "list", when in your question, you specified one IP address per line.

str.split(), with no separator specified, splits on whitespace and automatically discards whitespace from the results for you.

Calling check_ip() with the ip as a global variable is bad practice.  You should pass it as a parameter.  However, I wouldn't bother defining a function for it, especially since that function has a side-effect of printing its output.

The except Exception, e syntax is obsolescent.  Prefer writing except Exception as e.  (In this case, you don't need to name the exception at all.)

Since all of the color-changing codes should reset the color back to normal, I would define a function for that.

import fileinput
import socket

RED = '31'
BLUE = '34'

def color(color_code, text):
    return '\033[{}m{}\033[0m'.format(color_code, text)

for line in fileinput.input():
    for ip in line.split():
        try:
            socket.inet_aton(ip)
        except Exception as invalid_ip:
            print color(RED, 'Invalid IP address = ') + ip
        else:
            hostname = socket.getfqdn(ip)
            print color(BLUE, ip) + ' hostname is ' + color(BLUE, hostname)