Ejemplo n.º 1
0
def worker(modo):
    """Realiza el trabajo"""
    global equipos
    for equipo in equipos:
        if modo == 'ping':
            host = ping(equipo, count=4, interval=1, timeout=2)
            if host.is_alive:
                print(
                    f'Host:{host.address} RTT_min:{host.min_rtt} RTT_prom:{host.avg_rtt} RTT_max:{host.max_rtt} P_enviados:{host.packets_sent} P_recibidos:{host.packets_received} P_perdidos:{host.packet_loss}'
                )
            else:
                print(f'Host:{host.address} no responde!')

        if modo == 'traceroute':
            hops = traceroute(equipo,
                              count=3,
                              interval=0.05,
                              timeout=1,
                              max_hops=30,
                              fast_mode=True)
            print('_' * 20)
            print(f'Host:{equipo}')
            print('Distancia (ttl)  Address RTT_prom')
            last_distance = 0
            for hop in hops:
                if last_distance + 1 != hop.distance:
                    print(f'* * * * * *')
                print(f'{hop.distance}  {hop.address}   {hop.avg_rtt} ms')
                last_distance = hop.distance
            print('Traza completa')
Ejemplo n.º 2
0
def trace(host):
        last_distance = 0
        for hop in traceroute(host,fast=True):
                if last_distance + 1 != hop.distance:
                        print('*')
                print(f'path,hop={hop.distance},addr={hop.address} rtt={hop.avg_rtt} {timestamp}')
                last_distance = hop.distance
        return
Ejemplo n.º 3
0
def traceroute_ip(timeout=1, fast_mode=True):
    ip = input("Enter website or IP: ")
    hops = traceroute(ip, timeout=1)
    print('Distance(ttl)\t\tAddress\t\tAverage round-trip time')
    last_distance = 0
    for hop in hops:
        if last_distance + 1 != hop.distance:
            print(f'servers not responding')

        print(f'{hop.distance}\t\t{hop.address}\t\t{hop.avg_rtt} ms')
        last_distance = hop.distance
Ejemplo n.º 4
0
def fnTestRoute(siteAddress):
    objHost = ping(address=siteAddress, count=1)
    objRoute = traceroute(address=siteAddress)

    if objHost.is_alive:
        print('Distance (ttl)    Address    Average round-trip time')
        intDistance = 0
        for hop in objRoute:
            if intDistance + 1 != hop.distance:
                print(f"{intDistance + 1}       Hop ({hop.address}) isn't responding")
            print(f'{hop.distance}       {hop.address}        {hop.avg_rtt} ms')
            intDistance = hop.distance
    else:
        print(f"No connection to {siteAddress}")
Ejemplo n.º 5
0
def traceroute_function(domain):
  import socket
  from icmplib import ping, multiping, traceroute, Host, Hop
  ip=str(socket.gethostbyname(domain))
  hops =traceroute("157.240.210.35", count=3, interval=0.05, timeout=2, traffic_class=0, max_hops=30)
  last_distance = 0
  ans=""
  for hop in hops:
     if last_distance + 1 != hop.distance:
         ans=ans+'Some routers are not responding'+"\n"
     # See the Hop class for details
     ans=ans+" "+str(hop.distance)+" "+hop.address+" "+str(hop.avg_rtt)+" ms"+"\n"
     last_distance = hop.distance
  return ans
Ejemplo n.º 6
0
def run_ping():
    now = dt.datetime.now()
    y = now.strftime('%Y')
    m = now.strftime('%m')
    d = now.strftime('%d')

    # 監視対象ノードリストを取得しノードごとのフォルダを作成
    nodes = config.get('settings', 'nodes')
    with open(nodes) as n:
        row = csv.reader(n)
        header = next(row)  # header行をスキップ
        for row in csv.reader(n):
            folder = path + '/' + row[0]
            if not os.path.isdir(folder):
                os.makedirs(folder)
            file = folder + '/' + row[
                0] + '_' + y + m + d + '.csv'  # 日毎のcsvファイルを作成

            # pingのオプション設定取得
            pc = config.getint('ping_options', 'p_count')
            pi = config.getint('ping_options', 'p_interval')
            pt = config.getint('ping_options', 'p_timeout')

            node = ping(row[1], count=pc, interval=pi, timeout=pt,
                        id=PID)  # ping実行
            t = dt.datetime.now().strftime('%H:%M:%S')

            # 結果の書き込み
            with open(file, 'a') as f:
                w = csv.writer(f)
                if node.is_alive:  # ping成功
                    w.writerow([t, 'OK'])
                else:  # ping失敗
                    tc = config.getint('tracert_options', 't_count')
                    ti = config.getfloat('tracert_options', 't_interval')
                    tt = config.getint('tracert_options', 't_timeout')
                    tm = config.getint('tracert_options', 't_hops')
                    tf = config.get('tracert_options', 'fast_mode')

                    hops = traceroute(row[1],
                                      count=tc,
                                      interval=ti,
                                      timeout=tt,
                                      id=PID,
                                      max_hops=tm,
                                      fast_mode=tf)
                    w.writerow([t, 'NG', hops])

                    send_mail(row[0], file)
Ejemplo n.º 7
0
def icmp_trace(ip, tr_tout, output, collect):
    result = icmplib.traceroute(ip,
                                count=1,
                                interval=0.05,
                                timeout=tr_tout,
                                id=icmplib.PID,
                                max_hops=30,
                                fast_mode=True)
    print('\n' + R + 'HOPS'.ljust(7) + 'IP'.ljust(17) + 'HOST' + W + '\n')
    for entry in result:
        hop_index = str(entry._distance)
        hop_addr = entry._address
        try:
            hop_host = socket.gethostbyaddr(hop_addr)[0]
        except socket.herror:
            hop_host = 'Unknown'
        print(G + hop_index.ljust(7) + C + hop_addr.ljust(17) + W + hop_host)

        if output != 'None':
            collect.setdefault('Result', []).append(
                [str(hop_index), str(hop_addr),
                 str(hop_host)])
Ejemplo n.º 8
0
def response(request):
    if request.method == 'POST':
        search = request.POST['site']
        details = []
        i = 0
        hops = traceroute(search)
        # print(hops)
        for hop in hops:
            i = i + 1
            # print(hop.address)
            if (i >= 2):
                response = DbIpCity.get(hop.address, api_key='free')
                '''print(response.ip_address)
                print(response.city)
                print(response.region)
                print(response.country)
                print(response.latitude)
                print(response.longitude)'''
                details.append(
                    [hop.address, response.latitude, response.longitude])

        # for detail in details:
        #     long = detail[2]
        #     lat = detail[1]
        #     context = {'long': str(long), 'lat': str(lat)}
        #     return render(request, "response.html", context)

        long = '12.550343'
        lat = '55.665957'
        context = {'long': str(long), 'lat': str(lat)}
        return render(request, "response.html", {'details': details})

    long = '12.550343'
    lat = '55.665957'
    context = {'long': str(long), 'lat': str(lat)}
    return render(request, "response.html", context)
Ejemplo n.º 9
0
async def echo(websocket, path):
    async for message in websocket:
        print(message)
        mesage_parsed = message.split(sep=",")
        resp = ''
        if mesage_parsed[0] == 'ping':
            resp = ping(mesage_parsed[1],
                        count=int(mesage_parsed[2])).__repr__()
        if mesage_parsed[0] == 'trace':
            hops = traceroute(mesage_parsed[1])

            resp += 'Distance/TTL    Address    Average round-trip time\n'
            last_distance = 0

            for hop in hops:
                if last_distance + 1 != hop.distance:
                    resp += 'Some gateways are not responding\n'

                # See the Hop class for details
                resp += f'{hop.distance}    {hop.address}    {hop.avg_rtt} ms\n'

                last_distance = hop.distance

        await websocket.send(resp)
Ejemplo n.º 10
0
    icmplib
    ~~~~~~~

        https://github.com/ValentinBELYN/icmplib

    :copyright: Copyright 2017-2020 Valentin BELYN.
    :license: GNU LGPLv3, see the LICENSE for details.

    ~~~~~~~

    Example: traceroute
'''

from icmplib import traceroute

hops = traceroute('1.1.1.1', timeout=1, fast_mode=True)

print(hops)
# [<Hop 1 [192.168.0.254]>, <Hop 2 [194.149.169.162]>,
#  <Hop 4 [149.11.115.13]>, <Hop 5 [154.54.61.21]>,
#  <Hop 6 [154.54.60.126]>, <Hop 7 [149.11.0.126]>,
#  <Hop 8 [1.1.1.1]>]

last_distance = 0

for hop in hops:
    if last_distance + 1 != hop.distance:
        print('   *    Some routers are not responding')

    print(f'{hop.distance:4}    {hop.address:15}    ' f'{hop.avg_rtt} ms')
Ejemplo n.º 11
0
import dns.resolver
ans=""
my_resolver = dns.resolver.Resolver()

# 8.8.8.8 is Google's public DNS server
my_resolver.nameservers = ['8.8.8.8']

answer = my_resolver.resolve('myntra.com','A')
ans=ans+answer.rrset.to_text()
print(ans)

pip install icmplib

from icmplib import ping, multiping, traceroute, Host, Hop
hops = traceroute('1.1.1.1')
last_distance = 0
for hop in hops:
     if last_distance + 1 != hop.distance:
         print('Some routers are not responding')
     # See the Hop class for details
     print(f'{hop.distance}    {hop.address}    {hop.avg_rtt} ms')
     last_distance = hop.distance

"""FUNCTIONS FOR GUI"""

def ipInfo(addr):
    ans=""
    from urllib.request import urlopen
    from json import load
    if addr == '':
Ejemplo n.º 12
0
    if n1 == 172 and n2 == 16:
        n2 = 32
    #Skip the 192.168.0.0 network
    if n1 == 192 and n2 == 168:
        n2 = 169
    #Skip the 127.0.0.0 network
    if n1 == 127:
        n1 = 128
    #Creates the Host IP Address
    hostname = str(n1) + "." + str(n2) + "." + str(n3) + "." + str(n4)
    #Clears the terminal
    os.system('clear')
    #Prints Current Host IP Adress
    print(hostname)
    #Traceroutes the IP Address, Maximum # of trachoppers, and sets fast mode
    trachoppers = traceroute(hostname, max_hops=255, fast_mode=True)
    #Keeps track of the hops
    last_distance = 0
    #Line output variable
    lnout = ""
    #Sets if first part of the sentence
    lnfirst = 0
    for hop in trachoppers:
        if last_distance + 1 != hop.distance:
            lnout = lnout + " -> " + "Some routers are not responding"

        # See the Hop class for details
        if lnfirst == 0:
            lnout = hop.address
            lnfirst = 1
        else:
Ejemplo n.º 13
0
def run_traceroute(address: str) -> list:
    hops = icmplib.traceroute(address)

    return [get_ip_location(hop.address) for hop in hops]
Ejemplo n.º 14
0
psswrd = config["DatabaseDetails"]["Password"]

#Connect the database
dbConnection = pymysql.connect(host=host, user=uname, passwd=psswrd, db=dbname)

#Open image and keep in memory
print("Opening Image...")
image = Image.open("World Map.png")
drawer = ImageDraw.Draw(image)

#Performs actual trace route over ICMP
print("Performing TraceRoute...")
hops = traceroute(address,
                  count=2,
                  interval=0.05,
                  timeout=2,
                  first_hop=1,
                  max_hops=30,
                  source=None,
                  fast=False)

#A query to fetch latitude and longitude.
#This can be replaced by a webservice call as well
latLongQuery = "select latitude, longitude from ip_location il where %s between start_ip  and end_ip"

pX = 0
pY = 0
for hop in hops:
    ipAddrStr = hop.address
    ipAddr = ipaddress.IPv4Address(ipAddrStr)
    ipAddrLong = int(ipAddr)  #Convert IP Address to LONG
    #print("Querying", hop.address, hop.avg_rtt, hop.distance, ipAddrLong)
Ejemplo n.º 15
0
#!/usr/bin/env python3.8
# -*- coding: utf-8 -*-

from icmplib import traceroute
import sys

target = str(sys.argv[1])
print(target)
if __name__ == "__main__":
    hops = traceroute(target,
                      count=2,
                      interval=0.05,
                      timeout=2,
                      max_hops=20,
                      fast_mode=False)
    for row in hops:
        print(row.distance, row.address, row.avg_rtt)