Skip to content

Instantly share code, notes, and snippets.

@oowl
Last active February 4, 2021 13:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oowl/133986e8c3d51c1042a0eb0811df0c41 to your computer and use it in GitHub Desktop.
Save oowl/133986e8c3d51c1042a0eb0811df0c41 to your computer and use it in GitHub Desktop.
mtr ip location
#!/usr/bin/env python3
import sys
import re
import ipaddress
import requests
baseurl = "https://btapi.ipip.net/host/info"
user_agent = "ipip/tt"
accept_encoding = 'gzip'
ip_re = re.compile(r'''
(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
|
(?:(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}
|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}
|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}
|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}
|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}
|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}
|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})
|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)
|(?:[0-9a-fA-F]{1,4}:){1,7}:
|fe80:(?::[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}
|::(?:ffff(?::0{1,4}){0,1}:){0,1}(?:(?:25[0-5]
|(?:2[0-4]
|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]
|(?:2[0-4]
|1{0,1}[0-9]){0,1}[0-9])
|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]
|(?:2[0-4]
|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(?:25[0-5]
|(?:2[0-4]
|1{0,1}[0-9]){0,1}[0-9]))''', re.VERBOSE)
def lookup_ip_btapi(ip):
parms = { 'ip': ip,'host':'','lang':'cn'}
r = requests.session()
r.headers['User-Agent'] = user_agent
r.headers['Accept-Encoding'] = accept_encoding
result = r.request("get","https://btapi.ipip.net/host/info",parms)
l1,l2,l3,l4,isp,lat,lng = result.json()['area'].split('\t')
as_num = result.json()['as']
result_dict = {'l1':l1,'l2':l2,'l3':l3,'l4':l4,'isp':isp,'as':as_num,'lat':lat,'lng':lng}
return result_dict
def transformline(line, ip_dict):
shift = 0
for m in ip_re.finditer(line):
try:
ip = m.group(0)
ip = ipaddress.ip_address(ip)
if ip.is_global:
if str(ip) in ip_dict:
addr = ip_dict[str(ip)]
else:
addr = lookup_ip_btapi(str(ip))
ip_dict[str(ip)] = addr
addr = addr['l1'] + " " + addr['l2'] + " " + addr['l3'] +addr['l4'] + " " + addr['isp']
inpos = m.end() + shift
line = "%s (%s)%s" %(line[:inpos],addr,line[inpos:])
shift += len(addr) + 2
else:
pass
except:
pass
return line
def main():
try:
ip_dict = {}
for i in sys.stdin:
sys.stdout.write(transformline(i, ip_dict))
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
@oowl
Copy link
Author

oowl commented Sep 26, 2019

mtr 1.1.1.1 | ./ipmarkup
enjoy it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment