import tldextract def extract_domain(domain): suffix = {'.com','.la','.io', '.co', '.cn','.info', '.net', '.org','.me', '.mobi', '.us', '.biz', '.xxx', '.ca', '.co.jp', '.com.cn', '.net.cn', '.org.cn', '.mx','.tv', '.ws', '.ag', '.com.ag', '.net.ag', '.org.ag','.am','.asia', '.at', '.be', '.com.br', '.net.br', '.name', '.live', '.news', '.bz', '.tech', '.pub', '.wang', '.space', '.top', '.xin', '.social', '.date', '.site', '.red', '.studio', '.link', '.online', '.help', '.kr', '.club', '.com.bz', '.net.bz', '.cc', '.band', '.market', '.com.co', '.net.co', '.nom.co', '.lawyer', '.de', '.es', '.com.es', '.nom.es', '.org.es', '.eu', '.wiki', '.design', '.software', '.fm', '.fr', '.gs', '.in', '.co.in', '.firm.in', '.gen.in', '.ind.in', '.net.in', '.org.in', '.it', '.jobs', '.jp', '.ms', '.com.mx', '.nl','.nu','.co.nz','.net.nz', '.org.nz', '.se', '.tc', '.tk', '.tw', '.com.tw', '.idv.tw', '.org.tw', '.hk', '.co.uk', '.me.uk', '.org.uk', '.vg'} domain = domain.lower() names = domain.split(".") if len(names) >= 3: if ("."+".".join(names[-2:])) in suffix: return ".".join(names[-3:]), ".".join(names[:-3]) elif ("."+names[-1]) in suffix: return ".".join(names[-2:]), ".".join(names[:-2]) print "New domain suffix found. Use tld extract domain..." pos = domain.rfind("/") if pos >= 0: # maybe subdomain contains /, for dns tunnel tool ext = tldextract.extract(domain[pos+1:]) subdomain = domain[:pos+1] + ext.subdomain else: ext = tldextract.extract(domain) subdomain = ext.subdomain if ext.suffix: mdomain = ext.domain + "." + ext.suffix else: mdomain = ext.domain return mdomain, subdomain print extract_domain("baidu.com") == ("baidu.com", "") print extract_domain("www.baidu.com") == ("baidu.com", "www") print extract_domain("www.xx.com.cn") == ("xx.com.cn", "www") print extract_domain("www.xxx.gov.cn") == ("gov.cn", "www.xxx") print extract_domain("abc.www.xxx.net.co") == ("xxx.net.co", "abc.www") print extract_domain("abcwwwxxx.local") == ("local", "abcwwwxxx") print extract_domain("abcwwwxxxlocal") == ("abcwwwxxxlocal", "") print extract_domain("attack/www.baidu.com") == ("baidu.com", "attack/www") print extract_domain("xx.attack/xxx.baidu.com") == ("baidu.com", "xx.attack/xxx") print extract_domain("attack/xxx.baidu.com") == ("baidu.com", "attack/xxx") print extract_domain("xxx.baidu.new_suffix") == ("new_suffix", "xxx.baidu") print extract_domain("attack/xxx.baidu.new_suffix") == ("new_suffix", "attack/xxx.baidu")
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/7886296.html,如需转载请自行联系原作者