Exemplo n.º 1
0
    def ping(self, host, count=3):
        """ping <host> <count> times"""
        from ping import Ping
        result = dict()
        # Инициализация класса
        try:
            ping = Ping(host = host)
            ping.count = count

            (retcode, out) = ping.ping_host()
            cmd_result = out.split("\n")
            if retcode == 0:
                pinged = True
            else:
                pinged = False

            out = list()
            for s in cmd_result:
                out.append((s, ))

            result['status'] = True
            result['result'] = pinged
            result['data'] = out
        except Exception as e:
            result['status'] = False
            result['data'] = (('error:', e.message), )
            return result

        return result
Exemplo n.º 2
0
 def run(self):
     gateway, iface = setDefaultGatewayAndInterface()
     parts = gateway.split('.')
     network = parts[0]+'.'+parts[1]+'.'+parts[2]+'.'
     newPing = Ping(network)
     hostsAndStatus = newPing.findHosts()
     for hosts in hostsAndStatus:
         if hosts[1] == 'Alive':
             if hosts[0] not in self.pwndHosts:
                 self.queue.put('Found a new victim at ' + hosts[0])
                 newArpSpoofThread = arpSpoof(hosts[0])
                 newArpSpoofThread.start()
                 self.threadList.append(newArpSpoofThread)
                 self.pwndHosts.append(hosts[0])
                 self.queue.put('Now ARP spoofing ' + hosts[0])
             else:
                 self.queue.put('Tried to re-ARP spoof ' + hosts[0])
         elif hosts[1] == 'Dead':
             self.queue.put('Host at ' + hosts[0] + ' is now offline.')
             for threads in self.threadList:
                 if threads.victim == hosts[0]:
                     threads.stop()
                     self.pwndHosts.remove(hosts[0])
                     self.threadList.remove(threads)
                     self.queue.put('Stopped ARP spoofing ' + hosts[0])
Exemplo n.º 3
0
def get_ping(address):
    p = Ping(destination=address)
    sum = 0
    for _ in range(0, 10):
        sum += p.do()
    mean = sum / 10.0
    return mean
Exemplo n.º 4
0
def main():
    showDeviceInfo()
    p = Ping('0.0.0.0', '0.0.0.0')
    currentSocket = p.get_socket()
    buffer = []
    print(uploadedFiles)
    while (True):

        updateBattery()
        inputs, output, exception = select.select([currentSocket, sys.stdin],
                                                  [currentSocket], [])
        for i in inputs:
            if i == currentSocket:
                receiverFunction(p)
            elif i == sys.stdin:
                x = raw_input()
                buffer.append(x)
        if currentSocket in output:
            for i in range(len(buffer)):
                if buffer[i] == "u":
                    senderFunction(p, 'help.txt')
                elif buffer[i] == "help":
                    downloadFunction(p, 'help.txt')
                elif buffer[i] == "showInfo":
                    showDeviceInfo()
                elif buffer[i] == "showUfiles":
                    showUploadedFiles()
                elif buffer[i] == "showDfiles":
                    showDownloadedFiles()
                else:
                    print("Commmand not found! try again.")
            buffer = []
Exemplo n.º 5
0
def testICMP(config):

    db = Database(config)
    alert = Alert(db, config)
    ping = Ping()
    ping.thread_count = int(config.get('Config', 'config.numthreads'))

    while True:

        logger.info("Start test ICMP: %s" % time.ctime())

        #Get hots
        hosts = list(db.getHostsActive())
        if hosts:
            #test hosts
            tests = list(ping.start(list(hosts)))
            #Process old alerts with new alerts and send messages
            alert.procAlerts(tests)
        else:
            #Check if exist alerts when database is empty. If exist, clean all.
            flag, alerts = db.getAlert()
            if flag:
                for alert in alerts:
                    flag, result = self.db.delAlert(alert[0])
                    if not flag:
                        self.logger.info(
                            'I could not delete alerts %s, error %s' %
                            (str(alert[0]), result))
            else:
                self.logger.info('I could not get alerts: %s' % (alerts))

        #Uncomment to sleep a while
        #time.sleep( 30 )
        logger.info("End test ICMP: %s" % time.ctime())
Exemplo n.º 6
0
def send():
	sourceIp = findRandomIp()
	destinationIp = findRandomIp()
	while destinationIp == sourceIp:
		 destinationIp = findRandomIp()
	print "from %s to %s" % (sourceIp, destinationIp)
        Server = Ping(sourceIp , destinationIp)
        Server.do_send()
Exemplo n.º 7
0
 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'
Exemplo n.º 8
0
 def sendone(self, sendme):
     p = Ping(self.server)
     d = datetime.datetime.fromtimestamp(sendme.scanDate)
     beaconNumber = sendme.major
     if beaconNumber not in self.beacons:
         self.beacons[beaconNumber] = Beacon(beaconNumber, self.server)
     beaconId = self.beacons[beaconNumber].id
     p.ping(d, beaconId, sendme.tx, self.chronoId)
     self.logger.info('[SYNC] Ping sent : ' + str(sendme))
Exemplo n.º 9
0
def ping_rs(world: str, game: str):
    """
    Pings a list of runescape worlds

    Args:
        worlds: list of world numbers, i.e. [1, 2, 3]
        game: prefix for osrs/rs3: 'oldschool' or 'world' 
    """
    uri = "{}{}.runescape.com".format(game, world)
    cmd = Ping(platform.system(), uri, count='1')
    return (uri, cmd.average(cmd.send()))
Exemplo n.º 10
0
    def test_address_unreachable(self):
        mx = mox.Mox()
        http_client = mx.CreateMock(httplib2.Http)
        http_client.request('http://www.enderecoquenaoexiste.com', 'GET').AndRaise(httplib2.ServerNotFoundError)
        mx.ReplayAll()

        ping = Ping()
        self.assertFalse(ping.isReachable("http://www.enderecoquenaoexiste.com", http_client))

        mx.UnsetStubs()
        mx.VerifyAll()
Exemplo n.º 11
0
    def ip_file(self):
        A=Input()
	lock=threading.Lock()
	outqueue=Queue.Queue()
	if A.Input_file():
            for i in range(A.number):
	        B=Ping(A.queue,lock)
	        B.start()
            A.queue.join()
        else:
	   pass
Exemplo n.º 12
0
    def test_address_reachable(self):
        mx = mox.Mox()
        http_client = mx.CreateMock(httplib2.Http)
        http_client.request('http://globo.com', 'GET').AndReturn(({'status':'200'},'Mock Response'))
        mx.ReplayAll()

        ping = Ping()
        self.assertTrue(ping.isReachable("http://globo.com", http_client))

        mx.UnsetStubs()
        mx.VerifyAll()
Exemplo n.º 13
0
 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()
Exemplo n.º 14
0
	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
Exemplo n.º 15
0
    def test_fail_ftp_sunet(self):
        pinga = Ping('ftp.sunet.com')

        print pinga.get_ttl()
        self.assertTrue(self.reply_match("0", pinga.get_ttl()))

        pinga.get_response()
        self.assertTrue(
            self.reply_match("\d{1,3}.\d{1,3}", pinga.get_response()))

        self.assertTrue(
            self.reply_match("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}",
                             pinga.get_time()))

        self.assertTrue(self.reply_match("\w+.\w+", pinga.get_dest()))
Exemplo n.º 16
0
    def __init__(self, addresses, latest=False):
        """Create a PingTest object.

        Arguments:
            addresses: A list of strings containing the addresses to ping.
            latest: A boolean of whether to disregard older ping results.
        """
        self.addresses = list(addresses)
        self.__times = []
        self.__pings = []
        self.responses = []
        for address in addresses:
            ping = Ping(address)
            self.__pings.append(ping)
            self.__times.append(ping.ping(latest=latest))
            self.responses.append([])
Exemplo n.º 17
0
    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
Exemplo n.º 18
0
def ping():
    transport = TSocket.TSocket('127.0.0.1', 9099)
    tranport = TTransport.TFramedTransport(transport)
    protocol = TCompactProtocol.TCompactProtocol(tranport)
    client = Ping.Client(protocol)
    tranport.open()
    client.ping()
    tranport.close()
Exemplo n.º 19
0
class Pinger(threading.Thread):
    pingerCount = 0  
    error_occurred = False

    def __init__(self, session, vm, ip): 
        lock = threading.Lock()
        with lock: 
            threading.Thread.__init__(self)
            Pinger.pingerCount = Pinger.pingerCount + 1                 #pinger count - also used in VM unique has algorithm
         
            self.__stopPings = 0;                                       #stop pings toggle
            self.__session = session                                    #save session
            self.__VM = vm                                              #save vm being monitored
            self._id = (get_ident() ^ os.getpid()) + Pinger.pingerCount #create a unique hash for the VM - needed for ICMP pings

            self.__ip = ip                                              #save ip 
            self.__missedPings = 0                                      #number of missed pings
            self.__pingObj = Ping(ip, 1000, 55, self._id)               #create Ping object
            self.__snapped = 0                                          #toggle for if snapshot has already occurred
            self.misses = 2                                             #number of missed pings allowed
       
                  
    #stop pinging
    def stop(self):
        lock = threading.Lock()
        with lock: 
            self.__stopPings = 1            
                
            
    #ping function - starts the Ping object thread which starts pinging the VM and reporting results
    def ping(self): 
        lock = threading.Lock()
        with lock:  
            i = 0
            #keep pinging until told to stop or snapshot gets created due to missing pings
            while(self.__stopPings == 0 and self.snapped == 0):
                #get missed pings- hopefully 0
                self.__missedPings = self.__pingObj.run(self.misses) 
                time.sleep(5) #wait 5 seconds - let's not go overboard
                i = i + 1
                
                #if threshold for missed pings is hit, create a snapshot
                if self.__missedPings == self.misses:
                    if self.snapped == 0:
                        self.__session.xenapi.Async.VM.snapshot(self.__VM, "Network_Down") # create a snapshot
                        self.snapped = 1
                                       

    #initialize variables for thread object
    def run(self): 
        lock = threading.Lock()
        with lock:  
            self.__stopPings = 0
            self.__missedPings = 0
            self.snapped = 0
        
            self.ping() #start pingign
Exemplo n.º 20
0
def make_ping_object(h, ping_id):
    timeout = min(500, 1000.0 / PING_FREQUENCY if PING_FREQUENCY else 500)
    max_sleep = int(1000.0 / PING_FREQUENCY)
    if not is_valid_ip4_address(h):
        try:
            h = socket.gethostbyname(h)
        except:
            return False
    # print "ping_id = {}\n".format(ping_id)
    return Ping(h, timeout, own_id=ping_id, max_sleep=max_sleep)
Exemplo n.º 21
0
    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()
Exemplo n.º 22
0
 async def serverping(self, ctx, server):
     """Ping a server or an IP. \n\n**Pinging a specific port will not work. This is due to restrictions with the lib.**"""
     ping = Ping(server)
     embed = discord.Embed(title=f"Pinged {server}!")
     embed.add_field(
         name=f"Server returned {ping.avg}!",
         value=f"It returned {ping.returncode} error(s)!",
         inline=False,
     )
     embed.set_footer(text=f"I pinged {server}")
     await ctx.send(embed=embed)
Exemplo n.º 23
0
def update_cache(session_key=None):
    global dateLastUpdated
    try:
        appsMeta = Ping.ping(session_key)
        if appsMeta['dateLastUpdated'] > dateLastUpdated:
            logger.debug("cachedateLastUpdated:: %d" % dateLastUpdated)
            logger.debug("appsDateLastUpdated:: %d" % appsMeta['dateLastUpdated'])
            init_capture_ip_addresses(session_key)
            dateLastUpdated = appsMeta['dateLastUpdated']
    except Exception as e:
        # Exception happens as appsMeta file is in the process of getting written to.
        # Do Nothing and return existing cache.
        logger.exception(e)
Exemplo n.º 24
0
def init_streamfwdauth(sessionKey=None):
    global dateLastUpdated
    try:
        pingData = Ping.ping(sessionKey)
        if pingData['dateLastUpdated'] > dateLastUpdated:
            logger.debug("cacheDateLastUpdated:: %d" % dateLastUpdated)
            logger.debug("appsDateLastUpdated:: %d" %
                         pingData['dateLastUpdated'])
            dateLastUpdated = pingData['dateLastUpdated']
    except Exception as e:
        # Exception happens as appsMeta file is in the process of getting written to.
        # Do Nothing and return existing cache.
        logger.exception(e)
Exemplo n.º 25
0
def main():
    log = logging.getLogger("main")

    # parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--ping-manager-port",
                        required=False,
                        default="18888",
                        help="port number for ping")

    arguments = parser.parse_args()

    # setup application
    log.debug("setup application")
    ping_instance = Ping()
    ping_application_arguments = {'ping_instance': ping_instance}
    ping_application = tornado.web.Application([
        (r"/api/v1/ping/stats", PingStatsHandler, ping_application_arguments),
        (r"/api/v1/ping/adminstatus/([a-z]+)", PingAdminStatusHandler,
         ping_application_arguments),
        (r"/api/v1/ping/server/?([0-9a-z\.]*)", PingServerHandler,
         ping_application_arguments),
        (r"/api/v1/ping/rate/?([0-9]*)", PingRateHandler,
         ping_application_arguments),
        (r"/version", VersionHandler, ping_application_arguments)
    ])
    ping_server = tornado.httpserver.HTTPServer(ping_application)

    # setup SIGINT handler
    log.debug("setup SIGINT handler")

    def signal_handler(signal, frame):
        print("")  # print newline to clear user input
        log.info("Exiting")
        ping_instance.stop()
        ping_server.stop()
        log.info("Sayonara!")
        quit()

    signal.signal(signal.SIGINT, signal_handler)

    # start
    log.debug("start")
    try:
        ping_server.listen(arguments.ping_manager_port)
    except OSError:
        print("port %s is already is use, exiting" %
              arguments.ping_manager_port)
        return

    tornado.ioloop.IOLoop.instance().start()
Exemplo n.º 26
0
def main():
	p = Ping('0.0.0.0', '0.0.0.0')
	currentSocket = p.get_socket()
	buffer = []
	while(True):
		inputs, output, exception = select.select([currentSocket, sys.stdin] , [currentSocket], [])
		for i in inputs:
			if i == currentSocket :
				receiverFunction(p)
			elif i == sys.stdin :
				x = raw_input()
				buffer.append(x)
		if currentSocket in output :
			for i in range(len(buffer)):
				if buffer[i] == "upload":
					senderFunction(p)
				elif buffer[i] == "download":
					downloadFunction(p)
				elif buffer[i] == "vim":
					showFile()
				else :
					print "Commmand not found! try again."
			buffer = []
Exemplo n.º 27
0
def update_streams_cache(session_key=None):
    global dateLastUpdated
    global stream_forwarder_results_cache
    try:
        appsMeta = Ping.ping(session_key)
        if appsMeta['dateLastUpdated'] > dateLastUpdated:
            logger.debug("cachedateLastUpdated:: %d" % dateLastUpdated)
            logger.debug("appsDateLastUpdated:: %d" %
                         appsMeta['dateLastUpdated'])
            init_streams_collection(session_key)
            dateLastUpdated = appsMeta['dateLastUpdated']
            stream_forwarder_results_cache = {}
    except Exception as e:
        # Exception happens as appsMeta file is in the process of getting written to.
        # Do Nothing and return existing cache.
        logger.exception(e)
    def collect(self) -> str:
        hostfile_devices = list(
            chain.from_iterable(
                [HostFileParser(hf).read() for hf in configuration.HostFiles]))
        all_configured_devices = hostfile_devices + configuration.CustomNetworkDevices

        # Execute
        ping_executors = [
            Ping(hostentry) for hostentry in all_configured_devices
        ]
        self.execute_in_parallel(
            [ping_executor.ping() for ping_executor in ping_executors])
        return '\n'.join([
            '\n'.join(ping_executor.export_prometheus_metric())
            for ping_executor in ping_executors
        ])
Exemplo n.º 29
0
    def __init__(self, session, vm, ip): 
        lock = threading.Lock()
        with lock: 
            threading.Thread.__init__(self)
            Pinger.pingerCount = Pinger.pingerCount + 1                 #pinger count - also used in VM unique has algorithm
         
            self.__stopPings = 0;                                       #stop pings toggle
            self.__session = session                                    #save session
            self.__VM = vm                                              #save vm being monitored
            self._id = (get_ident() ^ os.getpid()) + Pinger.pingerCount #create a unique hash for the VM - needed for ICMP pings

            self.__ip = ip                                              #save ip 
            self.__missedPings = 0                                      #number of missed pings
            self.__pingObj = Ping(ip, 1000, 55, self._id)               #create Ping object
            self.__snapped = 0                                          #toggle for if snapshot has already occurred
            self.misses = 2                                             #number of missed pings allowed
Exemplo n.º 30
0
	def __init__(self,scan_type,*args):
		super(Header,self).__init__()
		self.target = args[0]
		self.ports = args[1]
		self.threads = args[2]
		self.timeout = args[3]
		self.quite = args[4]
		self.opened = []
		self.refused = []
		self.filtered = []
		self.packets = []
		self.conn_type = ""
		self.data = '\x00' * 20
		self.scan_type = scan_type
		self.sip = get_our_addr()
		self.portresult = portResult()
		self.sport = randrange(1,65535)
		
		self.udp_packet = UDPPacket()
		self.port_len = len(self.ports)-1
		self.ip = domain_resolver(self.target,True)
		self.response_time = Ping(self.target,self.timeout)._start_icmp()

		if self.scan_type == "conn" or self.scan_type == "syn":
			self.conn_type += "tcp"
		elif self.scan_type == "udp":
			self.conn_type = self.scan_type

		try:
			self.ipv6 = [str(ip) for ip in resolve_ipv6(self.target)]
		except:
			self.ipv6 = None
		
		self.rdns = resolve_PTR(self.ip)
		if self.rdns != None:
			self.rdns = self.rdns[0]

		self.resolved_ips = [str(ip) for ip in resolve_ips(self.target)]
		if len(self.resolved_ips) > 1:
			if self.ip in self.resolved_ips:
				self.resolved_ips.remove(self.ip)
		
		if self.scan_type == "udp":
			self.udp_packet_capture = Capture(self.ip)._set_udp()

		else:
			self.tcp_packet_capture = Capture(self.ip)._set_tcp()
Exemplo n.º 31
0
    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)
Exemplo n.º 32
0
    def check_server(cls, server):

        # Check if there was another in the leeway time
        minimum_time = timezone.now()-timedelta(minutes=settings.LEEWAY_TIME)
        if ServerCheck.objects.filter(server=server, check_date__gte=minimum_time).count() > 0:
            return False

        check_log = ServerCheck(server=server, ip_address=server.main_ip, check_date=timezone.now())
        checker = Ping(check_log.ip_address).run_ping()
        check_log.online = checker.is_online

        check_log.save()
        if check_log.did_change:
            if checker.is_online:
                send_back_up(checker, check_log)
            else:
                send_failure(checker, check_log)
        return check_log
Exemplo n.º 33
0
    def test_first(self):
        pinga = Ping('sun.com')

        self.assertTrue(self.reply_match("\d{2,3}", pinga.get_ttl()))

        self.assertTrue(
            self.reply_match("\d{2,3}.\d{2,3}", pinga.get_response()))

        self.assertTrue(
            self.reply_match("\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}",
                             pinga.get_time()))

        self.assertTrue(self.reply_match("\w+.\w+", pinga.get_dest()))
Exemplo n.º 34
0
def init_users(session_key=None):
    global tour_users, easy_setup_users, dateLastUpdated
    try:
        pingData = Ping.ping(session_key)
        if pingData['dateLastUpdated'] > dateLastUpdated:
            logger.debug("cachedateLastUpdated:: %d" % dateLastUpdated)
            logger.debug("appsDateLastUpdated:: %d" %
                         pingData['dateLastUpdated'])
            dateLastUpdated = pingData['dateLastUpdated']
            if not use_kv_store:
                tour_users_list = readAsJson(
                    os.path.join(users_dir, 'tour_users'))
                if tour_users_list != 'NotFound':
                    tour_users = set(tour_users_list)
                easy_setup_users_list = readAsJson(
                    os.path.join(users_dir, 'easy_setup_users'))
                if easy_setup_users_list != 'NotFound':
                    easy_setup_users = set(easy_setup_users_list)
            else:
                uri = user_tours_kv_store_uri
                if session_key:
                    uri = user_tours_kv_store_with_session_key_uri
                json_data = read_from_kv_store_coll(uri, session_key)
                if 'visited' in json_data:
                    tour_users = set(json_data['visited'])

                uri = user_easy_setup_kv_store_uri
                if session_key:
                    uri = user_easy_setup_kv_store_with_session_key_uri
                json_data = read_from_kv_store_coll(uri, session_key)
                if 'visited' in json_data:
                    easy_setup_users = set(json_data['visited'])

    except Exception as e:
        # Exception happens as appsMeta file is in the process of getting written to.
        # Do Nothing and return existing cache.
        logger.exception(e)
Exemplo n.º 35
0
def ping(host):
    p = Ping(PING_COUNT)
    return (p.time(host), whoami, host)
Exemplo n.º 36
0
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)
Exemplo n.º 37
0
def ping_host(host):
    with no_stdout():
        p = Ping(host, timeout=PING_TIMEOUT)
        return p.do()
Exemplo n.º 38
0
def main(argv):
    """
    Ping a domain name or IP address. A specific port may be specified as well as the time interval to send pings at
    and the period of time to wait for responses.
    :param argv: The list of command line arguments and their corresponding values.
    :return: A number indicating the success or failure of the function call.
            0 = no issue
            1 = GetoptError
            2 = Specified both hostname and ip address
            3 = Invalid IPV4 number
            4 = Invalid IPV6 number
            5 = Invalid IP address of unrecognized type
            6 = Invalid port number
            7 = Non-numerical time interval
            8 = Non-numerical wait period
    """
    try:
        opts, args = getopt.getopt(argv, "hn:i:p:t:w:", [
            "host_name=", "ip_address=", "port=", "time_interval",
            "wait_period"
        ])
    except getopt.GetoptError:
        sys.stderr.write(
            'python3 main.py -n <host name> -i <ip address> -p <port number> -t <time interval> -w <wait period>\n'
        )
        sys.exit(1)
    opt_specified = [opt for opt, arg in opts]
    time_interval_used = False
    wait_period_used = False
    port_requested = False
    if opt_specified.count('-h') != 0:
        print(
            'python3 main.py -n <host name> -i <ip address> -p <port number> -t <time interval> -w <wait period>'
        )
        sys.exit(0)
    elif opt_specified.count('-n') + opt_specified.count('-i') != 1:
        sys.stderr.write(
            'You specified more than one hostname, more than one IP address or a combination of hostnames and IP '
            'addresses. You specify one argument for -n or one argument for -i.\n'
        )
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-n':
            # Want to get the ip address from the hostname
            _, _, _, _, addr = socket.getaddrinfo(arg, 0)[0]
            # addr is a (host, port) tuple and we don't need the port for ICMP
            addr = addr[0]
        if opt == '-i':
            if isinstance(arg, str) and arg.count('.') == 3:
                byte_list = arg.split('.')
                for byte in byte_list:
                    byte = int(byte)
                    if not (byte >= 0 and byte <= 255):
                        sys.stderr.write(
                            'You specified an invalid IPV4 number. You must have four integers in the range [0, 255] '
                            'interspaced with the . character.\n')
                        sys.exit(3)
                addr = arg
            elif isinstance(arg, str) and arg.count(':') == 7:
                hexidecimals = arg.split(':')
                for hexidecimal in hexidecimals:
                    hexidecimal = int(hexidecimal, 16)
                    if not (hexidecimal >= 0 and hexidecimal <= 65535):
                        sys.stderr.write(
                            'You specified an invalid IPV6 number. You must have eight integers in the range [0, 65535]'
                            ' interspaced with the : character and written in hexadecimal.\n'
                        )
                        sys.exit(4)
                addr = arg
            else:
                sys.stderr.write(
                    'You specified an invalid IP address. You must use either IPV4 or IPV6 format.\n'
                )
                sys.exit(5)
        if opt == '-p':
            port_requested = True
            if arg.isdigit() and (int(arg) >= 0 and int(arg) <= 65535):
                port = arg
            else:
                sys.stderr.write(
                    'You specified an invalid port number. You must choose an integer in [0, 65535].\n'
                )
                sys.exit(6)
        if opt == '-t':
            if arg.isnumeric():
                time_interval = float(arg)
                time_interval_used = True
            else:
                sys.stderr.write(
                    'You specified an invalid time interval. You must choose an float.\n'
                )
                sys.exit(7)
        if opt == '-w':
            if arg.isnumeric():
                wait_period = float(arg)
                wait_period_used = True
            else:
                sys.stderr.write(
                    'You specified an invalid time interval. You must choose an float.\n'
                )
                sys.exit(8)

    if time_interval_used and wait_period_used:
        my_ping = Ping(addr,
                       timeout=wait_period,
                       time_between=time_interval,
                       id=1)
    elif wait_period_used:
        my_ping = Ping(addr, timeout=wait_period, id=1)
    elif time_interval_used:
        my_ping = Ping(addr, time_between=time_interval, id=1)
    else:
        my_ping = Ping(addr, id=1)
    if port_requested:
        port_open = False
        port_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        port_socket.settimeout(3)
        try:
            port_socket.connect((addr, int(port)))
            port_socket.shutdown(socket.SHUT_RDWR)
            port_open = True
        except:
            pass
        finally:
            port_socket.close()

        if port_open:
            print("Port number {} at {} is OPEN".format(port, addr))
        else:
            print("Port number {} at {} is CLOSED".format(port, addr))

    my_ping.run()
Exemplo n.º 39
0
                        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
Exemplo n.º 40
0
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import sys
from ping import Ping

ping = Ping()

fig = plt.figure()  # Create the main figure of the graph
fig.suptitle('Ping Response Graph')  # Give it a main title
fig.canvas.toolbar.pack_forget()  # Remove toolbar
fig.canvas.set_window_title('Ping Graph')

ax = plt.subplot()  # Create an Axes object for the figure
ax.set_xlabel('Time?')  # Set the label for the x-axis
ax.set_ylabel('Response Time (ms)')  # Set the label for the y-axis

pingarray = []


def animate(i, ostype,
            server):  # I don't know why, but the func def needs an argument
    pingresponse = ping.call(ostype,
                             server)  # Get the response time of the ping call
    pingarray.append(
        pingresponse
    )  # Add that response time to a list of responses for plotting

    if pingresponse == 0:
        plt.plot(pingarray, 'r')  # Plot the current array
    else:
        plt.plot(pingarray, 'b')  # Plot the current array
Exemplo n.º 41
0
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)
Exemplo n.º 42
0
# coding:utf8
from ping import Ping


class PingServer(object):

    def send_ping(self, msg):
        return msg


handler = PingServer()
processor = Ping.Processor(handler)

if __name__ == '__main__':
    from thrift.transport import TSocket
    from thrift.transport import TTransport
    from thrift.protocol import TBinaryProtocol
    from thrift.server import TServer
    from thrift.server.TProcessPoolServer import TProcessPoolServer

    transport = TSocket.TServerSocket("0.0.0.0", 7748)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TProcessPoolServer(processor, transport, tfactory, pfactory)

    server.serve()
Exemplo n.º 43
0
 def verbose_ping(self,hostname, timeout=1000, count=3, packet_size=55):
     self.p = Ping(hostname, timeout, packet_size,windows=self)
     self.p.run(count)
Exemplo n.º 44
0
class MyFrame1(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title= u'3G信号检测工具',size=(500,500))
        
        self.thread=None
        self.p = None
        
        panel = wx.Panel(self)
        self.left = wx.BoxSizer(wx.VERTICAL)
        self.right = wx.BoxSizer(wx.VERTICAL)
        
        self.startBtn = wx.Button(panel, -1, u"开始")
        self.stopBtn = wx.Button(panel, -1, u"停止")
        self.pingBtn = wx.Button(panel,-1,u"Ping生产服务器")
        self.stopPingBtn = wx.Button(panel,-1,u"停止Ping生产服务器")
        
        self.log = wx.TextCtrl(panel,-1,"",style=wx.TE_RICH|wx.TE_MULTILINE)
        
        self.signal1 = wx.Gauge(panel,-1,range=31,size=(100,20),style = wx.GA_HORIZONTAL)
        self.signal1.SetBezelFace(3)
        self.signal1.SetShadowWidth(3)
        self.signal2 = wx.Gauge(panel,-1,range=31,size=(100,20),style = wx.GA_HORIZONTAL)
        self.signal2.SetBezelFace(3)
        self.signal2.SetShadowWidth(3) 
 
        self.tc1 = wx.StaticText(panel, -1, u"电信3G信号强度:        ")
        self.tc2 = wx.StaticText(panel, -1, u"联通3G信号强度:        ")
        
        self.tc3 = wx.StaticText(panel, -1, u"与服务器通信平均延迟")
        
        self.menu = wx.BoxSizer(wx.VERTICAL)
        self.menu.Add(self.startBtn,0,wx.RIGHT,15)
        self.menu.Add(self.stopBtn,0,wx.RIGHT,15)
        self.right.Add(self.pingBtn,0,wx.RIGHT,15)
        self.right.Add(self.stopPingBtn,0,wx.RIGHT,15)
        self.right.Add(self.tc3,0,wx.RIGHT,15)
        
        self.left.Add(self.tc1,0,wx.LEFT,15)
        self.left.Add(self.signal1,0,wx.LEFT,15)
        self.left.Add(self.tc2,0,wx.LEFT,15)
        self.left.Add(self.signal2,0,wx.LEFT,15)
        
        self.top = wx.BoxSizer(wx.HORIZONTAL)
        self.top.Add(self.menu,0,wx.LEFT|wx.EXPAND, 5)
        self.top.Add(self.left,0,wx.LEFT|wx.EXPAND, 5)
        self.top.Add(self.right,0,wx.LEFT|wx.EXPAND, 5)
        
        self.main = wx.BoxSizer(wx.VERTICAL)
        self.main.Add(self.top,0,wx.ALL|wx.EXPAND,5)
        self.main.Add(self.log,1,wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(self.main)
        
        self.Bind(wx.EVT_CLOSE,  self.OnCloseWindow)
        self.Bind(wx.EVT_BUTTON, self.OnStartBtn,self.startBtn)
        self.Bind(wx.EVT_BUTTON, self.OnStopBtn,self.stopBtn)
        self.Bind(wx.EVT_BUTTON, self.pingServer, self.pingBtn)
        self.Bind(wx.EVT_BUTTON, self.stopPingServer, self.stopPingBtn)
    
    def OnCloseWindow(self, evt):
        self.Destroy()
    
    def OnStartBtn(self,evt):
        self.thread = ShowSignalThread(self)
        self.startBtn.Disable()
        #except TypeError:
            #self.
            
    def OnStopBtn(self,evt):
        if self.thread!=None:
            self.thread.stop()
            self.thread = None
        self.startBtn.Enable()
        self.UpdateSignal1('0')
        self.UpdateSignal2('0')
        
    def UpdateSignal1(self,msg):
        self.signal1.SetValue(int(msg))
        self.SetTc1(msg)
    
    def UpdateSignal2(self,msg):
        self.signal2.SetValue(int(msg))
        self.SetTc2(msg)
        
    def SetTc1(self,msg):
        percent = int(msg)*100/31
        self.tc1.SetLabel(u'电信3G信号强度:'+str(percent)+'%')
    
    def SetTc2(self,msg):
        percent = int(msg)*100/31
        self.tc2.SetLabel(u'联通3G信号强度:'+str(percent)+'%')
    
    def sendMessage(self, msg):
        self.log.AppendText(msg+"\n")
    
    def verbose_ping(self,hostname, timeout=1000, count=3, packet_size=55):
        self.p = Ping(hostname, timeout, packet_size,windows=self)
        self.p.run(count)
    
    def pingServer(self,evt):
        thread.start_new(self.verbose_ping, ("192.168.1.1", 4000,500,32))
    
    def stopPingServer(self,evt):
        self.p.stopRun()
    
    def showPing(self,msg):
        self.tc3.SetLabelText(u"与服务器通信平均延迟%0.3fms"%(msg))
Exemplo n.º 45
0
#!/usr/bin/env python
# coding: utf-8

import os
import requests
from ping import Ping
from time import sleep

STATED_APIKEY = os.getenv('STATED_APIKEY', '*****@*****.**')

while True:
    sleep(1)
    try:
        my_ip = os.getenv('MY_IP', '8.8.8.8')
        p = Ping(my_ip, 2000, 55)
        ms = p.run()
    except:
        print("Some exception")
    if ms:
        params = {"u":STATED_APIKEY, "stat":"ping", "value":str(ms)}
        r = requests.get("https://stated.io/api", params=params )
        print(str(ms) + "ms" + ": " + str(r.status_code))
    else:
        print("Ping failure")
Exemplo n.º 46
0
from __future__ import absolute_import

from thrift.transport.THttpClient import THttpClient
from thrift.protocol.TBinaryProtocol import TBinaryProtocolAccelerated

from ping import Ping

trans = THttpClient('http://localhost:8888/thrift')
proto = TBinaryProtocolAccelerated(trans)
client = Ping.Client(proto)

print client.ping('world')
Exemplo n.º 47
0
Arquivo: t.py Projeto: sbear/Mping
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
Exemplo n.º 48
0
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
Exemplo n.º 49
0
from ping import Ping

teste = Ping()
teste.preenche_dados()
teste.executa_teste()
Exemplo n.º 50
0
        "-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
Exemplo n.º 51
0
def init_date_last_updated():
    global dateLastUpdated
    pingData = Ping.ping()
    dateLastUpdated = pingData['dateLastUpdated']