示例#1
0
 def mdns_show_hosts_line(self, line):
     """Show hosts of mDNS client.\n"""
     parser = parsing_opts.gen_parser(
         self,
         "mdns_show_hosts",
         self.mdns_show_hosts_line.__doc__,
         parsing_opts.EMU_NS_GROUP,
         parsing_opts.MAC_ADDRESS,
     )
     opts = parser.parse_args(line.split())
     ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
     c_key = EMUClientKey(ns_key, opts.mac)
     hosts = self.get_client_hosts(c_key=c_key)
     if hosts:
         hosts = listify(hosts)
         keys_to_headers = [
             {
                 'key': 'number',
                 'header': 'Number'
             },
             {
                 'key': 'hostname',
                 'header': 'Hostname'
             },
         ]
         res = [{
             'number': i + 1,
             'hostname': host
         } for i, host in enumerate(hosts)]
         self.print_table_by_keys(res, keys_to_headers, title="Hostnames")
     else:
         text_tables.print_colored_line(
             "The client doesn't own any hostname.", "yellow")
示例#2
0
    def print_table_by_keys(self, data, keys_to_headers, title = None, empty_msg = 'empty'):

        def _iter_dict(d, keys, max_lens):
            row_data = []
            for j, key in enumerate(keys):
                val = str(conv_to_str(d.get(key), key))
                row_data.append(val)
                max_lens[j] = max(max_lens[j], len(val))
            return row_data

        if len(data) == 0:
            text_tables.print_colored_line(empty_msg, 'yellow', buffer = sys.stdout)      
            return

        table = text_tables.TRexTextTable(title)
        headers = [e.get('header') for e in keys_to_headers]
        keys = [e.get('key') for e in keys_to_headers]
        
        max_lens = [len(h) for h in headers]
        table.header(headers)

        if type(data) is list:
            for one_record in data:
                row_data = _iter_dict(one_record, keys, max_lens)
                table.add_row(row_data)
        elif type(data) is dict:
                row_data = _iter_dict(data, keys, max_lens)
                table.add_row(row_data)

        # fix table look
        table.set_cols_align(["c"] * len(headers))
        table.set_cols_width(max_lens)
        table.set_cols_dtype(['a'] * len(headers))
        
        text_tables.print_table_with_header(table, table.title, buffer = sys.stdout)
示例#3
0
 def dns_show_domains_line(self, line):
     """Show domains a Name Server holds.\n"""
     parser = parsing_opts.gen_parser(self, "dns_show_domains",
                                      self.dns_show_domains_line.__doc__,
                                      parsing_opts.EMU_NS_GROUP,
                                      parsing_opts.MAC_ADDRESS)
     opts = parser.parse_args(line.split())
     ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
     c_key = EMUClientKey(ns_key, opts.mac)
     domains = self.get_domains(c_key=c_key)
     if domains:
         domains = listify(domains)
         keys_to_headers = [
             {
                 'key': 'number',
                 'header': 'Number'
             },
             {
                 'key': 'domain',
                 'header': 'Domain'
             },
         ]
         res = [{
             'number': i + 1,
             'domain': domain
         } for i, domain in enumerate(domains)]
         self.print_table_by_keys(res, keys_to_headers, title="Domains")
     else:
         text_tables.print_colored_line(
             "The Name Server doesn't recognize any domains.", "yellow")
示例#4
0
    def icmp_get_ping_stats(self, line):
        """ICMP get ping stats (per client).\n"""
        parser = parsing_opts.gen_parser(self,
                                         "icmp_get_ping_stats",
                                         self.icmp_get_ping_stats.__doc__,
                                         parsing_opts.MAC_ADDRESS,
                                         parsing_opts.EMU_NS_GROUP,
                                         parsing_opts.EMU_SHOW_CNT_GROUP,
                                         parsing_opts.EMU_DUMPS_OPT
                                         )

        opts = parser.parse_args(line.split())
        ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
        c_key = EMUClientKey(ns_key, opts.mac)
        data_cnt = DataCounter(self.emu_c.conn, 'icmp_c_get_ping_stats')
        data_cnt.set_add_data(c_key=c_key)
        try:
            if opts.headers:
                data_cnt.get_counters_headers()
            elif opts.clear:
                self.emu_c.logger.pre_cmd("Clearing all counters :")
                data_cnt.clear_counters()
                self.emu_c.logger.post_cmd(True)
            else:
                data = data_cnt.get_counters(
                    opts.tables, opts.cnt_types, opts.zero)
                DataCounter.print_counters(
                    data, opts.verbose, opts.json, opts.yaml)
        except TRexError as err:
            text_tables.print_colored_line(
                '\n' + err.msg, 'yellow', buffer=sys.stdout)
示例#5
0
 def __icmp_start_ping_print(self, c_key, amount, pace, dst, timeout, pkt_size):
     res = False
     self.emu_c.logger.pre_cmd('Starting to ping : ')
     res = self.start_ping(c_key=c_key, amount=amount, pace=pace, dst=dst, timeout=timeout, pkt_size=pkt_size)
     self.emu_c.logger.post_cmd(res)
     if not res:
         text_tables.print_colored_line("Client is already pinging on in timeout.", 'yellow', buffer=sys.stdout)
     return res
示例#6
0
    def icmp_start_ping_wait(self, line):
        """ICMP start pinging and wait to finish (per client).\n"""
        parser = parsing_opts.gen_parser(self,
                                         "icmp_start_ping_wait",
                                         self.icmp_start_ping_wait.__doc__,
                                         parsing_opts.MAC_ADDRESS,
                                         parsing_opts.EMU_NS_GROUP,
                                         parsing_opts.EMU_ICMP_PING_PARAMS,
                                         parsing_opts.MONITOR_TYPE_VERBOSE
                                         )

        opts = parser.parse_args(line.split())
        ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
        c_key = EMUClientKey(ns_key, opts.mac)
        res = self.__icmp_start_ping_print(c_key=c_key, amount=opts.ping_amount, pace=opts.ping_pace, dst=opts.ping_dst,
                            timeout=opts.ping_timeout, pkt_size=opts.ping_size)
        amount = opts.ping_amount if opts.ping_amount is not None else 5  # default is 5 packets
        pace = opts.ping_pace if opts.ping_pace is not None else 1  # default is 1
        if res:
            try:
                while True:
                    time.sleep(min(1, 100/pace))
                    stats, err = self.get_ping_stats(c_key=c_key)
                    if err is None:
                        completed = stats['icmp_ping_stats']['requestsSent']
                        percent = completed / float(amount) * 100.0
                        dots = '.' * int(percent / 10)
                        text = "Progress: {0:.2f}% {1}".format(percent, dots)
                        sys.stdout.write('\r' + (' ' * 25) +
                                         '\r')  # clear line
                        sys.stdout.write(format_text(text, 'yellow'))
                        sys.stdout.flush()
                        if opts.verbose:
                            sys.stdout.flush()
                            stats_text = "\n"
                            for key, value in stats['icmp_ping_stats'].items():
                                stats_text += "{0} {1}: {2:.2f}\n".format(
                                    key, ' ' * (20 - len(key)), value)
                            sys.stdout.write(format_text(stats_text, 'green'))
                            sys.stdout.flush()
                        if completed == amount:
                            sys.stdout.write(format_text(
                                '\n\nCompleted\n\n', 'yellow'))
                            sys.stdout.flush()
                            break
                    else:
                        # Could get here if timeout is too short, but shouldn't happen.
                        break
            except KeyboardInterrupt:
                text_tables.print_colored_line(
                    '\nInterrupted by a keyboard signal (probably ctrl + c).', 'yellow', buffer=sys.stdout)
                self.emu_c.logger.pre_cmd('Attempting to stop ping :')
                res_stop = self.stop_ping(c_key=c_key)
                self.emu_c.logger.post_cmd(res_stop)
                return res_stop
示例#7
0
    def print_gen_data(self, data, title = None, empty_msg = 'empty'):

        if not data:
            text_tables.print_colored_line(empty_msg, 'yellow', buffer = sys.stdout)
            return

        if title is not None:
            text_tables.print_colored_line(title, 'yellow', buffer = sys.stdout)

        for one_data in data:
            print(conv_unknown_to_str(one_data))
        print('')  # new line for seperation 
示例#8
0
 def mdns_remove_hosts_line(self, line):
     """Remove hosts from mDNS client.\n"""
     parser = parsing_opts.gen_parser(self, "mdns_remove_hosts",
                                      self.mdns_remove_hosts_line.__doc__,
                                      parsing_opts.EMU_NS_GROUP,
                                      parsing_opts.MAC_ADDRESS,
                                      parsing_opts.MDNS_HOSTS_LIST)
     opts = parser.parse_args(line.split())
     ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
     c_key = EMUClientKey(ns_key, opts.mac)
     non_existing_hosts = self.add_remove_hosts(c_key=c_key,
                                                op=True,
                                                hosts=opts.hosts)
     if non_existing_hosts:
         msg = "Hosts: {} didn't exist.".format(listify(non_existing_hosts))
         text_tables.print_colored_line(msg, "yellow")
     self.logger.post_cmd(True)  # If we got here, it was successful
示例#9
0
    def icmp_stop_ping(self, line):
        """ICMP stop pinging (per client).\n"""
        parser = parsing_opts.gen_parser(self,
                                         "icmp_stop_ping",
                                         self.icmp_stop_ping.__doc__,
                                         parsing_opts.MAC_ADDRESS,
                                         parsing_opts.EMU_NS_GROUP,
                                         )

        opts = parser.parse_args(line.split())
        ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
        c_key = EMUClientKey(ns_key, opts.mac)
        self.emu_c.logger.pre_cmd('Attempting to stop ping :')
        res = self.stop_ping(c_key=c_key)
        self.emu_c.logger.post_cmd(res)
        if not res:
            text_tables.print_colored_line("No active pinging.", 'yellow', buffer=sys.stdout)
示例#10
0
    def icmp_ping(self, line):
        """ICMP ping utility (per client).\n"""
        parser = parsing_opts.gen_parser(self,
                                         "icmp_ping",
                                         self.icmp_ping.__doc__,
                                         parsing_opts.MAC_ADDRESS,
                                         parsing_opts.EMU_NS_GROUP,
                                         parsing_opts.EMU_ICMP_PING_PARAMS,
                                         )

        rows, cols = os.popen('stty size', 'r').read().split()
        if (int(rows) < self.MIN_ROWS) or (int(cols) < self.MIN_COLS):
            msg = "\nPing requires console screen size of at least {0}x{1}, current is {2}x{3}".format(self.MIN_COLS,
                                                                                                    self.MIN_ROWS,
                                                                                                    cols,
                                                                                                    rows)
            text_tables.print_colored_line(msg, 'red', buffer=sys.stdout)
            return

        opts = parser.parse_args(line.split())
        ns_key = EMUNamespaceKey(opts.port, opts.vlan, opts.tpid)
        c_key = EMUClientKey(ns_key, opts.mac)

        self.emu_c.logger.pre_cmd('Starting to ping : ')
        success, err = self.start_ping(c_key=c_key, amount=opts.ping_amount, pace=opts.ping_pace, dst=opts.ping_dst,
                                       payload_size=opts.ping_size, timeout=1)
        if err is not None:
            self.emu_c.logger.post_cmd(False)
            text_tables.print_colored_line(err.msg, 'yellow', buffer=sys.stdout)
        else:
            self.emu_c.logger.post_cmd(True)
            amount = opts.ping_amount if opts.ping_amount is not None else 5  # default is 5 packets
            try:
                while True:
                    time.sleep(1) # Don't get statistics too often as RPC requests might overload the Emu Server.
                    stats, err = self.get_ping_stats(c_key=c_key)
                    if err is None:
                        stats = stats['icmp_ping_stats']
                        sent = stats['requestsSent']
                        rcv = stats['repliesInOrder']
                        percent = sent / float(amount) * 100.0
                        # the latency from the server is in usec
                        min_lat_msec = float(stats['minLatency']) / 1000
                        max_lat_msec = float(stats['maxLatency']) / 1000
                        avg_lat_msec = float(stats['avgLatency']) / 1000
                        err = int(stats['repliesOutOfOrder']) + int(stats['repliesMalformedPkt']) + \
                              int(stats['repliesBadLatency']) + int(stats['repliesBadIdentifier']) + \
                              int (stats['dstUnreachable'])

                        text = "Progress: {0:.2f}%, Sent: {1}/{2}, Rcv: {3}/{2}, Err: {4}/{2}, RTT min/avg/max = {5:.2f}/{6:.2f}/{7:.2f} ms" \
                                                            .format(percent, sent, amount, rcv, err, min_lat_msec, avg_lat_msec, max_lat_msec)

                        sys.stdout.write('\r' + (' ' * self.MIN_COLS) +'\r')  # clear line
                        sys.stdout.write(format_text(text, 'yellow'))
                        sys.stdout.flush()
                        if sent == amount:
                            sys.stdout.write(format_text('\n\nCompleted\n\n', 'yellow'))
                            sys.stdout.flush()
                            break
                    else:
                        # Trying to collect stats after completion.
                        break
            except KeyboardInterrupt:
                text_tables.print_colored_line('\nInterrupted by a keyboard signal (probably ctrl + c).', 'yellow', buffer=sys.stdout)
                self.emu_c.logger.pre_cmd('Attempting to stop ping : ')
                success, err = self.stop_ping(c_key=c_key)
                if err is None:
                    self.emu_c.logger.post_cmd(True)
                else:
                    self.emu_c.logger.post_cmd(False)
                    text_tables.print_colored_line(err.msg, 'yellow', buffer=sys.stdout)