def get_ping(address): p = Ping(destination=address) sum = 0 for _ in range(0, 10): sum += p.do() mean = sum / 10.0 return mean
def poll(self): from ping import Ping import socket try: p = Ping(self.resolve(self.site), 1, 55) return 0, p.do() except socket.error: print 1, 'Need Superuser Priviledges'
def run(self): while True: ip = self.job_queue.get() p = Ping(destination=ip) for i in range(self.count): #p.run(self.count) # 发送一个icmp包 p.do() # 收到回包,ping ok if p.receive_count == 1: break # count+last_count个包都丢了,当成ping不可达 if p.receive_count == 0: self.result_queue.put(ip) print "ip %s done: %s" % (ip, p.receive_count) self.job_queue.task_done()
def __call__(self): """ Run the ping, print '!' for success and '.' for failure. """ p = Ping(self.destination, silent=True) while True: if p.do(): sys.stdout.write('!') sys.stdout.flush() else: sys.stdout.write('.') sys.stdout.flush()
def ping(self, host): try: p = Ping(host) result = p.do() # Inverts results so that they make more sense if result > 0: return 1 else: return 0 except socket.error, e: print "Ping Error:", e
"-w", dest="timeout", type=int, default=defaults.timeout, help="Timeout in milliseconds to wait for each reply." ) # Continuous flag (default is False) parser.add_argument("-t", dest="continuous", action="store_true", help="Ping the specified host until stopped.") # Number of pings parser.add_argument("-n", dest="count", type=int, help="Number of echo requests to send.") # Interval between pings (for Continous is True or Count > 1) parser.add_argument( "-i", dest="interval", type=int, default=defaults.interval, help="Wait interval seconds between sending each packet.", ) args = parser.parse_args() # If multiple pings, user Pinger() if args.continuous or args.count: sys.exit(Pinger(args.hostname, args.size, args.timeout, args.continuous, args.count, args.interval)) # Otherwise, just use single ping else: p = Ping(args.hostname, args.size, args.timeout) delay = p.do() print p print delay
def ping_once(host, timeout_ms=1000, packet_size=55, own_id=None): p = Ping(host, timeout=timeout_ms, packet_size=packet_size, own_id=own_id) ret = p.do() return ret
from ping import Ping p = Ping(destination='127.0.0.1',timeout=1000) p.run(3) print p.receive_count p.run(4) print p.receive_count p.do() p.do() p.do() print p.receive_count
help='Ping the specified host until stopped.') # Number of pings parser.add_argument('-n', dest='count', type=int, help='Number of echo requests to send.') # Interval between pings (for Continous is True or Count > 1) parser.add_argument( '-i', dest='interval', type=int, default=defaults.interval, help='Wait interval seconds between sending each packet.') args = parser.parse_args() # If multiple pings, user Pinger() if args.continuous or args.count: sys.exit( Pinger(args.hostname, args.size, args.timeout, args.continuous, args.count, args.interval)) # Otherwise, just use single ping else: p = Ping(args.hostname, args.size, args.timeout) delay = p.do() print p print delay
def ping_host(host): with no_stdout(): p = Ping(host, timeout=PING_TIMEOUT) return p.do()
class PingThread(Thread): '''The PingThread class manages pinging a specific network device in a thread and notifying any corresponding netdev rules that the network device was lost or found. ''' def __init__(self, hostname, config, timeout=500, packetSize=55): ''' * hostname -- The hostname for the network device * config -- The NetDevConfig object * timeout -- The ping timeout * packetSize -- The ping packet size ''' Thread.__init__(self) self.__hostname = hostname self.__timeout = timeout self.__config = config self.__foundHost = False self.__discoverRules = [] # List of rules to notify on device found self.__lostRules = [] # List of rules to notify on device lost self.__ping = Ping(self.__hostname, timeout, packetSize) def addRule(self, rule): '''Add a single rule pertaining to the network device managed by this PingThread. * rule -- The netdev rule ''' if rule.isDiscoverRule(): self.__discoverRules.append(rule) elif rule.isLostRule(): self.__lostRules.append(rule) def stop(self): '''Stop the PingThread.''' self.__shouldExit = True def run(self): '''Called when the PingThread is started.''' self.__shouldExit = False while not self.__shouldExit: foundHost = self.__pingHost() if foundHost != self.__foundHost: if foundHost: self.__config.log(LogPriority.Info, "Discovered host") # Notify all rules of a discovered device for rule in self.__discoverRules: rule.onNotify() else: self.__config.log(LogPriority.Info, "Lost host") # Notify all rules of a lost device for rule in self.__lostRules: rule.onNotify() self.__foundHost = foundHost sleep(0.1) def __pingHost(self): '''Handle pinging the network device a single time.''' pingTime = self.__ping.do() return (pingTime is not None)
class Pinger(object): def __init__(self, hostname, buffer_size = defaults.buffer_size, timeout = defaults.timeout, continous = False, count = defaults.pinger_count, interval = defaults.interval): self.hostname = hostname self.delays = [] self.ping = Ping(hostname, buffer_size, timeout) start_time = defaults.timer() if not continous and not count: return i = 0 while True: try: # Wait, to run do() every interval seconds time.sleep(start_time + i*interval - defaults.timer()) # Do ping self.ping.do() self.delays.append(self.ping.delay) print self.ping # Catch Ctrl + C except KeyboardInterrupt: print "" print self.statistics() # Exit sucessfully if loss is less than 50% return # Increment count i += 1 # Break out of loop if count and i >= count: break print self.statistics() # Exit sucessfully if loss is less than 50% return def statistics(self): self.lost = self.ping.sent - self.ping.received self.loss = self.lost / self.ping.sent self.dmin = min(self.delays) self.dmax = max(self.delays) average = lambda x: sum(x) / len(x) # Average delay self.davg = average(self.delays) # Calculate standard deviation of the delays self.jitter = average([(d - self.davg)**2 for d in self.delays])**0.5 return """Ping statistics for {0.hostname}: Packets: Sent = {0.ping.sent}, Received = {0.ping.received}, Lost = {0.lost} ({0.loss:.2f}% loss), Approximate round trip times in milli-seconds: Minimum = {0.dmin:.2f}ms, Maximum = {0.dmax:.2f}ms Average = {0.davg:.2f}ms, Jitter = {0.jitter:.2f}ms""".format(self)