首页 > 解决方案 > Ubuntu 上的 WHOIS 命令只返回响应代码?

问题描述

我正在尝试使用 python3 和Ubuntu 上的 whois 命令以编程方式查找 whois 信息。

例如:

import os

# Set domain
hostname = "google.com"
# Query whois
response = os.system("whois " + hostname)
# Check the response
print("This is the Response:" + str(response))

返回这个:

...MarkMonitor Domain Management(TM) 在数字世界中保护公司和消费者。

访问https://www.markmonitor.com上的 MarkMonitor联系我们:+1.8007459229 在欧洲,+44.02032062220 -- **这是回复:**0

进程以退出代码 0 结束

whois 信息按预期显示(未在引用中看到),但是,响应始终只是退出代码。

我需要退出代码之前的信息。我必须搜索特定字段的 whois 信息。当响应 = 0 时,我该如何处理?

解决方案:

import subprocess

# Set domain
hostname = "google.com"
# Query whois
response = subprocess.check_output(
    "whois {hostname}".format(hostname=hostname),
    stderr=subprocess.STDOUT,
    shell=True)
# Check the response
print(response)

正如下面所指出的,应该使用 subprocess.check_output ()而不是 os.system。

循环时的解决方法:

for domain in domain_list:
    hostname = domain
    response = subprocess.run(
        "whois {hostname}".format(hostname=hostname),
        stderr=subprocess.STDOUT,
        shell=True)
    # Check the response
    if response != 0:
        available.append(hostname)
    else:
        continue

尽管未注册域时会发生 != 0 响应,但Subprocess.run()仍将继续循环。

标签: pythonpython-3.xubuntucommand-line-interface

解决方案


尝试使用subprocess.check_output而不是os.system,请参阅运行 shell 命令并捕获输出以获取示例。


推荐阅读