コード例 #1
0
def checkhost(sqlhost, ipv6):
    """check the socket on the other nodes"""
    sqlhostname = reverse_lookup(sqlhost)
    print("\nChecking socket on {} ...".format(sqlhostname))
    if ipv6:
        mping = MultiPing([sqlhost])
        mping.send()
        _, no_responses = mping.receive(1)
    else:
        no_responses = None
        ping_response = ping3.ping(sqlhost, timeout=2)
        if not ping_response:
            no_responses = True

    if no_responses:
        print("{}Skipping {}: ping failed{}".format(RED, sqlhostname, WHITE))
        OTHER_WSREP.remove(sqlhost)
    else:
        cnx_sqlhost = None
        try:
            cnx_sqlhost = MySQLdb.connect(
                user='******',
                passwd=CREDENTIALS["monitor"],
                unix_socket='/var/lib/mysql/mysql.sock',
                host=sqlhost)
        except Exception:  #pylint: disable=W0703
            print("{}Skipping {}: socket is down{}".format(
                YELLOW, sqlhostname, WHITE))
            OTHER_WSREP.remove(sqlhost)
        else:
            print("{}Socket on {} is up{}".format(GREEN, sqlhostname, WHITE))
        finally:
            if cnx_sqlhost:
                cnx_sqlhost.close()
コード例 #2
0
ファイル: market.py プロジェクト: geraybos/zjf_lx
    def ping(self):
        print('step ping')
        with open(self.config_file) as f:
            server_json = json.loads(f.read())[self.server_name]

        mp = MultiPing(server_json['host_dict'].keys())
        mp.send()

        while True:
            try:
                res, no_res = mp.receive(1)
                if len(res):
                    print(u'{} 连接成功'.format(self.server_name))
                    break
                else:
                    print(u'{} 重连'.format(self.server_name))
            except:
                print(u'{} 重连'.format(self.server_name))
            sleep(2)
        self.ip_list = sorted(res.items(), key=lambda x: x[1])[:5]
        # self.ip_list = [min(res, key=lambda x: res[x])]   #20118/6/5  zjf  update
        self.host_dict = dict()
        for ip in self.ip_list:
            self.host_dict[ip[0]] = server_json['host_dict'][ip[0]]
        self.port = server_json['port']
        print(self.host_dict, self.port)
def scan_all_ip():
    ipRange = []
    if windows_dev:
        if debug_level >= 2:
            print(
                "Starting in local Windows development mode, searching local loopback addresses."
            )
        for i in range(1, 2):
            ipRange.append(
                "127.0.0." + str(i)
            )  #Temp code for testing on same Windows machine (loopback)
    else:
        if debug_level >= 2:
            print("Building ping list using %s and %s subnets." %
                  (IP_Addr_Base1, IP_Addr_Base2))
        for i in range(1, 253):  #scans range of IP addresses
            ipRange.append(IP_Addr_Base1 + str(i))
            ipRange.append(IP_Addr_Base2 + str(i))
            if debug_level >= 3:
                print("Adding IP addresses %s and %s to ping list." %
                      (IP_Addr_Base1 + str(i), IP_Addr_Base2 + str(i)))
    mp = MultiPing(ipRange)
    if debug_level >= 2: print("Pinging address list...")
    mp.send()
    responses, no_responses = mp.receive(1)
    for addr, rtt in responses.items():
        if debug_level >= 2: print("%s responded in %f seconds" % (addr, rtt))
    return responses
コード例 #4
0
ファイル: main.py プロジェクト: Anthold/ping_alert
def main():
    addrs = ["192.168.0.1", "192.168.0.2", "192.168.0.3", "192.168.0.25"]
    print("sending one round of pings and checking twice for responses")
    mp = MultiPing(addrs)
    mp.send()

    responses, no_responses = mp.receive(1)

    print("   received responses:  %s" % list(responses.keys()))
    print("   no responses so far: %s" % no_responses)

    print("sending again, but waiting with retries if no response received")

    mp = MultiPing(addrs)
    for i in range(3):
        mp.send()
        responses, no_response = mp.receive(1)

        print("    received responses:     %s" % list(responses.keys()))
        if not no_response:
            print("    all done, received responses from everyone")
            break
        else:
            print("    %d. retry, resending to: %s" % (i + 1, no_response))
    if no_response:
        print("    no response received in time, even after 3 retries: %s" %
              no_response)
        sendMail(no_response)
    print("")
コード例 #5
0
def ping(ip_addr,iterations):
    total_rtt=0
    average_rtt=0
    no_responses_cnt=0
    rtt_list=[]


    for i in range(iterations):
        time.sleep(0.2)
        mp = MultiPing([ip_addr])
        mp.send()
        responses, no_responses = mp.receive(1)

        for _, rtt in responses.items():
            #print("{} responded in {} seconds".format(addr, rtt))
            rtt_list.append(rtt)
            total_rtt+=rtt

        if no_responses:
            print ("These address did not respond: {}".format(no_responses))
            no_responses_cnt+=1

        
    average_rtt=(total_rtt/iterations)*1000
    loss = (no_responses_cnt/iterations)*100

    print("Average Round-trip time is {} ms".format(average_rtt))
    print("Loss is {}%".format(loss))

    return average_rtt, loss
コード例 #6
0
def isHostOn():
    # Request IP Address
    hostIp = input('Whats you IP?\n')

    # Host On Python List
    onHosts = []

    # Splicing IP to determine network to be tested (/24)
    gettingNetwork = hostIp.split('.')

    # Looping through all addresses (/24) (Modify for debugging)
    for host in range(1, 255):
        addressToPing = "{}.{}.{}.{}".format(gettingNetwork[0],
                                             gettingNetwork[1],
                                             gettingNetwork[2], host)
        mp = MultiPing([addressToPing])
        mp.send()
        # Set responses and 1 sec timeout
        responses, no_responses = mp.receive(1)

        if responses.keys():
            for addr, rtt in responses.items():
                # Printing to console host who responded
                print("{} responded in {}".format(addr, rtt))
                onHosts.append(addr)
    # Printing list of addresses that respondeds
    print("\n\n\n\n" + "Host on the network: {}".format(onHosts))
    return onHosts
コード例 #7
0
ファイル: mpingLIB.py プロジェクト: m49log/M49
def mping(network):  #network= x.x.x.x/x return dict{ip(int), time(float)}
    ip_per_scan = ''
    if network[-2:] == '32':
        ip_per_scan = network[:-3]
    else:
        try:
            for x in ipaddress.ip_network(network).hosts():
                ip_per_scan = ip_per_scan + ' ' + str(x)
        except:
            print('network %s do not conform' % network)
            #break

    mp = MultiPing(ip_per_scan.split())
    mp.send()
    responses, no_responses = mp.receive(1)
    if no_responses:
        for addr in no_responses:
            responses[addr] = 1

    ipscan_tmp = {}
    for addr, rtt in responses.items():
        ipscan_tmp[int(ipaddress.IPv4Address(addr))] = round((rtt * 1000), 2)

    ipscan = {}
    for addr in sorted(ipscan_tmp.keys()):  #ordina per ip adress
        ipscan[addr] = ipscan_tmp[addr]
    return ipscan
コード例 #8
0
def ping_check(ip_list):
    mp = MultiPing(ip_list)
    mp.send()
    responses, no_responses = mp.receive(1)
    # responses, no_responses = multi_ping(ip_list, timeout=3, retry=2)
    # print(no_responses)
    return no_responses
コード例 #9
0
ファイル: app.py プロジェクト: ofc076/flask_ping
def hello_world():
    addrs = [addrs_dict[x] for x in addrs_dict]
    #    responses, no_response = multi_ping(addrs, timeout=0.9, retry=2, ignore_lookup_errors=True)
    mp = MultiPing(addrs)
    mp.send()
    responses, no_response = mp.receive(0.9)
    for i in no_response:
        cmd = SYSTEM_PING_COMMAND[:]
        cmd.append(i)
        try:
            if subprocess.check_output(cmd):
                responses[i] = float(1)
        except Exception:
            pass
    res = []
    for k, v in addrs_dict.items():
        current = BusStation(k, v)
        if v in responses:
            current.status = True
        res.append(current)
    print(no_response)
    res.sort(key=lambda x: x.ip)
    # return str(res)
    return render_template(
        'base.html', content_arr=res), 200, add_headers_http(REFRESH_TIME,
                                                             request,
                                                             redirect='')
コード例 #10
0
ファイル: network.py プロジェクト: tjschweizer/StratasysAPI
def getActivePrinters():
    mp = MultiPing([cf.IP_Fortus450,cf.IP_Fortus250_New,cf.IP_Fortus250_Old,cf.IP_uPrint])
    mp.send()
    responses, no_responses=mp.receive(1)
    tmp=[]
    for printer in responses:
        printerData=printer_get_data(printer).decode("utf-8")
        tmp.append(printerData)
        print(tmp)
    return tmp
コード例 #11
0
 def ping(self, tries=1, timeout=1) -> bool:
     """Return true if server is reachable via ping."""
     try:
         mp = MultiPing([self.ip])
         mp.send()
         for _ in range(tries):
             responses, _ = mp.receive(timeout)
             if responses:
                 return True
         return False
     except Exception:
         return False
コード例 #12
0
ファイル: ping.py プロジェクト: jwan9714/PingCF
def multi_ping(ip_list):
    # Create a MultiPing object to test three hosts / addresses
    mp = MultiPing(ip_list)

    # Send the pings to those addresses
    mp.send()

    # With a 1 second timout, wait for responses (may return sooner if all
    # results are received).
    responses, no_responses = mp.receive(1)

    pprint(sorted(responses.items(), key=lambda obj: obj[1], reverse=True))
コード例 #13
0
def sub(host):
    RTT = ''
    mp = MultiPing([host])
    mp.send()

    # With a 1 second timout, wait for responses (may return sooner if all
    # results are received).
    responses, no_responses = mp.receive(1)
    for addr, rtt in responses.items():
        RTT = rtt

    return RTT
コード例 #14
0
ファイル: ping.py プロジェクト: rfdmeshkath/dcim_tool
def check_if_device_is_reachable(addresses):
    mp = MultiPing(addresses)
    # Send the pings to those addresses
    mp.send()
    # With a 1 second timeout, wait for responses (may return sooner if all
    # results are received.
    responses, no_responses = mp.receive(1)
    # print(responses.keys(), no_responses)
    # sleep(5)
    if no_responses:
        # print(no_responses)
        return no_responses
    return []
コード例 #15
0
def multi_pinger(ips):
    try:
        cprint("[-] Pinging %s" % ips)
        if (ips == "192.168.1.0"):
            return
        mp = MultiPing(ips)
        mp.send()
        response, no_response = mp.receive(1)
        for addr, ttl in response.items():
            cprint("%s is live and responed in %f" % (addr, ttl), 'green')
            live.append(addr)
    except MultiPingError:
        cprint("[x] Error " + MultiPingError, 'red')
コード例 #16
0
ファイル: class_collection.py プロジェクト: rvav/Samples
    def ping(host, n=0):
        if (n > 0):
            avg = 0
            for i in range(n):
                avg += ping(host)
            avg = avg / n
        # Create a MultiPing object to test hosts / addresses
        mp = MultiPing([host])

        # Send the pings to those addresses
        mp.send()

        # With a 1 second timout, wait for responses (may return sooner if all
        # results are received).
        responses, no_responses = mp.receive(5)

        for addr, rtt in responses.items():
            RTT = rtt

        if no_responses:
            # Sending pings once more, but just to those addresses that have not
            # responded, yet.
            mp.send()
            responses, no_responses = mp.receive(1)
            RTT = -1

        return RTT
コード例 #17
0
 async def command_ping(self, ctx):
     """Display the local network ping"""
     mp = MultiPing(["8.8.8.8", "8.8.8.4"])
     responses = {}
     for i in range(3):
         mp.send()
         for i in range(50):
             rep, _ = mp.receive(0.1)
             if rep:
                 responses = rep
                 break
         if responses:
             break
     ip, time = responses.popitem()
     await ctx.send("Pong : {} ms".format(int(time * 1000)))
コード例 #18
0
def ping(addrs, timeout=1):
    with socket.socket(socket.AF_INET, socket.SOCK_RAW,
                       socket.IPPROTO_ICMP) as sock:
        mp = MultiPing(addrs, sock=sock, ignore_lookup_errors=True)
        mp.send()
        responses, no_responses = mp.receive(timeout=timeout)

        for addr, rtt in responses.items():
            print("%s responded in %d ms" % (addr, rtt * 1000))
            rrd.rrd_init_or_update('%s.rrd' % addr, int(rtt * 1000))
        if no_responses:
            for addr in no_responses:
                rtt = timeout * 1000
                print("%s responded in %d ms" % (addr, rtt))
                rrd.rrd_init_or_update('%s.rrd' % addr, rtt)
コード例 #19
0
def py_ping(ip_address):

    '''
    In this case ip_address is a string to be converted onto a list with only one argumeny(ip address)
    to return just True or False
    TODO:
    rewrite script to take the list with many ip addresses
    '''
    ip_adresses_list = []
    ip_adresses_list.append(ip_address)
    mp = MultiPing(ip_adresses_list)
    mp.send()
    responses, no_responses = mp.receive(1)
    if responses:
        return True
    if no_responses:
         return False
コード例 #20
0
ファイル: tallylight.py プロジェクト: td0g/OBS_TallyLight
def scan_all_ip():
  ipRange = []
  logging.debug("Pinging all IP addresses")
  for i in range(1,253):
    ipRange.append("192.168.2."+str(i))
    ipRange.append("192.168.1."+str(i))
  mp = MultiPing(ipRange)
  try:
    mp.send()
    responses, no_responses = mp.receive(2)
  except:
    logging.debug("Failure to ping addresses")
    print("Failure to ping addresses")
    return ""
  for addr, rtt in responses.items():
  	logging.debug ("%s responded in %f seconds" % (addr, rtt))
  return responses
コード例 #21
0
    def check_internet_access(self):
        """
        check internet access via Ping
        Pingでインターネット接続を確認する
        """
        connect = False

        try:
            mp = MultiPing(['google.com'])
            mp.send()
            responses, no_responses = mp.receive(1)
            if len(responses) > 0:
                connect = True
        except Exception as e:
            print(e)

        return connect
コード例 #22
0
    def get_results(self, hosts):
        results = []
        mp = MultiPing(hosts)
        mp.send()
        responses, no_responses = mp.receive(1)
        self.count += 1

        for host, rtt in responses.items():
            results.append({'host': host, 'if_answer': True, 'rtt': rtt})

        for host in no_responses:
            if no_responses:
                results.append({'host': host, 'if_answer': False})

        if len(no_responses) == 0:
            sleep(1)

        return results
コード例 #23
0
ファイル: tallylight.py プロジェクト: td0g/OBS_TallyLight
def pingHost(ipToPing):
  p = []
  p.append(ipToPing)
  mp = MultiPing(p)
  try:
    mp.send()
    responses, no_responses = mp.receive(2)
  except:
    logging.debug("Ping " + ipToPing + " Failure - Unable To Ping")
    print("Ping " + ipToPing + " Failure - Unable To Ping")
    return False
  if ipToPing in responses:
    logging.debug("Ping " + ipToPing + " Successful")
    print("Ping " + ipToPing + " Successful")
    return True
    logging.debug("Ping " + ipToPing + ": No Response")
    print("Ping " + ipToPing + ": No Response")
  return False
コード例 #24
0
def pingHost(ipToPing):
    p = []
    p.append(ipToPing)
    mp = MultiPing(p)
    try:
        mp.send()
        responses, no_responses = mp.receive(2)
    except:
        logging.debug("Ping " + ipToPing +
                      " FAILURE! UNABLE to ping IP address!")
        print("Ping " + ipToPing + " FAILURE! UNABLE to ping IP address!")
        return False
    if ipToPing in responses:
        logging.debug("Ping " + ipToPing + " SUCCESSFUL!")
        print("Ping " + ipToPing + " SUCCESSFUL!")
        return True
        logging.debug("Ping " + ipToPing + ": NO RESPONSE!")
        print("Ping " + ipToPing + ": NO RESPONSE!")
    return False
コード例 #25
0
def ping(host, targets, df=None):
    ips = domains_to_ips(targets)
    t_to_ip = dict(zip(targets, ips))

    date = datetime.now()
    mp = MultiPing(ips, ignore_lookup_errors=True)
    mp.send()
    responses, no_responses = mp.receive(1)
    
    if type(df) == type(None):
        df = pd.DataFrame(columns=["date", "host", "target", "target_ip", "rtt"])

    for t, ip in t_to_ip.items():
        if ip in responses:
            df.loc[len(df)] = [date, host, t, ip, responses[ip] * 1000]
        else:
            df.loc[len(df)] = [date, host, t, ip, np.NaN]
    
    return df
コード例 #26
0
ファイル: check.py プロジェクト: liuwenjie-123/python_camp
def get_down_ip(ip_list_dict):
    for project_name, pronject_area_list in ip_list_dict.items():
        # print(project_name, pronject_area_list)
    # key是项目名称
        count = 0
        for area_dict in pronject_area_list:
            for area_dict_key, area_dict_value in area_dict.items():
                ip_list = area_dict_value
                mp = MultiPing(ip_list)
                mp.send()
                responses, no_responses = mp.receive(1)
                # responses, no_responses = multi_ping(ip_list, timeout=3, retry=2)
                no_responses.append(len(area_dict_value))
                #把不通的IP替换原来的列表里的IP
                ip_list_dict[project_name][count][area_dict_key] = no_responses
                # 查看默认发送接收缓冲区大小
                recv_buff = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
                send_buff = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
                print(f'默认接收缓冲区大小:{recv_buff}。默认发送缓冲区大小:{send_buff}')
            count += 1
    return ip_list_dict
コード例 #27
0
    def ping(self):
        # Create list of both IPv4 and IPv6 addresses if available
        ip_addresses = [
            ip for ip in [self.ipv4_address, self.ipv6_address]
            if ip is not None
        ]

        if not ip_addresses:
            raise ValueError("No IPs available")

        ping = MultiPing(ip_addresses)
        ping.send()
        responses, no_responses = ping.receive(1)

        if responses:
            self.state = True
            self.last_online = timezone.now()
            return True
        else:
            self.state = False
            return False
コード例 #28
0
def checkwsrep(sqlhost, ipv6):
    """check if the other nodes belong to the cluster"""
    sqlhostname = reverse_lookup(sqlhost)
    if ipv6:
        mping = MultiPing([sqlhost])
        mping.send()
        _, no_responses = mping.receive(1)
    else:
        no_responses = None
        ping_response = ping3.ping(sqlhost, timeout=2)
        if not ping_response:
            no_responses = True

    if no_responses:
        print("{}Skipping {}: it is not in the cluster{}".format(
            YELLOW, sqlhost, WHITE))
    else:
        print("\nChecking if {} belongs to cluster ...".format(sqlhostname))
        cnx_sqlhost = None
        wsrep_status = 0
        try:
            cnx_sqlhost = MySQLdb.connect(
                user='******',
                passwd=CREDENTIALS["monitor"],
                unix_socket='/var/lib/mysql/mysql.sock',
                host=sqlhost)
            cursor = cnx_sqlhost.cursor()
            wsrep_status = cursor.execute("""show variables LIKE 'wsrep_on'""")
        except Exception:  #pylint: disable=W0703
            pass
        finally:
            if cnx_sqlhost:
                cnx_sqlhost.close()
        if wsrep_status == 1:
            LASTCHECK_NODES.append(sqlhost)
            print("{}{} belongs to cluster{}".format(GREEN, sqlhostname,
                                                     WHITE))
        else:
            print("{}Skipping {}: it is not in the cluster{}".format(
                YELLOW, sqlhost, WHITE))
コード例 #29
0
def main():

    subnets = {}
    while 1:
        user_input = input(
            "\nEnter 'exit' to quit subnet entry.\n\nEnter subnet(s) to scan (i.e 192.168.1.0/24): "
        ).lower()

        if user_input == "exit":
            break
        try:
            network = ipaddress.ip_network(user_input)
        except ValueError or Exception as err:
            print(f"ERROR: Invalid IPv4 Network, {err}")
            continue
        print(f"\nGathering subnet {user_input} information...")
        subnets[network] = {}
        all_hosts = [str(host) for host in network.hosts()]
        mp = MultiPing(all_hosts)
        mp.send()
        alive, not_alive = mp.receive(1)
        subnet_utilization = ((len(alive) / len(all_hosts) * 100) // 1)
        subnet_utilization_string = f"Subnet Utilization: {subnet_utilization}% \tHosts Alive: {len(alive)}"
        all_alive_hosts = [list(alive.keys())[i] for i in range(0, len(alive))]
        subnets[network]['subnet util'] = subnet_utilization_string
        subnets[network]['alive hosts'] = {}
        for host in all_alive_hosts:
            subnets[network]['alive hosts'][str(host)] = get_mac_address(
                ip=str(host))
            if subnets[network]['alive hosts'][str(host)] is None:
                print(
                    "WARNING: Remote network detected, cannot gather MAC Addresses..."
                )
                for remote_host in all_alive_hosts:
                    subnets[network]['alive hosts'][str(
                        remote_host)] = "Unknown"
                break
        print(f"Successfully scanned subnet {user_input}...")
    return display_info(subnets)
コード例 #30
0
def ping2(ips):
    from multiping import MultiPing, multi_ping
    import copy

    receive_timeout = 2

    # Create a MultiPing object to test three hosts / addresses
    mp = MultiPing(ips)

    # Send the pings to those addresses
    mp.send()

    # With a 5 second timout, wait for responses (may return sooner if all
    # results are received).
    responses, no_responses = mp.receive(receive_timeout)
    #travel_backpack.pp({'responses':responses, 'no responses':no_responses})
    if responses is None:
        responses = {}

    #responses = copy.deepcopy(responses)

    #for i in range(5):
    while no_responses:
        print('No responses:')
        travel_backpack.pp(no_responses)
        if no_responses:
            mp = MultiPing(no_responses)
            mp.send()
            new_responses, no_responses = mp.receive(receive_timeout)
            if new_responses is not None:
                responses.update(new_responses)
            #travel_backpack.pp({'responses':responses, 'no responses':no_responses})
        else:
            break

    #print('final:')
    #travel_backpack.pp({'responses':responses, 'no responses':no_responses})
    return responses, no_responses