Last active
February 4, 2021 13:00
-
-
Save oowl/133986e8c3d51c1042a0eb0811df0c41 to your computer and use it in GitHub Desktop.
mtr ip location
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mtr 1.1.1.1 | ./ipmarkup
enjoy it