def send_ping(self,addrs,no_of_retries): print("sending again, waiting with retries via provided send_receive()") responses, no_response = multi_ping(addrs, timeout=1, retry=2,ignore_lookup_errors=True) print("\n\n\n\n reponses: %s" % list(responses.keys())) if no_response: print("\n no response received in time, even after retries: %s" % no_response)
def do_health_checks(self, list_of_ips): """ Perform a health check on a list of IP addresses, using ICMPecho. Return tuple with list of failed IPs and questionable IPs. """ # Calculate a decent overall timeout time for a ping attempt: 3/4th of # the monitoring interval. That way, we know we're done with this ping # attempt before the next monitoring attempt is started. ping_timeout = self.get_monitor_interval() * 0.75 # Calculate a decent number of retries. For very short intervals we # shouldn't have any retries, for very long ones, we should have # several ones. Converting the timeout to an integer gives us what we # want: For timeouts less than 1 we have no retry at all. num_retries = int(ping_timeout) try: self.ping_count += len(list_of_ips) responses, no_responses = multiping.multi_ping( list_of_ips, ping_timeout, num_retries) self.update_stats(responses, no_responses) except Exception as e: logging.error("Exception while trying to monitor servers: %s" % str(e)) # Need to assume all IPs failed no_responses = list_of_ips return no_responses, [] # return empty list for questionable IPs
def devices_from_network(self, string_network, window=30): network = ipaddress.ip_network(string_network) hosts = network.hosts() host_string_ip = [] for host in hosts: host_string_ip.append(str(host)) final_responses = {} final_no_responses = {} ip_devices = [] while (len(host_string_ip) > 0): if (window > (len(host_string_ip))): window = len(host_string_ip) responses, no_responses = multi_ping(host_string_ip[0:window - 1], timeout=1, retry=2) # pprint(responses) if (window == len(host_string_ip)): host_string_ip = [] else: host_string_ip = host_string_ip[window:] # pprint(host_string_ip) ip_devices = ip_devices + [*responses] self.verbose.info("responses {0}".format(len(str( responses.keys())))) final_responses = {**responses, **final_responses} devices = [] self.logger_connection.info("Devices up {0} in net {1}".format( len(ip_devices), string_network)) for ip in ip_devices: device = CiscoIOS(ip, "ios", self.master) devices.append(device) self.verbose.debug("Devices created {0}".format(len(devices))) devices = self.correct_device_platform(devices) self.verbose.debug("devices corrected {0}".format(len(devices))) return devices, ip_devices
def check_host(addrs): try: response, no_response = multi_ping(addrs, timeout=1, retry=2, ignore_lookup_errors=False) #Additional retries attempted within the timeout period if response: return True if no_response: return False except Exception as e: print("str(e)")
async def send_pings(websocket, path): while True: responses, no_responses = multi_ping(ips, timeout=2, retry=3) for n in nodes: if n['ip'] in responses: n['ping'] = responses[n['ip']] * 1000 n['result'] = True else: n['ping'] = 9999 n['result'] = False await websocket.send(json.dumps(nodes))
def get_cluster_nodes(name): nodes = list(clusters[name]['nodes'].values()) ips = [ n['ip'] for n in nodes] resp, no_resp = multi_ping(ips, timeout=2, retry=3) for n in nodes: if n['ip'] in resp: n['ping'] = resp[n['ip']] * 1000 n['status'] = True else: n['ping'] = 9999 n['status'] = False return jsonify(nodes)
def check_ping(self): ''' Ping the addresses up to 4 times (initial ping + 3 retries), over the course of 2 seconds. This means that for those addresses that do not respond another ping will be sent every 0.5 seconds. ''' addrs = [ "192.168.0.1", "192.168.0.100", "192.168.0.2", "192.168.0.102", "192.168.0.101" ] responses, no_responses = multi_ping(addrs, timeout=3, retry=3) for addr, rtt in responses.items(): print(f"{addr} responded in {rtt} seconds") self.ping_fail_ip = no_responses
def NetTestingPingExecute(self): #Defines the variables based on properties set above device_ip_address = self.device_ip_address result_of_ping = self.result_of_ping #Try statement to ensure the IP address entered is valid. If it is an invalid address the ipaddress module will raise a value error, at which point the user is informed that a valid IP address is required using a popup try: device_ip_address[ 0] = self.ids._IPv4_Target_Device_Layout_.ids.IPv4AddressTextInput.text ipaddress.ip_address(device_ip_address[0]) #ipaddress raises a value error when an invalid IP address is used except ValueError: Factory.InvalidIPAddressPopup().open() return #Exit from the function retry_amount = self.ids._Net_Testing_Ping_Layout_.ids.RetryAmountSpinner.text #retry_amount is set a the value of the retry spinner #If statement to check if the user set a retry anount, if not the retry amount is set to 0 if retry_amount == 'No Retries': retry_amount = 0 else: pass #Intiates the ping using the variables set, the responses will be outputted to 'responses' and 'no_response' depending if a response to the ping is recieved responses, no_responses = multi_ping(device_ip_address, timeout=0.5, retry=retry_amount, ignore_lookup_errors=True) #If statement to check the result of the ping if responses: #If a respone is found it is set as successful result_of_ping = 'Success' if no_responses: #If no response is found it is set as failed result_of_ping = 'Failed' self.ids._Net_Testing_Ping_Layout_.ids.ResultsLabel.text = "Result of ping to '[i]" + str( device_ip_address[0] ) + "[/i]' - [b] " + result_of_ping + " [/b]" #Sets the label on the screen stating the device pinged and the result of the ping
def callMain(): print("Checking IP addresses of the Atlas servers") checkIPAddrs() print("Using ICMP ping messages to contact servers") addrs = [atlasEUIP, atlasUSIP] responses, no_responses = multi_ping(addrs, timeout=4, retry=6) if not no_responses: print(f"Both servers responded to pings") else: print("...No responses received from: %s" % no_responses) try: print_ssl = open_ssl_socket(atlasEU) except ssl.SSLError: print(f"Could not connect to the Atlas EU server securely") print(f"...Opened an SSL connection to atlas EU. Version is {print_ssl}") try: print_ssl = open_ssl_socket(atlasUS) except: print(f"Could not connect to the Atlas US server securely") print(f"...Opened an SSL connection to atlas US. Version is {print_ssl}")
def auto_add_record(domain_name, region, username): zone = ZoneRecordDal.select_zone(domain_name) # Select an unsed ip if @domain name has no records existed. records = IpPool.query.outerjoin(DnsRecord, DnsRecord.record == IpPool.fixed_ip).add_columns( IpPool.fixed_ip, DnsRecord.record).filter(IpPool.region == region, DnsRecord.record.is_(None), IpPool.allocated.is_(True)).order_by(IpPool.fixed_ip) for item in records: ip = item.fixed_ip if CONF.etc.env != 'dev': responses, no_responses = multi_ping([ip], timeout=10, retry=2, ignore_lookup_errors=True) # 如果ping成功,那么ip不可用于自动分配 if responses: IpPool.query.filter_by(fixed_ip=ip).update({'allocated': False}) log.error("%s should have been set allocated=False since it is ping-able." % ip) continue with db.session.begin(subtransactions=True): try: iprecord = IpPool.query.filter_by(fixed_ip=ip).with_for_update(nowait=True, of=IpPool).first() except Exception: log.error("%s has been locked by other process" % ip) continue if DnsRecord.query.filter_by(record=ip).first(): continue record_type = 'A' if iprecord.is_ipv6: record_type = 'AAAA' insert_record = DnsRecord(domain_name=domain_name, record=ip, zone_name=zone, update_user=username, record_type=record_type) db.session.add(insert_record) return ZoneRecordDal.increase_serial_num(zone) else: raise BadParam("No unused ip for region:%s." % region, msg_ch=u'没有可用的ip')
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) print("") # Having control over your retries is powerful and gives you lots of # flexibility, but sometimes you don't want to deal with it manually and # just want 'the right thing' to be done for you. # # Fortunately, MultiPing provides a ready-made function to do the retry for # you, called multi_ping(). Specify the overall timeout and the number of # additional retries (which are attempted within this timeout). Omit the # 'retry' parameter or set to 0 and there will only be a single send. # # We are also adding an address we won't be able to resolve and set the # 'ignore_lookup_errors' flag, to show that those can be ignored if wanted. # They will just appear in the 'no response' return list. If the flag is # not set then an exception would be thrown. addrs.append("cannot.resolve.thiscom") print("sending again, waiting with retries via provided send_receive()") responses, no_response = multi_ping(addrs, timeout=0.5, retry=2, ignore_lookup_errors=True) print(" reponses: %s" % list(responses.keys())) if no_responses: print(" no response received in time, even after retries: %s" % no_response)
mp = MultiPing(addrs) for i in range(3): mp.send() responses, no_response = mp.receive(0.01) 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) print("") # Having control over your retries is powerful and gives you lots of # flexibility, but sometimes you don't want to deal with it manually and # just want 'the right thing' to be done for you. # # Fortunately, MultiPing provides a ready-made function to do the retry for # you, called multi_ping(). Specify the overall timeout and the number of # additional retries (which are attempted within this timeout). Omit the # 'retry' parameter or set to 0 and there will only be a single send. print("sending again, waiting with retries via provided send_receive()") responses, no_response = multi_ping(addrs, timeout=0.5, retry=2) print(" reponses: %s" % list(responses.keys())) if no_responses: print(" no response received in time, even after retries: %s" % no_response)
# ------------------------------------------- # 'IMPORTANT' GLOBAL VARS ping_address = "google.com" ping_delay = 0.5 # ISDOWN VARS, used to check if internet is down and calculate how long it has been down. is_down = False last_down = datetime.datetime.now() # COUNTERS bad_pings = 0 # Counts how many bad pings (>50) since last tweet. while True: responses, no_responses = multi_ping([ping_address], timeout=1, retry=2, ignore_lookup_errors=True) date = datetime.datetime.now() # Basically if internet is down if no_responses: print("Could not find IP. Maybe you have no connection?") # Write ping as -1 if down. Threat level = 9. result = Result(no_responses[0], date, -1, 9) # Write even if internet is down file = open("allping.txt", "a") write(file, result) file.close()
# ping) to those hosts that haven't responded, yet. Send can be called # multiple times and will result in pings to be resent to those addresses # from which we have not heard back, yet. Here we try three pings max. 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(0.01) 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) print("") # Fortunately, MultiPing provides a ready-made function to do the retry for # you, called send_receive(). Specify the overall timeout and the number of # additional retries (which are attempted within this timeout). Omit the # 'retry' parameter or set to 0 and there will only be a single send. print("sending again, waiting with retries via provided send_receive()") responses, no_response = multi_ping(addrs, 0.5, 2) print(" reponses: %s" % list(responses.keys())) if no_responses: print(" no response received in time, even after retries: %s" % no_response)
rootLogger = logging.getLogger() fileHandler = logging.FileHandler("{}".format(config['logfile'])) fileHandler.setFormatter(logFormatter) rootLogger.addHandler(fileHandler) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) rootLogger.addHandler(consoleHandler) rootLogger.setLevel(logging.DEBUG) try: rootLogger.info("Started pingcheck...") while True: slowest_time = 0 responses, no_responses = multi_ping(list(config['hosts'].keys()), timeout=config["timeout"], retry=3) for host, time in responses.items(): # if ping time is to high if time > config["slow_ping"]: rounded_time = round(time, 3) rootLogger.warning( "Slow ping to host: {} - {}, ping time: {}".format( host, config['hosts'][host], rounded_time)) # calculate slowest ping for exact sleep time if time > slowest_time: slowest_time = time if len(no_responses): # we've run into timeout value
from multiping import multi_ping address = ["10.8.32.10", "10.8.32.200", "8.8.8.8", "www.detik.cm"] responses, no_responses = multi_ping(address, timeout=2, retry=3) print(responses) print(no_responses)