Exemplo n.º 1
0
  def _ping(self, ip_address, now):
    """Ping a device, but rate limit.

    Don't ping more often than self._ping_frequency_secs.
    """
    if self._last_ping[ip_address] + self._ping_frequency_secs > now:
      return

    pyping.ping(ip_address, timeout=1, count=1)
    self._last_ping[ip_address] = now
Exemplo n.º 2
0
def main():
	print(txtclr("Inchk 2.1 Copyright 2016 Jesse Wallace", "HEADER"))
	if options.foption != True:
                # Test 1 - Main Host
                try:
		    print("%s Testing %s ..." % (ssb.working, main_icmp_host))
		    ping_t1 = pyping.ping(main_icmp_host)
                    # Will raise unknown_host here if unsuccessful
                    print('%s Successfully reached %s!' % (ssb.success, main_icmp_host))
                    if float(ping_t1.avg_rtt) >= 110.0:
                         print('%s Average response time is abnormally high' % (ssb.warning))
                    elif float(ping_t1.avg_rtt) >= 90.0:
                         print('%s Average response time is high' % (ssb.warning))
                    synopsis([ping_t1, 'N/A', 'N/A'], [txtclr('Successful', 'OKGREEN'), 'N/A', 'N/A'], 'Good connection')
                    raise SystemExit
                except socket.error as se:
                    print(' ')
                    print('%s Socket Error: %s' % (ssb.fail, se))
                    raise SystemExit
                except (Exception, 'unknown_host'):
                    print('%s Couldn\'t reach %s ...' % (ssb.fail, main_icmp_host))

                # Test 2 - Main DNS
                try:
                    print('%s Testing %s ...' % (ssb.working, main_icmp_dns_host))
                    ping_t2 = pyping.ping(main_icmp_dns_host)
                    # Will raise unknown_host here if unsuccessful
                    print('%s Successfully reached %s!' %s (ssb.success, main_icmp_dns_host))
                    if float(ping_t2.avg_rtt) >= 110.0:
                         print('%s Average response time is abnormally high' % (ssb.warning))
                    elif float(ping_t2.avg_rtt) >= 90.0:
                         print('%s Average response time is high' % (ssb.warning))
                    synopsis([ping_t1, ping_t2, 'N/A'], [txtclr('Failed', 'FAIL'), txtclr('Successful', 'OKGREEN'), 'N/A'], 'Your DNS server is reachable but may not be serving DNS requests correctly')
                    raise SystemExit
                except (Exception, 'unknown_host'):
                    print('%s Couldn\'t reach %s ...' % (ssb.fail, main_icmp_dns_host))
                # Test 3 - Local Gateway
                try:
                    defaultgateway = get_default_gateway()
                    print('%s Testing local gateway %s ...' % (ssb.working, defaultgateway))
                    ping_t3 = pyping.ping(defaultgateway)
                    # Will raise unknown_host here if unsuccessful
                    print('%s Successfully reached local gateway %s' % (ssb.working, defaultgateway))
                    if float(ping_t3.avg_rtt) >= 15.0:
                        print('%s Average response time is abnormally high' % (ssb.warning))
                    elif float(ping_t3.avg_rtt) >= 5.0:
                        print('%s Average response time is high' % (ssb.warning))
                    synopsis([ping_t1, ping_t2, ping_t3], [txtclr('Failed', 'FAIL'), txtclr('Failed', 'FAIL'), txtclr('Successful', 'OKGREEN')], 'Your LAN is not connected to the WAN')
                    raise SystemExit
                except (Exception, 'unknown_host'):
                    print('%s Couldn\'t reach %s ...' % (ssb.fail, defaultgateway))
                synopsis(['N/A', 'N/A', 'N/A'], ['N/A', 'N/A', 'N/A'], 'You are not connected to a functional LAN')
Exemplo n.º 3
0
    def handle(self, *args, **options):

        devices = Device.objects.all()

        for device in devices:
            response = pyping.ping(device.management_ip, count=1, timeout=1000)
            if response.ret_code == 0:
                device.status = 1
            else:
                device.status = 0

            device.save()

        # loss_pat='0 received'
        # msg_pat='icmp_seq=0'
        # for device in devices:
        #     try:
        #         management_ip = device.management_ip
        #         ping = subprocess.Popen(
        #             ["ping", "-c", "1" , "-W" , "1" , management_ip],
        #             stdout = subprocess.PIPE,
        #             stderr = subprocess.PIPE
        #         )
        #         out, error = ping.communicate()
        #         for line in out.splitlines():
        #             if line.find(msg_pat)>-1:
        #                 flag=True
        #                 break
        #             else:
        #                 flag=False
        #     except TypeError:
        #         flag=False
Exemplo n.º 4
0
def main_loop():
    reboots = [None]
    fail_count = 0
    ok_count = 0
    while True:
        if pyping.ping('192.168.10.1').ret_code:
            ok_count = 0
            fail_count += 1
            print("FAIL", fail_count)
            if fail_count > 3:
                reboots.append(datetime.now().strftime("%Y-%m-%m %H:%M"))
                print("rebooting router!")
                reboot_router()
                print("rebooted router, waiting 60 seconds")
                print('reboots:', reboots)
                sleep(60)
                print("OK, back to normal")
                fail_count = 0
        else:
            fail_count = 0
            ok_count += 1
            print("seems OK, ok_count:", ok_count, 'last_reboot:', reboots[-1],
                  'of',
                  len(reboots) - 1)
        sleep(2)
Exemplo n.º 5
0
	def single(self, ns):
		self.signal()
		netns.setns(ns)

		k = ns + '_' + self.check

		while True:
			self.results[k] = { 'check': self.check, 'type': self.type, 'ns': ns, 'state': 'RUN' }
			res = self.results[k]

			try:
				r = pyping.ping(self.host, count=self.count, packet_size=self.length)

				res['max_rtt'] = r.max_rtt
				res['avg_rtt'] = r.avg_rtt
				res['min_rtt'] = r.min_rtt
				res['packet_lost'] = r.packet_lost
				res['state'] = 'OK'

				logging.info("[PING:%s] host = %s, max time = %s, avg time = %s, min time = %s, lost packets = %d" % (ns, self.host, r.max_rtt, r.avg_rtt, r.min_rtt, r.packet_lost))
			except:
				res['state'] = 'FAIL'

				logging.info("[PING:%s] Cannot ping host %s" % (ns, self.host))

			self.results[k] = res

			time.sleep(float(self.delay))
Exemplo n.º 6
0
    def check(self):
        if 'timeout' not in self.params:
            self.params['timeout'] = 500
        if 'count' not in self.params:
            self.params['count'] = 2

        self._results = {}
        try:
            r = pyping.ping(
                hostname=self.params['destination'],
                timeout=self.params['timeout'],
                count=self.params['count'],
            )

            self._results = {
                'max_rtt': r.max_rtt,
                'min_rtt': r.min_rtt,
                'avg_rtt': r.avg_rtt,
                'packet_lost': r.packet_lost,
                'output': r.output,
                'packet_size': r.packet_size,
                'timeout': r.timeout,
                'destination': r.destination,
                'destination_ip': r.destination_ip,
                'result': 255 - (r.ret_code * 255),
            }

        except:
            self.log.exception('error in pyping.ping function')
            self._results = {
                'result': 0,
            }
Exemplo n.º 7
0
def ping_one(ip, ping_count=None, su=False):
    if not ping_count:
        ping_count = 3
    r = pyping.ping(ip, count=ping_count, udp=not su)
    _, geo_ip, isp, server = loc_from_ip_cn(ip)
    return {"ip": ip, "avg_rtt": float(r.avg_rtt) if r.avg_rtt else None, "geo_ip": geo_ip, "isp": isp,
            "server": server}
Exemplo n.º 8
0
 def _do_icmp(self):
     try:
         ip = self.monitor['ip']
         timeout = self.monitor['timeout'] * 1000
         return pyping.ping(ip, timeout, count=1).ret_code == 0
     except SystemExit:
         raise Exception('unknown host: {}'.format(self.monitor['ip']))
Exemplo n.º 9
0
    def probe(self):
        self.logger.info("starting %s probe " % (type(self).__name__))

        pingResult = PingTestResult(probeName=self.probeConfig.probeName, pingStart=timezone.now(), rttStdDev=-1,
                                    packageTransmitted=-1, packageReceived=-1, sendBytesBrutto=-1)
        startTimestamp = datetime.datetime.now()
        remoteHost = self.probeConfig.host
        result = pyping.ping(timeout=(self.probeConfig.timeout * 1000), hostname=remoteHost,
                             count=self.probeConfig.packageCount, packet_size=self.probeConfig.packageSize)

        pingResult.packageToTransmit = self.probeConfig.packageCount
        pingResult.rttMin = result.min_rtt
        pingResult.rttAvg = result.avg_rtt
        pingResult.rttMax = result.max_rtt
        pingResult.packageLost = result.packet_lost
        pingResult.destinationHost = result.destination
        pingResult.destinationIp = result.destination_ip
        pingResult.sendBytesNetto = result.packet_size
        pingResult.pingEnd = timezone.now()
        timeDelta = datetime.datetime.now() - startTimestamp
        pingResult.totalTime = int(timeDelta.microseconds / 1000)
        result.interfaceIp = getLocalIp(remoteHost)

        pingResult.save()
        self.logger.info("%s probe done" % (type(self).__name__))
Exemplo n.º 10
0
    def healthcheck(self):
        r = pyping.ping(self.ip_address)
        if r.ret_code != 0:
            print("Unable to ping: {}".format(self.name))
            return False

        # TODO: Check RDP port is up
        return True
Exemplo n.º 11
0
def GetIPTTL(ip):
	p = pyping.ping(str(ip) ,count=1)
	info = p.output[1]
	print info
	if re.search(r"timed out", info, flags=0):
		pass
	else:
		return ip, re.findall(r"ttl=(\d*)", info, re.I)[0]
Exemplo n.º 12
0
def ping(host):
    probe = pyping.ping(host)
    #print ("Host IP:",probe.destination)
    config.status = probe.ret_code
    #print ("Ping results:",probe.max_rtt,"max rtt",probe.avg_rtt,"avg rtt",probe.min_rtt,"min rtt")
    data.ping_stats.results["max_rtt"] = probe.max_rtt
    data.ping_stats.results["avg_rtt"] = probe.avg_rtt
    data.ping_stats.results["min_rtt"] = probe.min_rtt
Exemplo n.º 13
0
def ping_container(container):
    r = pyping.ping(container.name, count=3, timeout=2000, quiet_output=True)
    rtt = float(r.avg_rtt) if r.avg_rtt else None
    if not rtt or rtt >= int(os.getenv("PING_THRESHOLD_MS", 0)):
        return "%s->%s: %s" % (my_container_short_uuid, node_short_uuid.search(container.node).group(1),
                               "%8.2f ms" % rtt if rtt else "%11s" % "!!!")
    else:
        return
Exemplo n.º 14
0
 def ping(self, ip_address):
     # NOTE: ping requires root access.  Fake it during development with a random#
     if hasattr(args, 'test') and args.test:
         found = (random.randint(0, 3) == 3)
     else:
         response = pyping.ping(ip_address)
         found = (response.ret_code == 0)
     return found
Exemplo n.º 15
0
def rtt(address, base):
	print "rtt"
	print address
	print base
	r = pyping.ping(address, count=1)
	print r
	store("/var/mmonet/"+base+".ping.rtt", r.min_rtt)
	store("/var/mmonet/"+base+".ping.loss", r.packet_lost)
Exemplo n.º 16
0
def ping_host(host):
    try:
        response = pyping.ping(host)
        if response.ret_code:
            return False
        return True
    except Exception as e:
        print(e)
Exemplo n.º 17
0
def GetIPTTL(ip):
    p = pyping.ping(str(ip), count=1)
    info = p.output[1]
    print info
    if re.search(r"timed out", info, flags=0):
        pass
    else:
        return ip, re.findall(r"ttl=(\d*)", info, re.I)[0]
Exemplo n.º 18
0
def py_ping(HN):
    GCDT = gcdt()
    r = pyping.ping(HN)
    if r.avg_rtt == "None":
        print("[{}] This Host doesn't exist".format(GCDT))
    else:
        print("[{}] Avg. Round Trip Time={} ms from here to {}".format(
            GCDT, r.avg_rtt, HN))
Exemplo n.º 19
0
def ping_checker(args):
    Msg = ""
    for arg in args:
        r = ping(arg, count=1, timeout=3000, udp=False)
        Msg += str(
            datetime.now()) + "\tPING\t" + arg + "\t" + "Pktloss:" + str(
                r.packet_lost) + "\t" + "RTT:" + str(r.avg_rtt)
        Msg += "\n"
    return Msg
Exemplo n.º 20
0
 def __init__(self, host=None, count=3, timeout=2):
     self.host = host
     self.count = count
     self.timeout = timeout
     self.ping = ping(self.host, self.count, self.timeout)
     if self.ping.ret_code == 0:
         self.alive = True
     else:
         self.alive = False
Exemplo n.º 21
0
def get_local_presence_data(location_name, presence_name):
    ip = ''
    if presence_name == 'Nico':
        ip = "192.168.0.77"
    if presence_name == 'Flor':
        ip = "192.168.0.31"
    response = pyping.ping(ip)
    logging.debug (presence_name + ' ' + str(response.ret_code))
    return (response.ret_code == 0); #0 = reachable, other is unreachable
Exemplo n.º 22
0
def internet_on():

    r = pyping.ping('4.2.2.2')
    if r.ret_code == 0:
        print("Still Holding")
        return True
    else:
        print("Down goes Frazier")
        return False
Exemplo n.º 23
0
def ping(address):
    try:
        r = pyping.ping(address)
    except:
        email_error('Pinging Server')
        log_event('Exception Pinging Server')
        die()

    return not r.ret_code
Exemplo n.º 24
0
def get_target_status(target):
    try:
        r = pyping.ping(target)
        if r.ret_code == 0:
            return True
        else:
            return False
    except:
        return False
Exemplo n.º 25
0
def ip_scan(ip):
    try:
        #IP가 살아있는지 확인하자.
        if not pyping.ping(str(ip)).ret_code:
            threadLock.acquire()
            print("Alive Host : {}".format(ip))
            threadLock.release()
    except:
        pass
Exemplo n.º 26
0
def isIpBack(strIp):
    trace('\n[PcCtrl] --- try to ping ip: ' + strIp + '.')
    response = pyping.ping(strIp)
    if response.ret_code == 0:
        trace('\n[PcCtrl] --- ping result: pass.')
        return True
    else:
        trace('\n[PcCtrl] --- ping result: fail.')
        return False
Exemplo n.º 27
0
def IcmpMonitor(ImIp):  # tcp请求的函数 返回最大rtt值
    try:
        Im_MaxRtt = str(pyping.ping(ImIp).max_rtt)
        if Im_MaxRtt == 'timeout':
            return 0
        else:
            return Im_MaxRtt
    except:
        return 'timeout'
Exemplo n.º 28
0
def ping(address):
    try:
        r = pyping.ping(address)
    except:
        email_error('Pinging Server')
        log_event('Exception Pinging Server')
        die()

    return not r.ret_code
Exemplo n.º 29
0
def can_ping_node(ip_addr):
    """
    :ip_addr: Str
    :return: Bool
    """
    r = pyping.ping(ip_addr)
    if r.ret_code == 0:
        return True
    return False
Exemplo n.º 30
0
 def ping(self, bot, update, args):
     if not update.message.chat_id in validuser:
         return
     host = args[0]
     r = pyping.ping(host)
     if r.ret_code == 0:
         msg = ("{} Success".format(host))
     else:
         msg = "{} Failed with {}".format(host, r.ret_code)
     bot.send_message(chat_id=update.message.chat_id, text=msg)
Exemplo n.º 31
0
    def ping(self, host):
        """
        Returns True if host (str) responds to a ping request.
        Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
        """
        success = False
        ip_address = ''
        message = ''
        if HAVE_PING:
            try:
                result = pyping.ping(self.server.get(
                ))  # Need to be root or Administrator in Windows
                ip_address = result.destination_ip
                if result.ret_code != 0:
                    message = 'Could not ping server %s(%s)' % (
                        self.server.get(), result.destination_ip)
                else:
                    message = 'Min = %sms, Max = %sms, Average = %sms' % (
                        result.min_rtt, result.max_rtt, result.avg_rtt)
                    success = True
            except Exception as e:
                message = 'Error: %s' % e
            self.print('Ping: %s' % message)
        else:
            # Ping command count option as function of OS
            param = '-n 1' if system_name().lower() == 'windows' else '-c 1'

            # Building the command. Ex: "ping -c 1 google.com"
            command = 'ping %s %s' % (param, host)

            self.print('Ping command: %s' % command)

            # Pinging
            p = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
            while True:
                result = p.stdout.readline()
                self.print('ping: %s' % result)
                if result == '':
                    break
                else:
                    if 'avg' in result.lower() or 'average' in result.lower():
                        message = result.replace('imum', '').strip()
                        success = True
                    if 'unreachable' in result.lower():
                        break
                    if 'not' in result.lower():
                        break
                    if 'from' in result.lower():
                        ip_address = re.findall(
                            '([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', result)[0]
                        self.print('remote ip is: %s' % ip_address)

            p.terminate()

        return success, message, ip_address
Exemplo n.º 32
0
def working_fine(url, num):
    IP = "NONE"
    LOCAL_PROXY_PATH = "./lp/"
    if int(num) % 2 == 0:
        LOCAL_PROXY_PATH = "./lp_compression/"
    CGN_NODE_LIST_PATH = LOCAL_PROXY_PATH + "intermediate_nodes.list"
    with open(CGN_NODE_LIST_PATH) as f:
        for line in f:
            #print line
            if ":5555" in line:
                IP = line.split('=')[1].split(':')[0].strip()
                break
    rtn = False

    if IP == "NONE":
        return False

    with open("url_rtt_data.txt", 'w') as f:
        r = ping(IP)

        if r.ret_code == 0:
            rtn = True
            f.write(r.avg_rtt + '\n')

        if "http://" in url:
            url = url.strip()[7:]
        if "/" in url:
            url = url.split('/')[0].strip()

        r = ping(url)

        if r.ret_code == 0:
            f.write(r.avg_rtt + '\n')
            f.write(r.destination_ip + '\n')
            rtn = True

        r = ping('google.com')

        if r.ret_code == 0:
            rtn = True

    return rtn
Exemplo n.º 33
0
def func_ping(Ping_server):
    ping_hostname = Ping_server
    timeoutput_start = '%sZ' % datetime.datetime.utcnow().isoformat()
    p = pyping.ping(ping_hostname)
    timeoutput_finish = '%sZ' % datetime.datetime.utcnow().isoformat()
    if p.ret_code == 0:
        ping_status = "Online"
    else:
        ping_status = "Offline"
    output_csv = timeoutput_start + ',' + timeoutput_finish + ',' + p.destination + ',' + p.min_rtt + ',' + p.avg_rtt + ',' + p.max_rtt + ',' + str(p.packet_lost) + ',' + p.destination_ip + ',' + ping_status
    return output_csv
Exemplo n.º 34
0
def checkGW():
    # checks the computer's default gateway and check connection

    gateways = netifaces.gateways()
    default_gateway = gateways['default'][netifaces.AF_INET][0]
    response = pyping.ping(default_gateway)
    if response.ret_code == 0:
        print "Default GW ->", default_gateway
        print "Ping to GW -> OK"
    else:
        print "Ping to GW -> ERROR"
Exemplo n.º 35
0
async def ping(ctx):
    """Pings the bot"""
    #pingtime = time.monotonic()
    #pingms = await ctx.send("Pinging...")
    #ping = time.monotonic() - pingtime
    #await pingms.edit(content="The ping time is `{%.ms`" % ping)
    pingms = await ctx.send("Pinging...")
    # await bot.edit_message(pingms, topkek + " // ***{} ms***".format(str(ping)[3:][:3]))
    await pingms.edit(content="{} // **{} ms**".format(
        pingms.content,
        pyping.ping("creeperseth.com").avg_rtt))
Exemplo n.º 36
0
def Ping_Address_List():
    pingCounter = 0
    print "Pinging each address to verify its up."
    for address in ipList:
        pingresponse = pyping.ping(address)
        if pingresponse.ret_code == 0:
            pingCounter = pingCounter + 1
            print address
        else:
            pass
    print "Total results {}".format(len(ipList))
    print "Total alive results: {}".format(pingCounter)
Exemplo n.º 37
0
 def doPingAsyncTask(self, task):
     host = task["Host"]
     try:
         p = pyping.ping(host, count=task["PingCount"])
         print "Ping..." + host
         return [
             True, task, p.avg_rtt, p.min_rtt, p.max_rtt, p.packet_lost,
             p.destination_ip
         ]
     except:
         print "Ping..." + host + "...Err"
         return [False, task]
Exemplo n.º 38
0
def main():
    # 1번 문제
    nowTime = datetime.now()
    str_now = nowTime.strftime('%Y-%m-%d %H:%M:%S')
    LOG.debug('Start Healthcheck at (%s)', str_now)
    dest_url = 'google.com'
    LOG.debug('Desination URL : %s', dest_url)
    res = pyping.ping(dest_url)
    if not res.ret_code:
        LOG.debug("Success")
    elif res.ret_code:
        LOG.warning("Connection Failed")
Exemplo n.º 39
0
def ping(host):
    print "Sending ping"

    response = pyping.ping(host)
    print "\n---------------------------------"
    
    if response.ret_code == 0:
        print "ping       -> OK"
        return True
    else:
        print "ping       -> ERROR"
        return False
Exemplo n.º 40
0
def ping(ip, own_id=None):

    cprint('[-] Pinging %s' % ip, 'yellow')
    r = pyping.ping(ip, own_id)
    print(ip + "\t" + str(r.ret_code) + "\t" + own_id)
    if (r.ret_code == 0):
        lock.acquire()
        cprint("%s is live" % r.destination_ip, 'green')
        global live
        live.append(ip)
        lock.release()
    return
Exemplo n.º 41
0
def findMachines():
    for n in range(1,30):
        for machine in machines[:]:
            print("searching for "+ machine + " in team" + str(n))
            machineName = machine + ".team" + str(n) + ".isucdc.com"
            print machineName
            response = pyping.ping(machineName)
            if response.ret_code == 0:
                print("reachable")
                tryDefaultCreds(machineName)
            else:
                print("unreachable")
Exemplo n.º 42
0
 def ping(self, bot, update, args):
     if not str(update.message.chat_id) in validuser:
         self.logger.info('Not valid user {}'.format(
             update.message.chat_id))
         return
     host = args[0]
     r = pyping.ping(host)
     if r.ret_code == 0:
         msg = ("{} Success".format(host))
     else:
         msg = "{} Failed with {}".format(host, r.ret_code)
     bot.send_message(chat_id=update.message.chat_id, text=msg)
Exemplo n.º 43
0
 def run(self):
     global active_hosts
     global inactive_hosts
     while True:
         self.ip_address = self.queue.get()
         pinging = pyping.ping(self.ip_address, timeout=self.timeout, count=self.count)
         logging.info('Pinging {0} ... status={1}'.format(self.ip_address, pinging.ret_code))
         if pinging.ret_code == 1:
             inactive_hosts.append(self.ip_address)
         else:
             active_hosts.append(self.ip_address)
         self.queue.task_done()
Exemplo n.º 44
0
def catch_all(region):
    ip = request.form['ip']
    if request.method == 'POST':
        r = pyping.ping(ip)
        result = "REGION: " + region + "<br />"
        for i, item in enumerate(r.output):
            result+=item + "<br />"
        #result = r.output
        #aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
        #result = "\n".join(r.output)
        print result
        return result
Exemplo n.º 45
0
def ping(ip):
    # Packet size must be 0, otherwise timeout rate may rise significantly
    try:
        result = pyping.ping(
            ip, count=1, timeout=config.PING_TIMEOUT * 1000,
            packet_size=0, own_id=random.randrange(0xffff),
        )
        rtt = float(result.avg_rtt) / 1000 if result.avg_rtt else None
    except ZeroDivisionError:
        rtt = None

    logging.debug("Ping: %s, %s", ip, rtt if rtt else "timeout")
    return rtt
Exemplo n.º 46
0
def pingscan():
    """
    对目标进行ping扫描, 并做时长统计. 上下线会发出提醒.
    """
    t_start = time.time()
#    print('t_start is:', t_start)
    while True :
        try:
            p = pyping.ping('10.1.1.1', timeout=3000, count=4)
        except Exception as e:
            print(e)
        if p.avg_rtt:
            time.sleep(7)
            t_stop = time.time()

            global today
            today = datetime.datetime.today().strftime('%Y-%m-%d')
            if mark['count'] == 0:
#                print('已开机')
#                alarm('began')
                markdb('mark_start')
            mark['online'] += (t_stop - t_start)
#            print('mark.online is:', mark['online'])
            if mark['closed'] > 0:
                alarm('began')
                print('已开机')
                mark['closed'] = 0
            if mark['online'] > 606:#若online在线超过10分钟,在DB中标记最新时间戳.
                 markdb('cycle_mark')
                 mark['online'] = 6

            mark['count'] += (t_stop - t_start)
 #           print('mark.count is:', mark['count'])
            t_start = t_stop
            alarm()
 #           print('+1count=',mark['count'],'online=',mark['online'],'close=',mark['closed'])
        else:
            time.sleep(10)
            t_stop = time.time()
            if mark['closed'] == 0:
                alarm('closed')
                print('已关机')
            mark['closed'] += (t_stop - t_start)
            t_start = t_stop
        if mark['closed'] > 300 and mark['online'] != 0:#可加 and count > 10分钟
            mark['online'] = 0
            writedb()
            mark['count'] = 0
            print('Wrote DB and set count to 0 successfully')
Exemplo n.º 47
0
  def ping_subnet(self, now):
    """Ping broadcase address for all interfaces."""
    if self._last_ping['SUBNET'] + self._ping_frequency_secs > now:
      return

    self._last_ping['SUBNET'] = now

    for interface in netifaces.interfaces():
      if interface.startswith('lo'):
        continue

      details = netifaces.ifaddresses(interface)
      if netifaces.AF_INET not in details:
        continue

      for detail in details[netifaces.AF_INET]:
        address = detail.get('addr', None)
        netmask = detail.get('netmask', None)
        if address is None or netmask is None:
          continue

        parsed = ipaddr.IPv4Network('%s/%s' % (address, netmask))
        logging.debug('Ping broadcast address %s', parsed.broadcast)
        pyping.ping(str(parsed.broadcast), timeout=10, count=10)
Exemplo n.º 48
0
def ping_test(ping_address):
    try:
        r = pyping.ping(ping_address)
        ping_result = r.ret_code == 0
        avg_rtt = r.avg_rtt
        min_rtt = r.min_rtt
        max_rtt = r.max_rtt
        destination_ip = r.destination_ip
    except:
        traceback.print_exc()
        ping_result = False
        avg_rtt = 0
        min_rtt = 0
        max_rtt = 0
        destination_ip = ''
    return ping_result, avg_rtt, min_rtt, max_rtt, destination_ip
Exemplo n.º 49
0
def get_site_info(site):
	s = pyping.ping(site, udp = False)
	print ("ho\n");
	#sInfo = ''
	if(s.ret_code == 0):#DEU BOM
		
		sInfo = '<h3>CONNECTION SUCCESS: </h3>' + str(s.destination)
		sInfo = sInfo + '<br>IP: ' + str(s.destination_ip)
		sInfo = sInfo + '<br>PACKETS LOST: ' + str(s.packet_lost) 
		sInfo = sInfo + '<br>MINIMUM ROUND TRIP TIME (in ms): ' + str(s.min_rtt)
		sInfo = sInfo + '<br>AVERAGE ROUND TRIP TIME (in ms): ' + str(s.avg_rtt)
		sInfo = sInfo + '<br>MAXIMUM ROUND TRIP TIME (in ms): ' + str(s.max_rtt)
		sInfo = sInfo + '<br>';
		pass
	else:
		sInfo = '<h3> CONNECTION FAILED </h3>' + site
	return sInfo
	pass
 def run(self):
   for dest in self._ips:
     """
     For each ip, make an aggregate of all packet responses and then send the
     aggregate to the pipe.
     """
     packets_sent = 0
     reply_data = ReplyData()
     while packets_sent < self.req_data.packet_count:
       r = pyping.ping(dest, count=1, packet_size=self.req_data.buf_size,
                       timeout=self.req_data.timeout)
       reply_data = reply_data + ReplyData(r.destination_ip, r.packet_size, r.avg_rtt, r.packet_lost)
       #now figure out how to send this response to the caller thread
       packets_sent += 1
       time.sleep(self.getDelay(self.req_data))
     self.reply_pipe.send(reply_data)
     #send a reply that indicates we are finished
     finish_reply = ReplyData(finalReply=True)
   self.reply_pipe.send(finish_reply)
Exemplo n.º 51
0
def _ping(address, dump, irange=255):
    with open(dump+'.csv', 'w') as csvfile:
        felten = ['IP', 'state']
        write = csv.DictWriter(csvfile, fieldnames=felten)
        write.writeheader()
        tot = tz.time()
    
        for j in xrange(1, irange):
                start = tz.time()
                clean =  address.split(".")
                loot = "{}.{}.{}.{}".format(clean[0], clean[1], clean[2], j)
                ping = pyping.ping(loot, timeout=3, count=2)
    
                if ping.ret_code == 0:
                    write.writerow({'IP': loot, 'state':"Online"})
                    print ping.destination
            
                else:
                    pass
    
    print "Total",  tz.time() - tot,  "seconds"
Exemplo n.º 52
0
def run_pyping_check(state):
    try:
        H = pyping.ping(host)
    except:             # If there's an error, print error msg and mark as down.
        time_log()
        print("{} : {} - Error Connecting.") .format(ts, host)
        state = "DOWN"
        return state
    if H.ret_code == 1:      # If the ping FAILS
        if state == "UP":    # and host was previously UP
            time_log()       # grab a timestamp and print message.
            print("{} : {} is now down. ({})") .format(ts, host, td)
            state = "DOWN"
    elif H.ret_code == 0:    # If the ping RESPONDS
        if state == "DOWN":  # and host was previously DOWN
            time_log()       # grab a timestamp and print message.
            print("{} : {} is now up. ({})") .format(ts, host, td)
            state = "UP"
    else:  # if something tragic happens, just leave.
        print("ERROR: Exiting...")
        exit()
    return state
Exemplo n.º 53
0
def ping_ip_address(time_aut_ping,ip_address_ping): 
    print ""
    sys.stdout.write("START PING IP ADDRESS:"+ip_address_ping+"   ")    
    i=0
    ping_ok=1
    while ping_ok==1:
        ping_ip=pyping.ping(ip_address_ping,count=2)
        ping_ok=ping_ip.ret_code
        if i < time_aut_ping:
            if i==0:
                sys.stdout.write("ping ") 
            else:
                sys.stdout.write(".") 
            i=i+1 
        else:
            sys.stdout.write("WAIT "+str(i)+", PING IP ADDRESS STOP :")
            break                      
    if ping_ok==0:
        sys.stdout.write("      IP ADRESS:"+ip_address_ping+" AVALIBLE")
        return 1            
    else:
        sys.stdout.write("      IP ADRESS:"+ip_address_ping+" IS'T AVALIBLE")              
        return  0
Exemplo n.º 54
0
def w_r():
    conn1 = sqlite3.connect('ex.db')
    c1 = conn1.cursor()
    for row in rows:
		t = int(time.time())
		s_t = str(t)
		r = pyping.ping(row[1], count=1)
        #     print row[0] + "=>" + r.avg_rtt
		c1.execute("INSERT INTO result (r_name, r_delay) VALUES (?, ?)", (row[0], r.avg_rtt))
		if r.avg_rtt == None:
			s_delay = '0'
		else:
			s_delay = str(r.avg_rtt)
		data_source = 'DS:delay:GAUGE:2:0:' + s_delay
		rrdtool.create( 'delay.rrd',
						'--start', s_t,
						data_source,
						'RRA:AVERAGE:0.5:1:60')
		conn1.commit()
		SECOND = 60
		MINUTE = 60 * SECOND
		path = '/tmp/delay.png'
		rrdtool.graph(path,
						'--imgformat', 'PNG',
						'--width', '540',
						'--height', '100',
						'--start', s_t,
						'--end', "+1",
						'--vertical-label', 'delay/Day',
						'--title', 'Annual delay',
						'--lower-limit', '0',
						'DEF:response=delay.rrd:delay:AVERAGE',
						'LINE:response#990033')
		info = rrdtool.info('delay.rrd')
		print info['last_update']
		print info['ds[delay].minimal_heartbeat']
    conn1.close()
import requests
import time
import threading
import pyping
from termcolor import colored

r = pyping.ping('google.com')
speed = r.avg_rtt

if round(float(speed)) > 60:
    print"\n\nNetwork speed not optimal for accurate tests! " + str(speed) + "ms!\n\n"
    exit(0)
else:
    print"\n\nNetwork test passed! " + str(speed) + "ms!\n\n"

log = time.strftime("%m-%d-%Y") + time.strftime(" %I:%M:%S")

def scan(url):
    url = url.rstrip('\n')
    #Check the response time 3 times in a row for accurate data
    for y in range(0, 3):
        try:
            response = requests.get(url)
            x = response.elapsed
            if x.seconds > 1:
                #If the site fails the check then print to the console and write to the log file
                print colored("*WARNING*  " + str(line) + " response was " + str(x) + " with status code " + str(response.status_code) + "; Count: " + str(y), "red") 
                f2.write(str(line) + " - *WARNING*  Response time: " + str(response.elapsed) + " with status code " + str(response.status_code) + "; Count: " + str(y) + "\n\n")
                exit(0)
            else:
                #If the site passes the check then just write to the file
Exemplo n.º 56
0
import pyping
import datetime


print datetime.datetime.now() 

hostname = "mymusictaste.com"

response = pyping.ping(hostname,count=100)


packet_lost = response.packet_lost
min_rtt = response.min_rtt
avg_rtt = response.avg_rtt
max_rtt = response.max_rtt
ip_info = response.destination_ip
ret_code = response.ret_code
packet_size = response.packet_size
timeout = response.timeout
destination = response.destination

print "Packet Lost : " , packet_lost
print "Min Rtt : " , min_rtt
print "Max Rtt : " , max_rtt
print "Avg Rtt : " , avg_rtt
print "ret_code : ", ret_code
print "packet_size : " , packet_size
print "timeout : " , timeout
print "destination : " , destination

if packet_lost > 50:
Exemplo n.º 57
0
 def __init__(self, parent):
     self.ping = float(
         ping(hostname=parent.host,
         timeout=2000,
         count=1).avg_rtt
     )
Exemplo n.º 58
0
def is_online():
  write('Testing connectivity')
  for _ in range(10):
    if pyping.ping('8.8.8.8', timeout = 5000, count = 1, udp = True).ret_code == 0:
      return True
  return False
Exemplo n.º 59
0
import base64, hashlib, socket, pyping, os, getpass, time, psutil, log, sqlite3, keys
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from simplecrypt import decrypt

app_log = log.log("arches.log")

(key, private_key_readable, public_key_readable, public_key_hashed, address) = keys.read()

timestamp = str(time.time())

r = pyping.ping('google.com')                # Need to be root or

openfield = "Arches:" + socket.gethostname(), psutil.virtual_memory(), psutil.cpu_times(), r.ret_code, r.destination, r.max_rtt, r.avg_rtt, r.min_rtt, r.destination_ip
print openfield

transaction = (timestamp, address, address, '%.8f' % 0, 0, str(openfield))  # this is signed
print transaction

h = SHA.new(str(transaction))
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
signature_enc = base64.b64encode(signature)
#app_log.info("Client: Encoded Signature: " + str(signature_enc))

mempool = sqlite3.connect('mempool.db')
mempool.text_factory = str
m = mempool.cursor()

m.execute("INSERT INTO transactions VALUES (?,?,?,?,?,?,?,?)", (timestamp, address, address, '%.8f' % 0, signature_enc, public_key_hashed, "0", str(openfield)))
Exemplo n.º 60
0
def check_ip(ip_addr):
    r = pyping.ping(ip_addr)
    return r.ret_code