我有一个脚本可以执行以下操作...
import socket
hostIP=sys.argv[1]
if socket.inet_aton(hostIP):
# Do something with valid ip address
else:
# Print error message
这适用于有效地址,但是当我尝试无效地址时它不起作用(即打印我的错误消息),并抛出一个套接字错误......
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
关于如何实现我想要的任何想法(即只是一个简单的消息而不是套接字错误)。
提前致谢,
米宾
更新:工作(ish)脚本
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