Пример #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')
 def check_device_status(self, address):
     """
     Returns True if host (str) responds to a ping request.
     Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
     """
     host = ping(address, count=1, interval=0.2)
     return host.is_alive
Пример #3
0
def ping_host(hostname):
    if os.geteuid() == 0:
        host = ping(hostname, count=3, privileged=True)
        return {
            'anchor': hostname.split('.')[0],
            'min_rtt': host.min_rtt,
            'max_rtt': host.max_rtt,
            'jitter': host.jitter,
            'packet_loss': host.packet_loss
        }
    else:
        p = subprocess.Popen(shlex.split(f'ping -c3 {hostname}'),
                             stdout=subprocess.PIPE)
        output = p.stdout.read()
        for line in output.decode('utf-8').split('\n'):
            if 'packets transmitted' in line:
                transmitted = line
            if line.startswith('rtt min'):
                rtt = line
        packet_loss = float(transmitted.split(',')[2].split('%')[0].strip())
        min_rtt, _, max_rtt, jitter = map(
            float,
            rtt.split('=')[1].strip().split(' ')[0].split('/'))
        return {
            'anchor': hostname.split('.')[0],
            'min_rtt': min_rtt,
            'max_rtt': max_rtt,
            'jitter': jitter,
            'packet_loss': packet_loss
        }
Пример #4
0
    def __init__(self, source_host, port=50000, target=None):
        """
        Creates a metasploit class to connect and use metasploit functionality.

        Args:
            source_host (str): the host that uses metasploit.
            port (int): on which port the msfrpc listens to.
            target (str): target host to perform actions.

        Raises:
            MsfrpcdConnectionError: in case metasploit connection attempt has failed.
            InvalidHostName: in case the provided target host name is invalid.
        """
        self._source_host = source_host

        try:
            if target:
                self._target_host = socket.gethostbyname(target)
                is_target_reachable = ping(address=self._target_host, privileged=False).is_alive
                if not is_target_reachable:
                    raise HostIsUnreachable(source_host=self._source_host, target_host=self._target_host)
        except socket.gaierror:
            raise InvalidHostName(invalid_host=target)

        try:
            self._metasploit = Metasploit(server=source_host, port=port)
        except ConnectionError:
            raise MsfrpcdConnectionError(host=source_host, port=port)
Пример #5
0
async def main():
    try:
        jar = aiohttp.CookieJar(unsafe=True)
        nodes_ssh_dict: dict = {}

        async for apic in FABRICS:
            async with ClientSession(cookie_jar=jar) as session:
                tasks = []
                url = API % apic
                await apic_login(session, url)
                await verify_apic_faults(session, url)
                impacted_devices = await verify_devices(session, url)
                async for node in AsyncIterator(impacted_devices):
                    ssh_info = await get_ssh_ip(session, url, node)
                    nodes_ssh_dict.update(ssh_info)

        async for node in AsyncIterator(nodes_ssh_dict):
            if 'mgmtRsOoBStNode' in nodes_ssh_dict[node].keys():
                node_ip = nodes_ssh_dict[node]['mgmtRsOoBStNode']
            elif 'mgmtRsOoBStNode' not in nodes_ssh_dict[node].keys():
                node_ip = nodes_ssh_dict[node]['mgmtRsInBStNode']
            host = ping(node_ip, count=5, interval=0.2, privileged=False)
            if host.is_alive:
                log.info(f'Attempting SSH connection to {node} '
                         f'at oobMgmt {host.address}')
                power_on_hrs = await query_nxos_switches(node, host.address)
                # print(power_on_hrs)
            else:
                log.error(f'{node} is unreachable via SSH '
                          f'on {host.address}. Unable to verify.')

    except Exception as e:
        print(str(e), 'Exception happened on main')
Пример #6
0
def tn_connect(ip_remote, ftp_ip, ftp_local):
    """Connect via telnet"""

    if ftp_local:
        for ip_local in ips_local:
            host = ping(ip_remote, count=2, interval=0.1, source=ip_local)
            if host.is_alive:
                ftp_path = ip_local
                break
    else:
        ftp_path = f'{ftp_ip}/FTP'

    with telnetlib.Telnet(ip_remote, 23) as tn:
        tn.read_until(b'Login:'******'admin\n\r')
        tn.read_until(b'Password:'******'admin\n\r')
        tn.write(b'sys ver\n\r')
        time.sleep(3)
        result = tn.read_very_eager().decode('utf-8')
        pattern = re.compile(r'SN:(\d+)')
        if pattern.search(result):
            sn = pattern.search(result).group(1)
            if sn in licenses:
                ftp_file = licenses[sn].name
                ftp_command = f'license --install=ftp://anonymous:anonymous@{ftp_path}/{ftp_file}\n\r'
                tn.write(ftp_command.encode('utf-8'))
                time.sleep(3)
                tn.write(b'co sa; rest y\n\r')
                #result = tn.read_very_eager().decode('utf-8')
                #print(result)
            else:
                print(f'ERROR: The license not found.')
Пример #7
0
def alive(address):
    try:
        if icmplib.ping(address):
            return "%s is alive!" % address
    except:
        pass
    return "%s is dead!" % address
Пример #8
0
def main():
    # Довольно громоздкий вызов получается имхо, поэтому я параметры в словарик вытащил
    # Они всё равно не меняются сейчас
    ping_parameters = {
        'address': config.SERVER_TO_PING,
        'interval': config.INTERVAL_BETWEEN_PINGS,
        'count': 1,
        'timeout': config.TIMEOUT_SECONDS
    }
    progress = PingProgress(config.TIMEOUTS_BEFORE_FAILURE,
                            config.TIMEOUTS_BEFORE_SUCCESS)
    progress.on_network_up = on_network_up
    while True:
        try:
            ping_result = icmplib.ping(**ping_parameters)
            if not ping_result.is_alive:
                progress.fail()
                print('Хост недоступен')
            if ping_result.received_packets == 0:
                progress.fail()
                # print('Fail')
            else:
                progress.success()
                # print('Success')
        except KeyboardInterrupt:
            print('Ctrl-C')
            break
Пример #9
0
 def isOnline(self):
     """sends every 0.5s a ping to check if host is up. Returns after first received ping."""
     host = ping(self.ip,
                 interval=0.5,
                 timeout=self.ping_timeout,
                 privileged=False)
     return host.is_alive
Пример #10
0
def ping_discovery(net=0):
    """
    Função que realiza descoberta de hosts onlines na rede utilizando ping. Por padrão utiliza rede vinculada ao
    hostname da máquina onde o script está sendo rodado com a máscara /24. Por exemplo, se o seu ip é 192.168.10.10,
    a rede a ser utilizada no scan será 192.168.10.0/24
    :param net: Opcional, Rede a ser escaneada. Se não especificado será utilizada rede do gateway padrão
    :return: Lista com os endereços que responderam o ping.
    """
    # if __name__ == '__main__':
    target = net
    try:
        nethosts = ip_network(target).hosts()
        iponline = []
        for ip in nethosts:
            ipstr = str(ip)
            pingresult = ping(ipstr)
            if pingresult.is_alive:
                iponline.append(pingresult.address)
        return iponline
    except KeyboardInterrupt:
        print(
            '\nO usuário preferiu interromper a execução, portanto o retorno será 0'
        )
        return 0
    except:
        print("Tente digitar a rede no formato 172.16.0.0/24")
        def newClient():
            nonlocal threadPingData

            # starting the fake client and connecting to the server
            f_client = socket.socket()
            # f_client.settimeout(1)
            hostip = socket.gethostbyname(socket.gethostname())
            f_client.connect((hostip, 54321))

            # saving response
            response = f_client.recv(1024).decode()
            pingData = str(response).split(",", 3)
            pingData = ping(pingData[0], int(pingData[1]), int(pingData[2]),
                            int(pingData[3]))

            with lock:
                # saving the ping data for later processing
                threadPingData.append(pingData)

            time.sleep(2)

            # telling the client to stop the attack
            f_client.sendall("n".encode('ascii', 'strict'))
            if len(threadPingData) == 2:
                sys.exit()
Пример #12
0
def alive(address):
	try:
		if icmplib.ping(address):
			return "%s is alive!" % address
	except:
		pass
	return "%s is dead!" % address
Пример #13
0
async def on_message(message):
    global bot_busy
    if not bot_busy:
        if message.author != client.user:
            if message.content.startswith("$ctp"):
                bot_busy = True
                async with message.channel.typing():
                    await message.channel.send("{} requested command!".format(
                        message.author))
                    await message.channel.send(
                        "Checking if Tsu can play! Please wait...")

                    # Capture initial time when starting timer. NOTE: time.perf.counter() returns time in seconds. So
                    # simply multiply by 1000 to get milliseconds! \o/
                    timer_init = time.perf_counter()

                    # icmplib.ping(address, count=4, interval=1, timeout=2)
                    ping_object = icmplib.ping("8.8.8.8", 10, 1, 2)
                    prep_str = "Max: %d ms\nMin: %d ms\nDropped Packets: %d\nAverage Latency: %d ms" % (
                        ping_object.max_rtt, ping_object.min_rtt,
                        ping_object.packet_loss, ping_object.avg_rtt)
                    await message.channel.send(prep_str)

                    # Calculate the duration of the timer.
                    time_passed_ms = round((time.perf_counter() - timer_init),
                                           2)
                    await message.channel.send(
                        "Command processed in: {} seconds.".format(
                            time_passed_ms))
    else:
        await message.channel.send("Sorry, {}! Bot busy: {}".format(
            message.author, bot_busy))
Пример #14
0
def deepScan():
    prefixoIP = str(file.get("Rede", "prefixip"))
    faixaDeIp = str(file.get("Rede", "faixaip"))
    ipStart = input("Digite o IP inicial: ")
    ipEnd = input("Digite o IP Final: ")

    if ((int(ipStart) <= 0) or (int(ipEnd) > 254)):
        print("IP inválido!")
    else:
        for cont in ipEnd:
            cont = int(cont) + 1
            hostRemoto = ping(prefixoIP + '.' + faixaDeIp + '.' + str(cont),
                              count=2,
                              interval=1)
            print(prefixoIP + faixaDeIp + str(cont))
            if hostRemoto.is_alive == True:
                print("Online!")
                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as scan:
                    try:
                        temposocket = file.get("Rede", "timesocket")
                        socket.setdefaulttimeout(float(temposocket))
                        scan.connect((ip, 5900))
                        print("VNC Ok")
                        scan.close()
                    finally:
                        menu.opcoes()
Пример #15
0
 def check_alive(self):
     ping_res = ping('www.starlink.com', count=3, interval=0.1, timeout=1)
     #ping_res = ping(self.data["host"], count=3, interval=0.1, timeout=1)
     self.data["is_alive"] = ping_res.is_alive
     if ping_res.is_alive:
         self.data['last_seen_alive'] = datetime.now().strftime("%H:%M:%S")
     return ping_res.is_alive
Пример #16
0
def PingNetwork(Endereco):

    hos = ping(Endereco, count=32, interval=0.5, timeout=1)

    print(f"IP:{hos.address}")
    print(f"Min:{hos.min_rtt}ms")
    print(f"Med:{hos.avg_rtt}ms")
    print(f"Max:{hos.max_rtt}ms")
    print(f"Enviados:{hos.packets_sent}")
    print(f"Recebido:{hos.packets_received}")
    print(f"Perda:{hos.packet_loss}")
    print(f"Host:{hos.is_alive}")
    print(xy.strftime("%X"))
    print(xy.strftime("%x"))

    Result = {
        "Domain": Endereco,
        "Ip": hos.address,
        "Ping-Min": hos.min_rtt,
        "Ping-Avg": hos.avg_rtt,
        "Ping-Max": hos.max_rtt,
        "PacketsSent": hos.packets_sent,
        "PacketsReceived": hos.packets_received,
        "Loss": hos.packet_loss,
        "Accessible host": hos.is_alive,
        "Date": xy.strftime("%x"),
        "hora": xy.strftime("%X")
    }
    with open('return/Ping.json', 'w') as json_file:
        json.dump(Result, json_file, indent=4)
        json_file.close()
    return "Network Ok 01"
Пример #17
0
def latency(dest):
    """Calculate the internet latency stats based on ICMP.

    This method uses icmp echo request/response and calculate the average rtt, packet loss and jitter.

    Args:
        dest (string): hostname or IP address

    """

    PING_REQUESTS.inc()
    try:
        with PING_FAILURES.count_exceptions():
            LOGGER.debug("PING - destination: " + str(dest))
            host = ping(str(dest), count=2, interval=0.5)
        PING_LATENCY.observe(host.avg_rtt / 1000)
        PING_PACKET_LOSS.inc(host.packet_loss)
        PING_JITTER.set((host.max_rtt - host.min_rtt) / 1000)
        LOGGER.debug("PING - max_rtt: " + str(host.max_rtt))
        LOGGER.debug("PING - min_rtt: " + str(host.min_rtt))
        LOGGER.debug("PING - avg_rtt: " + str(host.avg_rtt))
        LOGGER.debug("PING - packet_loss: " + str(host.packet_loss))
        UP.set(1)
    except Exception as e:
        LOGGER.error("Could not process ICMP Echo requests: %s", e)
        UP.set(0)
Пример #18
0
def ping_retry(addr: str, ttl: int) -> bool:
    if ttl <= 0:
        return False

    if not ping(addr, count=1).is_alive:
        return ping_retry(addr, ttl - 1)

    return True
Пример #19
0
def fnTestConnectivity(siteAddress):
    objHost = ping(address=siteAddress, count=1)

    if objHost.is_alive:
        return "Address {}, ({}), can be reached".format(
            siteAddress, objHost.address)
    else:
        return "No connection to {}".format(siteAddress)
Пример #20
0
def pinging(adres):  #metoda pingowanie adresu ip
    global name_text
    tab_ip = {
        "192.168.1.1": "serwer1",
        "192.168.1.2": "serwer2",
        "192.168.1.3":
        "serwer3",  #slownik zawierajacy adresy IP przypisanych do serwerów lub innych urządzeń sieciowych
        "192.168.1.4": "serwer4",
        "192.168.1.5": "serwer5",
        "192.168.1.6": "serwer6",
    }
    host = ping(adres, count=1)  #ping 1 raz wysłanie 1 pakietu
    if host.packet_loss:  #jezeli brak odpowiedzi to jest wykonywana kolejna linia kodu
        host = ping(adres, count=5)  #ping 5 razy wysłanie 5 pakietów
        if host.packet_loss > 0.5:  #jezeli jest wiecej niz połowa (w procentach liczone) utracona to jest wykonywana kolejna linia kodu
            # name_text = tab_ip[adres]  # przypisanie do zmiennej wartosci o kluczu krórym jest adres ip a vartosc to nazwa serwera
            warnings.append(Host(adres, tab_ip[adres]))
Пример #21
0
def do_ping_icmplib(dst):
    host = ping(dst, count=5, interval=0.2)
    if host.is_alive:
        print(f"{Fore.GREEN}pinging {dst}, avg rtt is {host.avg_rtt}")
        print(
            f"sent {host.packets_sent} packets, packet loss is {host.packet_loss} {Fore.RESET}"
        )
    else:
        print(f"{Fore.GREEN}pinging {dst}, host is down {Fore.RESET}")
Пример #22
0
async def check_ping(addr, count=10):
    host = ping(addr, count=count, interval=0.2, timeout=2)
    k = 0.8
    if host.transmitted_packets == 0:
        return False
    elif host.received_packets == 0:
        return False
    elif host.received_packets / host.transmitted_packets < k:
        return False
    else:
        return True
Пример #23
0
def ping(address):
    host = ping(address, count=1)

    is_alive = False
    ping = -1

    if host.is_alive:
        is_alive = True
        ping = utils.format.format_output(round(host.avg_rtt))

    return {"is_alive": is_alive, "ping": ping}
Пример #24
0
 def pingThread(self):
     logger.info('Thread started')
     while True:
         host = ping(self.addr, count=1, interval=1, timeout=2)
         if host.is_alive:
             self.data['status'] = True
             self.data['data'] = host
         else:
             self.data['status'] = False
             self.data['msg'] = 'Device seems down'
             logger.warning('Cannot ping through {}'.format(self.addr))
         time.sleep(self.interval)
Пример #25
0
 def ping(self, addr):
     if len(addr.strip()) == 0:
         return "pong"
     addr = addr.split(" ")[0].strip()
     try:
         result = icmplib.ping(addr)
         if not result:
             return "Request timed out"
         else:
             return "%1.2fms" % (result * 1000)
     except:
         return None
Пример #26
0
	def ping(self, addr):
		if len(addr.strip()) == 0:
			return "pong"
		addr = addr.split(" ")[0].strip()
		try:
			result = icmplib.ping(addr)
			if not result:
				return "Request timed out"
			else:
				return "%1.2fms" % (result * 1000)
		except:
			return None
Пример #27
0
def rede():
    if sys.platform != "linux":
        print("\33[33m"+"Este módulo só funciona em "+"\33[34m"+"Linux."+"\33[31m"+" Saindo...")
        time.sleep(3)
        sys.exit()

    info = configparser.ConfigParser()
    info.read("Configs/Configs.ini")
    qtd = info.get('Rede','pings')
    prefixo = info.get('Rede','prefixip')
    faixa = info.get('Rede','faixaip')
    mostraoff = info.get('Outros','showoffline')
    intervalo = info.get('Rede','timeout')
    faixadeip = int(input("Faixa de IP: "))

    ip = int(input("IP inicial: "+prefixo+"."+str(faixadeip)+"."))

    if (ip < 1):
        print("\33[33m"+"\nEndereço IP inválido!.")
    ipfinal = int(input("IP final: "+prefixo+"."+str(faixadeip)+"."))

    if ipfinal > 254:
        print("Endereço IP inválido!")
        print("\33[33m"+"O IP final não deve ser maior que 254, portanto, o programa verificará até o 254.")
    if ip > ipfinal:
        print("\33[31m"+"O IP inicial não pode ser maior que o final.")
        rede()
    print("\n")
    print("\33[5m"+"Varrendo rede..."+"\33[0m")
    print("\n")
    user = getpass.getuser()
    if user != "root":
        print("**********************************************************************")
        print("* Você não tem privilégios suficientes para isto, execute como sudo. *")
        print("**********************************************************************")
        menu.opcoes()
    for cont in range(ip, ipfinal+1):
        host = ping(prefixo+'.'+str(faixadeip)+'.'+str(cont), count=int(qtd), interval=float(intervalo))
        if host.is_alive == True:
            print("\33[0m")
            print("*"*32)
            print("* "+"\33[36m"+prefixo+"."+str(faixadeip)+"."+str(cont)+"\33[32m"+" ✔️  Host online *")
        else:
            if (mostraoff == "true"):
                print("\33[37m"+prefixo+"."+str(faixadeip)+"."+str(cont)+"\33[31m"+" ❌️ Host offline")
            elif (mostraoff == "false"):
                pass
            elif ((mostraoff != "true") and (mostraoff != "false")):
                print("Valor incorreto na configuração")
                menu.opcoes()
    if os.path.exists("echo.txt"):
        os.remove("echo.txt")
    menu.opcoes()
Пример #28
0
 def do_GET(self):
     if None != re.search('/api/ping/*', self.path):
         ipaddr = "" + self.path.split('/')[-1]
         print(self.path.split('/'))
         #This URL will trigger our sample function and send what it returns back to the browser
         self.send_response(200)
         self.send_header('Content-type', 'text/html')
         self.end_headers()
         self.wfile.write(
             str(ping(
                 ipaddr, count=3, interval=0.2,
                 timeout=1).avg_rtt).encode())  #call sample function here
         return
     if None != re.search('/api/isalive/*', self.path):
         ipaddr = "" + self.path.split('/')[-1]
         print(self.path.split('/'))
         #This URL will trigger our sample function and send what it returns back to the browser
         self.send_response(200)
         self.send_header('Content-type', 'text/html')
         self.end_headers()
         self.wfile.write(
             str(ping(
                 ipaddr, count=3, interval=0.2,
                 timeout=1).is_alive).encode())  #call sample function here
         return
     if None != re.search('/api/mult/*', self.path):
         num1 = float(self.path.split('/')[-1])
         num2 = float(self.path.split('/')[-2])
         #This URL will trigger our sample function and send what it returns back to the browser
         self.send_response(200)
         self.send_header('Content-type', 'text/html')
         self.end_headers()
         self.wfile.write(str(num1 *
                              num2).encode())  #call sample function here
         return
     else:
         #serve files, and directory listings by following self.path from
         #current working directory
         http.server.SimpleHTTPRequestHandler.do_GET(self)
Пример #29
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}")
Пример #30
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)
Пример #31
0
    def check_link_quality(self):
        """ Actually determine the quality of the link """
        res = ping(self.data['host'], count=10, interval=0.1, timeout=0.5)

        # packet_loss is a percent
        self.data['packet_loss'] = int(round(res.packet_loss, 2) * 100)

        # link quality is judged to be the maximum distance from average
        # on the min or max rtt time. Basically, closer numbers to the average
        # are better, because they indicate less jitter. Units are in ms.
        min_diff = res.avg_rtt - res.min_rtt
        max_diff = res.max_rtt - res.avg_rtt
        self.data["link_quality"] = 100 - int(round(max(min_diff, max_diff),
                                                    0))
        return self.data["link_quality"]
Пример #32
0
def check_ping(hostname, x):
    global up, responses
    try:
        data = threading.local()
        data.response = ping(hostname, count=1, timeout=2)

        if data.response.is_alive:
            responses[x - 1] = colored(f"{hostname} is up", "green")
            up += 1

        else:
            responses[x - 1] = colored(f"{hostname} is down", "red")

    except KeyboardInterrupt:
        quit("Stopping...")
Пример #33
0
def ping(address):
	return icmplib.ping(address)