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
Use
tryandexcept.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 theelse. You put the other code underelseinstead of in thetry, to avoid catching exceptions that are raised by the other code.UPDATE: