python实现besttrace 归属地功能
本地ip库速度比较快,不过只能本机使用,最好自己写个接口来调用.
这里使用的是纯真ip库,下载ip库后,需要安装纯正ip库的模块
pip install qqwry-py3
#!/usr/bin/python
#coding:utf-8
import sys
import os
import re
import subprocess
import platform
from qqwry import QQwry
q = QQwry()
dbfile = “/yourpath/qqwry.dat”
header={
‘User-Agent’: ‘Dalvik/1.6.0 (Linux; U; Android 4.4.4; HM NOTE 1S MIUI/V6.6.1.0.KHKCNCF)’,
}
def lookup(ip):
q.load_file(dbfile)
ipinfo = q.lookup(ip)
return ipinfo
def trpy(iphost):
system_name = platform.dist()[0]
if system_name == ‘redhat’:
trace_cmd = ‘/bin/traceroute’
elif system_name == ‘Ubuntu’:
trace_cmd = ‘/usr/sbin/traceroute’
else:
trace_cmd = ‘/bin/traceroute’
try:
p = subprocess.Popen([trace_cmd,iphost],stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()
if not line:
break
line = line.decode().replace(‘\n’, ‘’).replace(‘\r’, ‘’)
ips = re.findall(r"(((?:[0-9]{1,3}.){3}[0-9]{1,3}))", line)
if ips:
try:
ip = ips[0]
print(line + ", " + ’ '.join(lookup(ip)))
except IndexError as e:
print()
else:
print(line)
except (KeyboardInterrupt,SystemExit):
sys.exit()
if name == ‘main’:
if len(sys.argv) < 2:
print(“Usage: {} <hostname|ip>”.format(sys.argv[0]))
sys.exit()
else:
iphost = sys.argv[1]
trpy(iphost)
- 点赞
- 收藏
- 关注作者
评论(0)