0

背景:我一直想尝试编写脚本,所以就这样吧!

问题:当 gethostbyaddr 到达没有 DNS 条目的 IP 时,它会出错并且我的脚本不会继续。

这是我到目前为止所拥有的:

import socket

file = 'ServerList'

f = open(file, 'r')

 lines = f.readlines()
 f.close()
 for i in lines:
    host = i.strip()
    if socket.gethostbyaddr(host) return(True):
        val1 = socket.gethostbyaddr(host)
        print("%s - %s" % (host, val1))
    else:
        print ("%s - No Entry" % (host))

但它可能会出错,因为 return(True) 的语法不正确。

任何人都可以帮忙吗?

谢谢,J

4

1 回答 1

2

至于基本语法,您应该删除itzmeontvreturn(True)提到的。

但是,如果该方法失败,它很可能会抛出某种异常(我尝试了一些服务器并得到了一个socket.gaierror),因此您需要通过以下方式捕获和处理这些情况try ... except

import socket

file = 'ServerList'

f = open(file, 'r')

lines = f.readlines()
f.close()
for i in lines:
    host = i.strip()
    try:
        val1 = socket.gethostbyaddr(host)
        print("%s - %s" % (host, val1))
    except socket.error, exc:
        print ("%s - No Entry, socket error: %s" % (host, exc))

我建议通读处理异常

于 2015-07-15T06:40:51.810 回答