【问题标题】:Python script to read through a list and grab reverse DNS entry用于读取列表并获取反向 DNS 条目的 Python 脚本
【发布时间】:2015-10-04 00:41:05
【问题描述】:

背景:我一直想尝试编写脚本,所以开始吧!

问题:当 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

【问题讨论】:

  • if socket.gethostbyaddr(host): 解决您的问题?
  • 如果提供的脚本对您有用,您是否尝试过?如果对您有帮助,请考虑将其作为可接受的答案。

标签: python sockets networking reverse-dns gethostbyaddr


【解决方案1】:

至于基本语法,你应该删除itzmeontv提到的return(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))

我建议阅读Handling Exceptions

【讨论】:

  • 但不能使用 except: - 而是使用 except socket.gaierror: 或类似的东西...
猜你喜欢
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
相关资源
最近更新 更多