如何从 Python 中的 FQDN 中提取主机名和(子)域?

How do I extract the hostname and the (sub)domain from a FQDN in Python?

我正在尝试编写一个脚本,它将采用 FQDN 并提供主机名和(子)域。

我能够获取主机名,但我不知道如何获取整个域,包括任何子域。

请注意,这些域和子域将是内部域,而不是 public 域。

import re 

words = "testing.something.thisdomain.com"
 

stuff = re.match(r"(.+?)(?=\.)", words)

print(stuff.group(1))

我们不能只在字符串上使用 split 并打印您需要的部分,而不是做一堆花哨的正则表达式吗?

words = "testing.something.thisdomain.com"
stuff = words.split(".")
print(stuff[1])

即使您的 fqdn 没有任何子域,这仍然有效

代码:

fqdn = "testing.something.thisdomain.com"
tld, domain, *sub_domains = fqdn.split(".")[::-1]
print(tld,domain,sub_domains)

输出:

com thisdomain ['something', 'testing']