1

我有一个脚本可以执行以下操作...

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
4

5 回答 5

2

要详细说明我对使用异常的初步评论,请创建一个返回TrueFalse基于地址有效性的函数:

import socket

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

然后

check_ip('apple')
False

check_ip('74.125.225.98')
True
于 2012-06-30T19:35:09.237 回答
1

使用tryexcept

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

首先你尝试运行socket.inet_aton(hostIP),如果失败,它会打印错误消息,如果成功,它会在else. 您将其他代码放在下面else而不是try, 以避免捕获由其他代码引发的异常。


更新:

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."
于 2012-06-30T19:25:17.257 回答
1

您可以使用以下模板,以便捕获套接字错误。

try:
    your block here
except socket.error:
    print "your message"
于 2012-06-30T19:25:32.667 回答
1

这:

not hostIP in open(hostsFileLoc).read()

会将整个文件作为单个字符串读取,然后hostIP在该字符串中查找。这也会找到部分匹配项,例如"92.168.1.21"in "192.168.1.2"

于 2012-06-30T19:45:08.977 回答
0

您将使用的一些 Python 代码将引发异常。因此,您必须编写代码以适应如下异常:

import socket

hostIP=sys.argv[1]

try:
  socket.inet_aton(hostIP):
  return True
except socket_error:
  return False
于 2012-06-30T21:08:21.030 回答