1

I have a script that does something like the following...

import socket

hostIP=sys.argv[1]

if socket.inet_aton(hostIP):
    # Do something with valid ip address
else:
    # Print error message

Which works fine for valid addresses, however when I try an invalid address it does not work (i.e. printing my error message), and throws out a socket error...

Traceback (most recent call last):
  File "addNew.py", line 35, in <module>
    if socket.inet_aton(hostIP):
socket.error: illegal IP address string passed to inet_aton

Any thoughts on how I can achieve what I want (i.e. just a simple message rather than the socket error).

Thanks in advance,

MHibbin

UPDATE: Working(ish) script

import os
import sys
import fileinput
import platform
import subprocess
import re
import socket

hostsFile = "hosts.txt"
hostsLookFile = "hosts.csv"
hostsURLFileLoc = "urls.conf"
plat = platform.system()
currentDir = "C:/Program Files/Splunk/etc/apps/gtvm/bin"
hostsFileLoc = currentDir + "/" + hostsFile
hostsLookFileLoc = currentDir + "/../lookups/" + hostsLookFile
hostsURLFileLoc = currentDir + "/../default/" + hostsURLFileLoc
hostIP = sys.argv[1]
hostName = sys.argv[2]
hostURL = sys.argv[3]
hostMan = sys.argv[4]
hostModel = sys.argv[5]
hostType = sys.argv[6]
hostDC = sys.argv[7]

#pat = re.compile(^hostIP\s+)

#test = pat.match(hostIP)
#if test:
#   print "Acceptable ip address"
#else:
#   print "Unacceptable ip address"


try:
    socket.inet_aton(hostIP)
except socket.error as e:
    print "Unacceptable ip address", e
else:
    print "Acceptable ip address, proceeding..."
    print "Checking host if " + hostIP + " exists..."
    if not hostIP in open(hostsFileLoc).read():
        print hostIP + " does not yet exist, checking valid required input..."
        if hostName != "*" and hostIP != "*":
            print "...processing..."
            with open(hostsFileLoc,'a+') as hostsFilePython, open(hostsLookFileLoc, 'a+') as hostsLookFileCSV, open(hostsURLFileLoc, 'a+') as 

hostsURLPython:
                print "..host IP adddress for ping testing.."
                hostsFilePython.write(hostIP + "\n")
                print "..and, all values for referencing.."
                hostsLookFileCSV.write(hostIP + "," + hostName + "," + hostURL + "," + hostMan + "," + hostModel + "," + hostType + "," + 

hostDC + "," + "\n")
                if hostURL != "*": 
                    "..adding URL for webping testing.."
                    hostsURLPython.write("[" + hostName + "]\n" + "url = " + hostURL + "\n" + "sleep = 60" + "\n" + "\n")
                    print "done!"

        else:
            print "..failed! - Both host IP address and host name required"
    else:
        print hostIP + " already exists, please review lookups."
#except socket.error as e:
#   print "Unacceptable ip address", e
3
  • 1
    How about catching the exception? Commented Jun 30, 2012 at 19:22
  • 1
    you are putting a colon after it: socket.inet_aton(hostIP):, which shouldn't be there. It is also better to put all the other code from print "Acceptable ip address, proceeding..." to print hostIP + " already exists, please review lookups." in an else after the except, as shown in my answer. Commented Jun 30, 2012 at 19:38
  • Modified my script to match that. Thanks Commented Jun 30, 2012 at 20:10

5 Answers 5

2

To elaborate on my initial comment about using exceptions, create a function that returns True or False based on the validity of the address:

import socket

def check_ip(addr):
    try: 
        socket.inet_aton(addr)
        return True
    except socket.error:
        return False

then

check_ip('apple')
False

check_ip('74.125.225.98')
True
Sign up to request clarification or add additional context in comments.

3 Comments

Bare excepts are not recommended because they catch all exceptions. Catch only what you want to handle.
@MRAB how would I only catch that exception then?
Ah yep, sorry I see now :)... Long day :( and i'm a newbie... as you can probably tell
1

Use tryand except.

import socket

hostIP=sys.argv[1]

try:
    socket.inet_aton(hostIP)
except socket.error as e:
    print "Error:", e
else:
    # Do something with valid ip address

First you try to run socket.inet_aton(hostIP), if it fails it prints the error message, if it succeeds, it does some code under the else. You put the other code under else instead of in the try, to avoid catching exceptions that are raised by the other code.


UPDATE:

import platform
import subprocess
import re
import socket

hostsFile = "hosts.txt"
hostsLookFile = "hosts.csv"
hostsURLFileLoc = "urls.conf"
plat = platform.system()
currentDir = "C:/Program Files/Splunk/etc/apps/gtvm/bin"
hostsFileLoc = currentDir + "/" + hostsFile
hostsLookFileLoc = currentDir + "/../lookups/" + hostsLookFile
hostsURLFileLoc = currentDir + "/../default/" + hostsURLFileLoc
hostIP = sys.argv[1]
hostName = sys.argv[2]
hostURL = sys.argv[3]
hostMan = sys.argv[4]
hostModel = sys.argv[5]
hostType = sys.argv[6]
hostDC = sys.argv[7]

#pat = re.compile("\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}")

#test = pat.match(hostIP)
#if test:
#   print "Acceptable ip address"
#else:
#   print "Unacceptable ip address"


try:
    socket.inet_aton(hostIP)
except socket.error as e:
    print "Unacceptable ip address", e
else:
    print "Acceptable ip address, proceeding..."
    print "Checking host if " + hostIP + " exists..."
    if not hostIP in open(hostsFileLoc).read():
        print hostIP + " does not yet exist, checking valid required input..."
        if hostName != "*" and hostIP != "*":
            print "...processing..."
            with open(hostsFileLoc,'a+') as hostsFilePython, open(hostsLookFileLoc, 'a+') as hostsLookFileCSV, open(hostsURLFileLoc, 'a+') as hostsURLPython:
                print "..host IP adddress for ping testing.."
                hostsFilePython.write(hostIP + "\n")
                print "..and, all values for referencing.."
                hostsLookFileCSV.write(hostIP + "," + hostName + "," + hostURL + "," + hostMan + "," + hostModel + "," + hostType + "," + hostDC + "," + "\n")
                if hostURL != "*": 
                    "..adding URL for webping testing.."
                    hostsURLPython.write("[" + hostName + "]\n" + "url = " + hostURL + "\n" + "sleep = 60" + "\n" + "\n")
                    print "done!"

        else:
            print "..failed! - Both host IP address and host name required"
    else:
        print hostIP + " already exists, please review lookups."

Comments

1

This:

not hostIP in open(hostsFileLoc).read()

will read the entire file as a single string and then look for hostIP in that string. That will also find partial matches, such as "92.168.1.21" in "192.168.1.2".

2 Comments

I was actually going to post a question about that, thanks for noticing.. can I make it so it's an exact match only i.e. in regex something like "^hostIP[\s\.]*"
I'd probably use a set instead, eg. hostIP not in set(line.rstrip() for line in open(hostsFileLoc)). The .rstrip() is to remove the "\n" line ending.
1

You could use the following template, so that the socket error is trapped.

try:
    your block here
except socket.error:
    print "your message"

Comments

0

Some Python code you will use will throw an exception. So, you must write your code to accomodate exceptions like this:

import socket

hostIP=sys.argv[1]

try:
  socket.inet_aton(hostIP):
  return True
except socket_error:
  return False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.