def sort_given_ple_nodes(self, ple_list): ''' Sort given PLE nodes based on RTT measurements Return: sorted list of PLE nodes, 1st: min ''' for node in ple_list: # ignore first ping if (ping.Ping(node, timeout=2000).do()) is None: # in case of timeout break self._delays[node] = 0 for i in range(PING_NO): delay = ping.Ping(node, timeout=2000).do() if delay is not None: self._delays[node] += delay if DEBUG: print self._delays[node] else: # timeout occurs at least once: # dont use the node del self._delays[node] break else: # calculate average self._delays[node] /= PING_NO if DEBUG: print "delays: " + str(self._delays) # ordered ple list, 1st: min return sorted(self._delays, key=self._delays.get)
def ping_measurement(node): ''' Function for parallel ping measurements using with multiprocess Return: (node, average delay or None if timeout occurs) ''' # ignore first ping if (ping.Ping(node, timeout=2000).do()) is None: # in case of timeout return (node, None) delay_avg = 0 for i in range(PING_NO): delay = ping.Ping(node, timeout=2000).do() if delay is not None: delay_avg += delay else: # timeout occurs at least once: # dont use the node return (node, None) else: # calculate average delay_avg /= PING_NO return (node, delay_avg)
def check_connections(self): import ping, socket connections_good = True try: ping.verbose_ping(self.base_page_address, count=1) delay = ping.Ping(self.base_page_address, timeout=2000).do() except socket.error: connections_good = False print("ping error when trying to connect to: ", self.base_page_address) try: ping.verbose_ping(self.video_stream_address, count=1) delay = ping.Ping(self.video_stream_address, timeout=2000).do() except socket.error: connections_good = False print("ping error when trying to connect to: ", self.video_stream_address) return connections_good
def main(): signal.signal(signal.SIGINT, kill_myself) signal.signal(signal.SIGTERM, kill_myself) args = Utilities.input_parser() # object for iteration ip_iter_obj = AddressIter(args.list, args.ip_network) proto = args.ARP pinger = ping.Ping(proto, args.timeout, args.p_hostname) while True: print_header() with TPool() as TManager: future_to_ping = [ TManager.submit(pinger.ping_host, str(ip)) for ip in ip_iter_obj ] try: for thread in as_completed(future_to_ping): try: host, st, time = thread.result() print_result(host, st, time) # print_only_online(host, st, time) except ping.PermissionException: print('You need to have root rights to run this.') break except KeyboardInterrupt: print('here') for thread in future_to_ping: thread.cancel() break if args.refresh: sleep(args.refresh) else: break
def try_to_ping(host): sum = 0.0 best = None worst = None loss = 0 for i in range(0, attempts): try: delay = ping.Ping(host, timeout=timeout).do() #timeout in ms time.sleep(interval / 1000) if delay: sum += delay if not best or best > delay: best = delay if not worst or worst < delay: worst = delay else: loss += 1 except socket.error, e: loss += 1
def __init__(self, hostname, count=3, timeout=1000, packet_size=55): self.hostname = hostname self.count = count self.timeout = timeout self.latency = 0 self.packet_size = packet_size self.p = ping.Ping(self.hostname, self.timeout, self.packet_size)
def alive(url): for key in ["ns.", "ns1.", "ns2.", "ns3.", "dns.", "dns1.", "dns2."]: try: lat = ping.Ping(key + url, timeout=2000).do() return key except Exception as e: print e continue return ""
def get_pings(since): pings = [] pattern = re.compile('Failed password for [invalid user ]*root from ([^ ]+) port [0-9]+ .*') p = subprocess.Popen(['journalctl', '-b', '-o', 'json', '--since', since, '-u', 'sshd.service'], stdout=subprocess.PIPE) out = p.communicate()[0].decode('utf-8').strip() for log in out.split('\n'): if log != '': j = json.loads(log) m = pattern.match(j['MESSAGE']) if m != None: pings.append(ping.Ping(j['__REALTIME_TIMESTAMP'], m.group(1))) return pings
def __init__(self, mmsGroupName, tag=None, *args, **kwargs): self.mmsGroupName = mmsGroupName self.tag = tag self.mongo = kwargs['mongo'] # Individual ping documents self.pings = {} # If tag not specified get the most recent tag of the group if self.tag is None: try: match = {'name': mmsGroupName} proj = {'_id': 0, 'tag': 1} curr_pings = self.mongo.euphonia.pings.find(match, proj).\ sort("tag", -1).limit(1) except pymongo.errors.PyMongoError as e: raise e if curr_pings.count() > 0: self.tag = curr_pings[0]['tag'] if self.tag is not None: try: # Get all pings with this tag match = {'tag': self.tag, 'hostInfo.deactivated': False} curr_pings = self.mongo.euphonia.pings.find(match) except pymongo.errors.PyMongoError as e: raise e for p in curr_pings: self.pings[p['_id']] = ping.Ping(p) # Get Salesforce project id res = mmsGroupNameToSFProjectId(mmsGroupName, self.mongo) if not res['ok']: raise Exception("Failed to determine Salesforce project id for MMS" "group %s" % mmsGroupName) gid = res['payload'] from groupping_tests import GroupPingTests grouptestdocument.GroupTestDocument.__init__( self, groupId=gid, mongo=self.mongo, src='pings', testsLibrary=GroupPingTests)
def expPing(self, urlsToPing): delay = 0 timeouts = 0 for url in urlsToPing: try: response = ping.Ping(url, timeout=5000).do() #result in msec except socket.error as e: print "Ping Error: ", e, ", exiting" exit except: print "Ping Error, exiting" exit if (response == "Request timed out."): timeouts += 1 continue else: delay += response return delay, timeouts
sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progressSize / (1024 * 1024), speed, duration)) sys.stdout.flush() a = [[ "Linode Fremont", "speedtest.fremont.linode.com", "http://speedtest.fremont.linode.com/100MB-fremont.bin" ], ["BuyVM", "205.185.112.31", "http://speedtest.lv.buyvm.net/100mb.test"]] for one in a: times = 10 all_ = [] for i in range(1, times): delay = ping.Ping(one[1], timeout=2000).do() if delay: all_.append(delay) print one[0] + '\n' + str(sum(all_) / len(all_)) + 'ms' + '\n' p = multiprocessing.Process( target=urllib.urlretrieve(one[2], reporthook=reporthook)) p.start() #exec_proc = subprocess.Popen(urllib.urlretrieve(one[2],reporthook=reporthook), stdout = subprocess.PIPE, stderr = subprocess.STDOUT, shell = True) #max_time = 10 #cur_time = 0.0 #return_code = 0 #while cur_time <= max_time: # #if exec_proc.poll() != None: # # return_code = exec_proc.poll() # # break # time.sleep(0.1)
] f = open("ipexample.bin", "rb") test = f.read() ipv4 = ping.IPv4(test) icmpv4 = ping.ICMPv4(ipv4.payload) print(ipv4.src, ipv4.dst, ipv4.rem, ipv4.size) print(icmpv4.msg_body) a = ping.ip.make_simple_ping() icmp2 = ping.ICMPv4(a) print("checksum: ", ping.ip.inet_checksum(a)) p = ping.Ping() suc, dt = p.ping_once("www.google.com", 0.5) print(suc, dt) a = p.ping_seq("www.google.com", 4, 0.2, 0.6) for suc, dt in a: print(f"{suc} - {dt*1000:3.7f} ms") a = p.ping_multi(HOSTS) print( "\n".join( [ f"{host:18s}: {delay:.6f}" for host, delay in a.items() ]
import ping, socket try: ping.verbose_ping('www.google.com', count=3) delay = ping.Ping('www.wikipedia.org', timeout=2000).do() except socket.error, e: print "Ping Error:", e
import ping, socket import sys x = (int)(sys.argv[1]) ips = open("PhysicalIPsorted", "r").read()[1:-1].split(",") f = open("PhysicalIPsortedtimes" + str(x), "w") total = 0 for i in range(len(ips)): ips[i] = ips[i].strip("' ") print((int)(ips[i].split(".")[0])) / 10, ips[i] if (((int)(ips[i].split(".")[0])) / 10 != x): continue print ips[i] try: delay = ping.Ping(ips[i], timeout=4000).do() f.write(ips[i] + " " + str(delay) + "\n") total += delay print delay except socket.error, e: f.write(ips[i] + " " + "Ping Error:" + str(e) + "\n") print "#####################Ping Error:", e pass except TypeError: f.write(ips[i] + " " + "timeout" + "\n") print total
# User configurable settings LOG_FILENAME = "uptime_log.txt" DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S" ROUTER_IP = "192.168.1.1" RECORD_INTERVAL_SECS = 30 PING_SITES = [ "google.com", "yahoo.com", ] # End settings pings = [ping.Ping(hn, 1000, 55, print_stats=False) for hn in PING_SITES] rp = ping.Ping(ROUTER_IP, 55, print_stats=False) with open(LOG_FILENAME, "w") as lf: while True: successes = [False for p in PING_SITES] for i, p in enumerate(pings): p.run(1) if p.send_count == p.receive_count: successes[i] = True # if all false internet = True router = True if all((not a for a in successes)): internet = False
def last_ping(): pings = get_pings('-1h') if len(pings) == 0: return ping.Ping() return max(pings, key=attrgetter('timestamp'))
def check_ping(hostname, count, timeout, packet_size=55): p = ping.Ping(hostname, timeout, packet_size) p.run(count) return p.send_count, p.receive_count, p.total_time