def whois(k, i):
k = str(k[i])
print (k)
whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ou, err = whois.communicate()
who = str(ou)
print (who.find('NetName:'))
who = re.split('NetName:', who)[1]
who = re.split('NetHandle', who)[0]
who = who.replace(r'\n', '')
print (whois(k, 4))
输出:
108.160.172.204
520
None
为什么python返回“None”而不是“Dropbox”? 如果我拿这个代码并且:
k = '108.160.172.204'
print (k)
whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ou, err = whois.communicate()
who = str(ou)
print (who.find('NetName:'))
who = re.split('NetName:', who)[1]
who = re.split('NetHandle', who)[0]
who = who.replace(r'\n', '')
print (who)
输出是:
108.160.172.204
520
DROPBOX
答案 0 :(得分:4)
您的函数不返回值,因此它返回None,因为所有未指定返回值的python函数都会执行:
def whois(k, i):
k = str(k[i])
print (k)
whois = subprocess.Popen(['whois', k], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ou, err = whois.communicate()
who = str(ou)
print (who.find('NetName:'))
who = re.split('NetName:', who)[1]
who = re.split('NetHandle', who)[0]
who = who.replace(r'\n', '')
return who # return who
如果您只想要输出,也可以使用check_output
,也不需要重新分割:
from subprocess import check_output
def whois(k, i):
k = str(k[i])
who = check_output(['whois', k], universal_newlines=True)
who = who.split('NetName:')[1]
who = who.split('NetHandle')[0]
return who.replace(r'\n', '')
还有多个python库可以执行你想要的几个ipwhois,python-whois
如果您只想要NetHandle
,可以使用re来查找:
def whois(k, i):
k = k[i]
who = check_output(['whois', k], universal_newlines=True)
return dict(map(str.strip,ele.split(":",1)) for ele in re.findall(r'^\w+:\s+.*', who, re.M))
演示:
In [28]: whois([1,1,1,1, "216.58.208.228"],4)
Out[28]: 'NET-216-58-192-0-1'
或创建一个字典并获取键/值配对中的所有信息:
def whois(k, i):
k = k[i]
who = check_output(['whois', k], universal_newlines=True)
print(who)
return dict(map(str.strip,ele.split(":",1)) for ele in re.findall('\w+:\s+.*', who))
d = whois([1,1,1,1, "216.58.208.228"],4)
print(d["NetHandle"])
from pprint import pprint as pp
pp(d)
输出:
NET-216-58-192-0-1
{'Address': '1600 Amphitheatre Parkway',
'CIDR': '216.58.192.0/19',
'City': 'Mountain View',
'Country': 'US',
'NetHandle': 'NET-216-58-192-0-1',
'NetName': 'GOOGLE',
'NetRange': '216.58.192.0 - 216.58.223.255',
'NetType': 'Direct Allocation',
'OrgAbuseEmail': 'arin-contact@google.com',
'OrgAbuseHandle': 'ZG39-ARIN',
'OrgAbuseName': 'Google Inc',
'OrgAbusePhone': '+1-650-253-0000',
'OrgAbuseRef': 'http://whois.arin.net/rest/poc/ZG39-ARIN',
'OrgId': 'GOGL',
'OrgName': 'Google Inc.',
'OrgTechEmail': 'arin-contact@google.com',
'OrgTechHandle': 'ZG39-ARIN',
'OrgTechName': 'Google Inc',
'OrgTechPhone': '+1-650-253-0000',
'OrgTechRef': 'http://whois.arin.net/rest/poc/ZG39-ARIN',
'Organization': 'Google Inc. (GOGL)',
'OriginAS': 'AS15169',
'Parent': 'NET216 (NET-216-0-0-0-0)',
'PostalCode': '94043',
'Ref': 'http://whois.arin.net/rest/org/GOGL',
'RegDate': '2000-03-30',
'StateProv': 'CA',
'Updated': '2013-08-07'}