简体   繁体   中英

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

I am trying to write a script that will take a FQDN and give me the hostname as well as the (sub)domain.

I am able to get the hostname, but I can't figure out how to also get the entire domain, including any subdomains.

Please note that these domains & subdomains would be internal domains and not public domains.

import re 

words = "testing.something.thisdomain.com"
 

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

print(stuff.group(1))

This works even if your fqdn does not have any subdomains

Code:

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

Output:

com thisdomain ['something', 'testing']

Instead of doing a bunch of fancy regex couldn't we just use split on the string and print which part you need?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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