Skip to content

Instantly share code, notes, and snippets.

@rkhapov
Created March 28, 2019 11:49
Show Gist options
  • Select an option

  • Save rkhapov/b8fc3e7fff98b85ad29ee5dc1048663e to your computer and use it in GitHub Desktop.

Select an option

Save rkhapov/b8fc3e7fff98b85ad29ee5dc1048663e to your computer and use it in GitHub Desktop.
tracert
import json
import argparse
import requests
import subprocess
import re
IP_REGEXP = re.compile('(?:[0-9]{1,3}\\.){3}[0-9]{1,3}')
RESOLVER = 'https://ipinfo.io/{}/json'
def parse_args():
parser = argparse.ArgumentParser(description='tracre AS to address')
parser.add_argument('address', help='target address')
return parser.parse_args()
def get_ips():
address = parse_args().address
ips = []
with subprocess.Popen(['tracert', '-4', '-d', address], stdout=subprocess.PIPE) as proc:
proc.stdout.readline()
proc.stdout.readline()
proc.stdout.readline()
while True:
line = proc.stdout.readline().decode('cp866')
if line == '':
break
if line.find('***') != -1:
proc.kill()
break
ip = IP_REGEXP.findall(line.strip())
if len(ip) != 0:
yield ip[0]
def get_for_ip(ip):
with requests.request('get', RESOLVER.format(ip)) as r:
j = json.loads(r.text)
if 'bogon' in j:
return f'{ip} - gray'
org = j['org'] if j['org'] else 'unknown'
return f'{ip} - {org} in {j["country"]}'
def main():
for ip in get_ips():
print(get_for_ip(ip))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment