示例#1
0
def collectPing(hostname):
    if sys.platform == "linux" or sys.platform == "linux2":
        response = pingparser.parse(str(systemCommand("ping -W 5 -c 1 " + hostname, False)))
    elif sys.platform == "darwin":
        response = pingparser.parse(str(systemCommand("ping -W 5 -c 1 " + hostname, False)))
    elif sys.platform == "win32":
        response = systemCommand("ping "+hostname+" -n 1")
    else:
        response = systemCommand("ping -W -c 1 " + hostname)
    return response
示例#2
0
def collectPing(hostname):
    if sys.platform == "linux" or sys.platform == "linux2":
        response = pingparser.parse(
            str(systemCommand("ping -W 5 -c 1 " + hostname, False)))
    elif sys.platform == "darwin":
        response = pingparser.parse(
            str(systemCommand("ping -W 5 -c 1 " + hostname, False)))
    elif sys.platform == "win32":
        response = systemCommand("ping " + hostname + " -n 1")
    else:
        response = systemCommand("ping -W -c 1 " + hostname)
    return response
def ping(target, num_pings, interface):
    cmd = ['ping', '-c', str(num_pings)]
    if (interface):
        cmd.extend(['-I', interface])
    cmd.append(target)
    if EXPCONFIG['verbosity'] > 1:
        print("doing {} pings to {} ...".format(num_pings, target))
    time_start = time.time()
    p = Popen(cmd, stdout=PIPE)
    data = p.communicate()[0]
    time_end = time.time()
    if EXPCONFIG['verbosity'] > 1:
        print("ping finished.")
    if EXPCONFIG['verbosity'] > 2:
        print("ping: {}".format(data))
    try:
        ping = pingparser.parse(data)
    except Exception as e:
        ping = {'error': 'could not parse ping'}
    if not ping:
        ping = {'error': 'no ping output'}
    ping['time_start'] = time_start
    ping['time_end'] = time_end
    ping['raw'] = data.decode('ascii', 'replace')
    return ping
示例#4
0
def ping(target, num_pings, interface, ping_timeout):

    cmd = ["ping", "-c", str(num_pings), "-a", "-W", str(ping_timeout)]

    if (interface):
        cmd.extend(["-I", interface])
    cmd.append(target)

    if EXPCONFIG["cnf_verbosity"] > 1:
        print("\n" + TAG +
              "Running {} pings to {} ...".format(num_pings, target))

    time_start = time.time()
    p = Popen(cmd, stdout=PIPE)
    data = p.communicate()[0]
    time_end = time.time()

    if EXPCONFIG["cnf_verbosity"] > 1:
        print(TAG + "Ping finished.")

    if EXPCONFIG["cnf_verbosity"] > 2:
        print(TAG + "Ping result: \n{}".format(data))

    try:
        ping = pingparser.parse(data)
    except Exception as e:
        ping = {"error": "could not parse ping"}
    if not ping:
        ping = {"error": "no ping output"}

    ping["time_start"] = time_start
    ping["time_end"] = time_end
    ping["raw"] = data.decode("ascii", "replace")

    return ping
示例#5
0
    def measure_ping_latency(self, destination_host):
        ping_latency = str(os.system(
            "ping " + ("-n 1 " if platform.system().lower() == "windows" else "-c 1 ") + str(destination_host)))

        ping_data_parsed = pingparser.parse(ping_latency)

        return ping_data_parsed
示例#6
0
def ping(host):
    ping = subprocess.Popen(["ping", "-c", "1", "-W", "1", host],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)

    out, error = ping.communicate()

    return pingparser.parse(out)
示例#7
0
def ping(host):
	ping = subprocess.Popen(
		["ping", "-c", "1", "-W", "1", host],
		stdout = subprocess.PIPE,
		stderr = subprocess.PIPE
	)

	out, error = ping.communicate()
	return pingparser.parse(out)
def ping_test(h0, h1, ping_results):
    info("*** Running test\n")
    ping_res = h0.cmdPrint('ping -c1 ' + h1.IP())
    ping_res = pingparser.parse(ping_res)
    tm_local = time.localtime()
    ping_res['time'] = '{}:{}:{}'.format(tm_local.tm_hour, tm_local.tm_min,
                                         tm_local.tm_sec)
    val_string = ','.join(ping_res.itervalues())
    ping_results.append(val_string + "\n")

    print ping_res
    info("*** Sleep\n")
示例#9
0
文件: test.py 项目: gg/pingparser
 def testParseFunction(self):
     """
     Test parse() of `data` expecting `expected_result`
     """
     for file_name, data, expected_result in self.test_data:
         try:
             parsed = parse(data)
             assert(format_ping_result(parsed) == expected_result)
         except (AssertionError) as e:
             e.args += ('File: ', file_name, ' failed comparison.', parsed, expected_result)
             raise
         except:
             # Any other exception, TODO: explicitly handle all parse() errors
             raise
示例#10
0
def ping(address):
    'Ping address and return the parsed results'
    command = 'ping -c 1 ' + address
    args = shlex.split(command)
    try:
        output = subprocess.check_output(args, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError:
        print('Error pinging address. Check hosts in config file.')
        sys.exit(1)

    output = str(output).strip()
    results = pingparser.parse(output)

    return results
示例#11
0
 def testParseFunction(self):
     """
     Test parse() of `data` expecting `expected_result`
     """
     for file_name, data, expected_result in self.test_data:
         try:
             parsed = parse(data)
             assert (format_ping_result(parsed) == expected_result)
         except (AssertionError) as e:
             e.args += ('File: ', file_name, ' failed comparison.', parsed,
                        expected_result)
             raise
         except:
             # Any other exception, TODO: explicitly handle all parse() errors
             raise
示例#12
0
文件: tools.py 项目: thaolt/EasyStorj
    def measure_ping_latency(self, destination_host):
        """
                Measure ping latency of a host
                Args:
                    destination_host (str): the ip of the host
                Returns:
                    ():
        """
        ping_latency = str(
            os.system("ping " + ("-n 1 " if platform.system().lower() ==
                                 "windows" else "-c 1 ") +
                      str(destination_host)))

        ping_data_parsed = pingparser.parse(ping_latency)

        return ping_data_parsed
示例#13
0
def ping(request, tunnel_id, target):
    tunnel = get_object_or_404(Tunnel, pk=tunnel_id)
    if target == '':
        hostname = tunnel.client
    else:
        hostname = target
    pkts = 10
    if request.GET.get('pkts'):
        try:
            pkts = int(request.GET['pkts'])
        except (ValueError, TypeError) as exc:
            log.warning("Couldn't cast pkts param (%s) to int: %r",
                        request.GET['pkts'], exc)

    cmd = ['ping', '-c', str(pkts), '-i', '0.4', '-W', '1', '-q', '-I',
           str(tunnel.name), str(hostname)]
    ping_output = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    ping_parsed = pingparser.parse(ping_output.stdout.read())
    return JsonResponse(ping_parsed)
def make_ping(hostname, number=3):
    try:
        output = subprocess.check_output("ping -c " + str(number) + " " +
                                         hostname,
                                         shell=True)
        results = pingparser.parse(output)

    except Exception as e:
        ErrorM.send_email('*****@*****.**', hostname + ' not responding')
        results = {}
        results["host"] = hostname
        results["received"] = '0'
        results["sent"] = '5'
        results["jitter"] = '0'
        results["packet_loss"] = '0'
        results["avgping"] = '0'
        results["minping"] = '0'
        results["maxping"] = '0'

    return OrderedDict(sorted(results.items()))
from __future__ import division
import pingparser
import os, sys, glob, re
from os.path import isfile


if __name__ == '__main__':
    i = 0.54
    jitter_file = open('/home/luca/workspace/interference_scenario/jitter_diff.dat', "w")
    delay_file = open('/home/luca/workspace/interference_scenario/delay_diff.dat', "w")
    packet_loss_file = open('/home/luca/workspace/interference_scenario/packet_loss_diff.dat', "w")

    os.chdir("/home/luca/stats/interference_scenario/")
    for my_file in sorted(glob.glob('*')):
        if isfile(my_file):
            print my_file
            with open (my_file, "r") as read_file:
                data=read_file.read().replace('\n', '')
                read_file.close()
                parsed_data = pingparser.parse(data)        
                #print parsed_data
                jitter = parsed_data.get('jitter')
                jitter_file.write(str(i) + " " + jitter + "\n")
                delay = parsed_data.get('avgping')
                delay_file.write(str(i) + " " + delay + "\n")
                packet_loss = 100 - (float(parsed_data.get('received', None)) * 100 / float(parsed_data.get('sent', None)))
                packet_loss_file.write(str(i) + " " + str(packet_loss) + "\n")
                i = i + 0.01
示例#16
0
def ping(host,
         count=1,
         index=None,
         sourcetype="ping",
         source="ping_search_command",
         logger=None):
    """
    Pings the host using the native ping command on the platform and returns a tuple consisting of:

     1) the output string
     2) the return code (0 is the expected return code)
     3) parsed output from the ping command
    """

    cmd = ["ping"]

    # Add the argument of the number of pings
    if system_name().lower() == "windows":
        cmd.extend(["-n", str(count)])
    else:
        cmd.extend(["-c", str(count)])

    # Add the host argument
    cmd.append(host)

    output = None
    return_code = None

    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        return_code = 0
    except subprocess.CalledProcessError as exception:
        output = exception.output
        return_code = exception.returncode
    except OSError as exception:
        if exception.errno == errno.ENOENT:
            raise CommandNotFoundException(cmd[0])
        else:
            raise exception

    # Parse the output
    try:
        parsed = pingparser.parse(output)
    except Exception:
        parsed = {'message': 'output could not be parsed', 'output': output}

    # Write the event as a stash new file
    if index is not None:
        writer = StashNewWriter(index=index,
                                source_name=source,
                                sourcetype=sourcetype,
                                file_extension=".stash_output")

        result = collections.OrderedDict()
        result.update(parsed)

        if 'host' in result:
            result['dest'] = result['host']
            del result['host']

        result['return_code'] = return_code
        result['output'] = output

        # Remove the jitter field on Windows since it doesn't get populated on Windows
        if 'jitter' in result and (result['jitter'] is None
                                   or len(result['jitter']) == 0):
            del result['jitter']

        # Log that we performed the ping
        if logger:
            logger.debug("Wrote stash file=%s", writer.write_event(result))

    return output, return_code, parsed