from subprocess import Popen, PIPE import re host = 'google.com' hops = [] p = Popen(['tracert', host], stdout=PIPE) while True: line = str(p.stdout.readline()) ip = re.findall( r'[0-9]+(?:\.[0-9]+){3}', line) if ip == []: pass else: print(ip[0]) hops.append(ip[0]) if hops[0] == hops[-1] and len(hops) > 1: break