简体   繁体   English

Python中的快速主机名/ IP检查?

[英]Fast hostname/IP check in Python?

I have a list of hostnames and I want to check if these machines are running or not in an interval of about one second. 我有一个主机名列表,我想在大约一秒钟的间隔内检查这些机器是否正在运行。

What I have until now is this, but the timeout on the machines which are offline take some seconds: 到目前为止我所拥有的是这个,但是离线机器上的超时需要几秒钟:

socket.setdefaulttimeout(0)
def resolve_hostname(hostname):
    try:
        return socket.gethostbyname(hostname)
    except socket.error:
        return False

Not good as the list has about 30 machines. 不太好,因为该列表有大约30台机器。

Any ideas how to speed things up a bit? 有什么想法如何加快速度?

Thank you! 谢谢!

Instead of coding this up yourself, I would look into using a third-party mass DNS resolver. 我会考虑使用第三方大规模DNS解析器,而不是自己编写代码。 Here is one that looks promising: 这是一个看起来很有希望的:

https://pypi.python.org/pypi/berserker_resolver/1.0.3 https://pypi.python.org/pypi/berserker_resolver/1.0.3

To install: 安装:

pip install berserker_resolver

Here is an example: 这是一个例子:

>>> import berserker_resolver
>>> resolver = berserker_resolver.Resolver()
>>> to_resolve = ['www.google.com', 'www.microsoft.com', 'www.facebook.com', 'invalid.invalid']
>>> resolver.resolve(to_resolve).keys()
['www.microsoft.com', 'www.facebook.com', 'www.google.com']

I don't have a connection with a slow name lookup to try, but the timeout seems to be respected exactly for socket.socket.connect() 我没有连接慢速名称查找尝试,但超时似乎完全符合socket.socket.connect()

import socket

def test_hostname(hostname, port, timeout=1.0):
    s = socket.socket()
    s.settimeout(timeout)
    try:
        s.connect((hostname, port))
    except (socket.timeout, socket.gaierror):
        return False
    else:
        return True
    finally:
        s.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM