Beispiel #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
Beispiel #2
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
Beispiel #3
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 = []
Beispiel #4
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())
Beispiel #5
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()
Beispiel #6
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))
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)
Beispiel #8
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()))
 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)
Beispiel #10
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()))
Beispiel #11
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()
Beispiel #12
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()))
Beispiel #13
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([])
    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
        ])
Beispiel #15
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()
Beispiel #16
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
Beispiel #17
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
Beispiel #18
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 = []
Beispiel #19
0
            pass
        else:
            return port


if __name__ == '__main__':
    if platform.system() == 'Windows':
        sys.stderr.write('It only works on Linux OS\n')
        sys.exit(1)

    args = parse_args()
    dst = socket.gethostbyname(args.host)
    ip = args.ip
    if dst == '127.0.0.1':
        ip = '127.0.0.1'
    if not ip:
        ip = get_ip()

    if os.geteuid() != 0:
        sys.stderr.write('Use it with sudo\n')
        sys.exit(1)

    s = Network()
    port = _check_port(s)

    ping = Ping((ip, port), (dst, args.port), s, args.waiting, args.debug)
    try:
        ping.start(args.count, args.interval)
    except KeyboardInterrupt:
        sys.exit()
Beispiel #20
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()
Beispiel #21
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
Beispiel #22
0
from ping import Ping

teste = Ping()
teste.preenche_dados()
teste.executa_teste()
Beispiel #23
0
 def setUpClass(cls):
     cls.socket = Network()
     ip = '127.0.0.1'
     cls.ping = Ping((ip, 10001), (ip, 10002), cls.socket, 2)
Beispiel #24
0
from display import Display
from ping import Ping
from usb_control import Usb_Control

server_ip = '192.168.43.134'

if __name__ == '__main__':
    wsc = WSC()  # 创建wsc
    wsc.connect('http://%s:12306' % server_ip)  # 连接树莓派

    time.sleep(1)  # 这里应该是异步回调,图省事先

    ctrl = Ctrl(wsc)  # 创建控制现场
    ctrl.restartCamera()  # 下发指令给树莓派启动摄像头
    ctrl.initCarControl()  # 初始化舵机和电调

    usbControl = Usb_Control(wsc)
    usbControl.start()

    camera = Camera(server_ip)
    camera.start()

    keyboardControl = Keyboard_Control(wsc)
    # keyboardControl.start()

    ping = Ping(wsc)  # 创建ping对象
    ping.start()  # 循环下发ping测指令给树莓派
    wsc.setPing(ping)  # 将ping对象传递给wsc

    display = Display(camera, keyboardControl, ping)
    display.start()
Beispiel #25
0
async def create_ping(message, client, pings):
    msg_content = message.content
    print("Message \"{0}\" being made into a ping".format(msg_content))
    channel = message.channel

    # don't let an author create multiple pings in one server
    if len(pings) > 0:
        for ping in pings:
            if ping.get_author(
            ) == message.author and ping.get_server == message.server:
                msg = 'Hey you, you already have a ping in this server! :angry:'
                await client.send_message(channel, msg)
                return

    msg = ""
    msg_start = msg_content.find('"')
    msg_end = msg_content.rfind('"')

    if msg_start != -1 and msg_end != -1:
        msg_start += 1
        msg = msg_content[msg_start:msg_end]
    else:
        return_msg = error + 'No message given / missing a quotation mark!'
        await client.send_message(channel, return_msg)
        return

    mentions = []

    index = 0

    while msg_content.find('<', index, msg_start) != -1:
        mention_start = msg_content.find('<', index)
        mention_end = msg_content.find('>', index) + 1

        mention = msg_content[mention_start:mention_end]
        print(mention)

        if not mention in mentions:
            mentions.append(mention)

        index = mention_end

    if not mentions:
        return_msg = error + 'No users to ping!'
        await client.send_message(channel, return_msg)
        return
    elif client.user.mention in mentions:
        return_msg = error + 'Don\'t ping me :rage:'
        await client.send_message(channel, return_msg)
        return

    interval_start = msg_content.rfind('every', msg_end)
    interval_end = msg_content.rfind('seconds', msg_end)

    if interval_start != -1 and interval_end != -1:
        interval_start += 6
        interval_end -= 1
    else:
        return_msg = error + 'You didn\'t say \"every\" or \"seconds\", silly. ;)'
        await client.send_message(channel, return_msg)
        return

    interval = int(msg_content[interval_start:interval_end])

    if interval == 1:
        return_msg = 'No 1 second messages allowed. :rage:'
        await channel.send_message(channel, return_msg)
        return

    pingie = Ping(message, msg, mentions, interval, client)
    pings.append(pingie)
    await client.send_message(channel, success + 'Gotcha. :)')
    await pingie.start()
Beispiel #26
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
Beispiel #27
0
from ping import Ping
from db import PingDB

locs = [
    Ping('sun.com'),
    Ping('oracle.com'),
    Ping('ftp.sunet.se'),
    Ping('bolagsverket.se')
]

db = PingDB()

#
#sun.com 2011-11-26 06:55:28 184.954 229
#oracle.com 2011-11-26 06:55:29 184.796 229
#ftp.sunet.se 2011-11-26 06:55:29 35.066 51
#bolagsverket.se 2011-11-26 06:55:29 45.789 113

for loc in locs:
    print loc.get_dest(), loc.get_time(), loc.get_response(), loc.get_ttl()
    db.write(date=loc.get_time(),
             pingobj=loc.get_dest(),
             ttl=loc.get_ttl(),
             response=loc.get_response())
Beispiel #28
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")
 def process_ping(self, vehicle_name, x, y, timestamp):
     ping = Ping(x, y, timestamp)
     if len(self.vehicles) == 0 or vehicle_name != self.vehicles[-1].get_name():
         self.vehicles.append(Vehicle(vehicle_name))
     self.vehicles[-1].get_pings().append(ping)