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("")
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
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
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()
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
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
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
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
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='')
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 ping(host, n=1, timeout=1, retry_on_failure=True): """ Ping a host :param host: host to ping :type host: str :param n: ping how many times, default=1 :type n: int :param timeout: Timeout in seconds. How long to wait for ICMP response. :type timeout: int :param retry_on_failure: Do a final attempt on those hosts, which failed to respond. :type retry_on_failure: bool :return: float Round Trip Time [s] """ if n < 1: raise ValueError("n needs to be a positive integer") if n > 1: avg = 0 for i in range(n): avg += ping(host) avg = avg / n return avg # Pinging only once. # Create a MultiPing object to test hosts / addresses mp = MultiPing([host]) # 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(timeout) rtt = None for addr, rtt in responses.items(): rtt = rtt if retry_on_failure and no_responses: # Sending pings once more, but just to those addresses that have not # responded, yet. mp.send() responses, no_responses = mp.receive(timeout) return rtt
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
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
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))
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
def __ping(node, n=0): if ":" in node: node = node.split(":")[0] if n > 0: avg = 0 for i in range(n): avg += Node.__ping(node) avg /= n try: mp = MultiPing([node]) mp.send() r, nr = mp.receive(1) for addr, rtt in r.items(): RTT = rtt if nr: mp.send() r, nr = mp.receive(1) RTT = -1 return RTT except: return -1
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 []
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')
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
def find_alive_hosts(networks_input, verbose): ips_to_ping_full, invalid = _get_ips_to_ping(networks_input) if invalid: click.echo() if not ips_to_ping_full: click.echo('No valid IPv4 addresses or networks entered. Quitting.') sys.exit() click.echo('\nPinging addresses...') ping = MultiPing(ips_to_ping_full) ping.send() responses_1, timeouts_1 = ping.receive(0.5) responses = responses_1.copy() if verbose and responses_1: click.echo( f"\nIPs responded to first ping:\n{', '.join([x for x in responses_1])}\n" ) if len(ips_to_ping_full) > len(responses_1): ping.send() responses_2, timeouts_2 = ping.receive(5) responses.update(responses_2) if verbose and responses_2: click.echo( f"\nIPs responded to second ping:\n{[x for x in responses_2]}\n" ) hosts_alive = sorted(responses.keys(), key=lambda x: IPv4Address(x)) click.echo(f"{len(hosts_alive)} hosts responded to ping.\n") return (*hosts_alive, )
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)
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)))
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
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
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
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
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
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
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
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