def connect_command(connect): """ Connect to ssh session and give control to user. """ from ssh_connection import CONNECTIONS if type(connect) == int: name, session = CONNECTIONS[connect].items()[0] print GREEN("Connecting to session[%s]" % name) session.session.interact() else: for connection in CONNECTIONS: for name, session in connection.items(): if name == connect: print GREEN("Connecting to session[%s]" % name) session.session.interact()
def _connect_host(self, dut_id=0): """ Create connection to assigned crb, parameter dut_id will be used in parallel_lock thus can assure isolated locks for each crb. Parallel ssh connections are limited to MaxStartups option in SSHD configuration file. By default concurrent number is 10, so default threads number is limited to 8 which less than 10. Lock number can be modified along with MaxStartups value. """ try: self.session = pxssh.pxssh() if ':' in self.host: self.ip = self.host.split(':')[0] self.port = int(self.host.split(':')[1]) self.session.login(self.ip, self.username, self.password, original_prompt='[$#>]', port=self.port, login_timeout=20) else: self.session.login(self.host, self.username, self.password, original_prompt='[$#>]') self.send_expect('stty -echo', '#') self.send_expect('stty columns 1000', "#") except Exception as e: print RED(e) if getattr(self, 'port', None): suggestion = "\nSuggession: Check if the firewall on [ %s ] " % \ self.ip + "is stopped\n" print GREEN(suggestion) raise SSHConnectionException(self.host)
def __init__(self, host, username, password): self.magic_prompt = "MAGIC PROMPT" try: self.session = pxssh.pxssh() self.host = host self.username = username self.password = password if ':' in host: self.ip = host.split(':')[0] self.port = int(host.split(':')[1]) self.session.login(self.ip, self.username, self.password, original_prompt='[$#>]', port=self.port, login_timeout=20) else: self.session.login(self.host, self.username, self.password, original_prompt='[$#>]') self.send_expect('stty -echo', '# ', timeout=2) except Exception, e: print RED(e) if getattr(self, 'port', None): suggestion = "\nSuggession: Check if the fireware on [ %s ] " % \ self.ip + "is stoped\n" print GREEN(suggestion) raise SSHConnectionException(host)
def parallel_transmit_ptks(self, send_f=None, intf='', pkts=[], interval=0.01): """ Callable function for parallel processes """ print GREEN( "Transmitting and sniffing packets, please wait few minutes...") send_f(intf=intf, pkts=pkts, interval=interval)
def check_pf_vf_link_status(self, session, intf): """ sometimes pf/vf will up abnormal, retry 5 times """ for i in range(5): # down-up get new mac form pf. # because dpdk pf will give an random mac when dpdk pf restart. session.send_expect("ifconfig %s down" % intf, "#") out = session.send_expect("ifconfig %s up" % intf, "#") # SIOCSIFFLAGS: Network is down # i think the pf link abnormal if "Network is down" in out: print GREEN(out) print GREEN("Try again") self.vm0_dut.restore_interfaces_linux() else: out = session.send_expect("ethtool %s" % intf, "#") if "Link detected: yes" in out: return True time.sleep(1) return False
def ping4(self, session, intf, ipv4): """ using seesion , ping -I $intf $ip sometimes it failed, so we try 5 times. """ for i in range(5): out = session.send_expect( "ping -w 5 -c 5 -A -I %s %s" % (intf, ipv4), "# ") if '64 bytes from' not in out: print GREEN("%s ping %s failed, retry" % (intf, ipv4)) else: return True return False
def __init__(self, host, domain_id, bus_id, devfun_id): super(BoulderRapid, self).__init__(host, domain_id, bus_id, devfun_id) self.tp_path = "~" self.sec_port = False self.host = host # load port config portconf = PortConf(PORTCONF) portconf.load_ports_config(host.crb['IP']) pci_addr = ':'.join((domain_id, bus_id, devfun_id)) if not portconf.check_port_available(pci_addr): raise PortConfigParseException("BoulderRapid must configured") port_cfg = portconf.get_ports_config()[pci_addr] # secondary port do not need reinitialize if 'sec_port' in port_cfg.keys(): print GREEN("Skip init second port test point session") if 'first_port' not in port_cfg.keys(): raise PortConfigParseException( "BoulderRapid second port must configure first port") # find net_device by pci_addr first_addr = port_cfg['first_port'] port_info = self.host.get_port_info(first_addr) if port_info is None: raise PortConfigParseException( "BoulderRapid first port not found") # get addtional session netdev = port_info['port'] self.ctrl_crb = netdev.get_control() self.sec_port = True return if 'tp_ip' not in port_cfg.keys(): raise PortConfigParseException( "BoulderRapid must configure test point ip") if 'passwd' not in port_cfg.keys(): raise PortConfigParseException( "BoulderRapid must configure host password") crb = {} crb['IP'] = port_cfg['tp_ip'] crb['pass'] = port_cfg['passwd'] if 'tp_path' in port_cfg.keys(): self.tp_path = port_cfg['tp_path'] # create addtional session self.ctrl_crb = CtrlCrb(crb)
def main(): config_done = False scan_suites() scan_executions() while not config_done: config_option = { 'prompt': 'Choose preparation steps for running dts', 'type': 'choice', 'help': 'Running DTS request preparation few ' + 'configurations', 'options': [ 'DUT&Tester crb', 'execution plan', 'ixia port for performance', 'port config for manually assign ports', 'start running DTS' ], 'default': def_opt } opt = Option(**config_option) choice = opt.parse_input() index = opt.choice if index == 0: config_crbs() write_crbs_cfg() elif index == 1: if not config_execution(): continue write_exec_cfg() elif index == 2: if not config_ixia(): continue write_ixia_cfg() elif index == 3: if not config_ports(): continue write_ports_cfg() elif index == 4: config_done = True run_dts() print GREEN("Waiting for preparation ready...") time.sleep(2) get_next_opt()
def start_testpoint(self): """ Before any execution, must enable test point first """ if self.sec_port: print GREEN("Skip start second port testpoint") return self.ctrl_crb.send_expect("cd %s" % self.tp_path, "# ") if self.tp_path != "~": command = './' + TP_BINARY else: command = TP_BINARY self.ctrl_crb.send_expect("%s" % command, "<0>%", 120) for rule in FUNC_RULES: self.ctrl_crb.send_expect("%s" % rule, "<0>%")
def __init__(self, host, username, password, ssh_key=None): self.magic_prompt = "MAGIC PROMPT" try: SSHPexpect.connections += 1 ssh_options = {} path = '{}/ssh_{}_{}.log'.format(settings.FOLDERS['Output'], host, SSHPexpect.connections) self.logfile = open(path, 'w') self.session = pxssh.pxssh(logfile=self.logfile) self.host = host self.username = username self.password = password self.ssh_key = ssh_key if ':' in host: self.ip = host.split(':')[0] self.port = int(host.split(':')[1]) self.session.login(self.ip, self.username, self.password, original_prompt='[$#>]', port=self.port, login_timeout=20, ssh_key=ssh_key) else: self.session.login(self.host, self.username, self.password, original_prompt='[$#>]', ssh_key=ssh_key) self.send_expect("PS1='# '", '# ') self.send_expect('stty -echo', '# ', timeout=2) self.session.sendline("sudo su") self.session.expect('#') self.send_expect("PS1='# '", '# ') except Exception, e: print RED(e) if getattr(self, 'port', None): suggestion = "\nSuggession: Check if the fireware on [ %s ] " % \ self.ip + "is stoped\n" print GREEN(suggestion) raise SSHConnectionException(host)
def start_testpoint(self): """ Before any execution, must enable test point first """ if self.sec_port: print GREEN("Skip start second port testpoint") return self.ctrl_crb.send_expect("cd %s" % self.tp_path, "# ") if self.tp_path != "~": command = './' + TP_BINARY else: command = TP_BINARY # special commands for tp 4.1.6 command += " --api.platform.config.switch.0.uioDevName:text:/dev/uio0" command += " --api.platform.pktInterface:text:pti" self.ctrl_crb.send_expect("%s" % command, "<0>%", 120) for rule in FUNC_RULES: self.ctrl_crb.send_expect("%s" % rule, "<0>%")
def check_random_pkts(self, portList, pktnum=2000, interval=0.01, allow_miss=True, seq_check=False, params=None): """ Send several random packets and check rx packets matched """ # load functions in packet module module = __import__("packet") pkt_c = getattr(module, "Packet") send_f = getattr(module, "send_packets") sniff_f = getattr(module, "sniff_packets") load_f = getattr(module, "load_sniff_packets") compare_f = getattr(module, "compare_pktload") strip_f = getattr(module, "strip_pktload") save_f = getattr(module, "save_packets") tx_pkts = {} rx_inst = {} # packet type random between tcp/udp/ipv6 random_type = ['TCP', 'UDP', 'IPv6_TCP', 'IPv6_UDP'] pkt_minlen = {'TCP': 64, 'UDP': 64, 'IPv6_TCP': 74, 'IPv6_UDP': 64} # at least wait 2 seconds timeout = int(pktnum * (interval + 0.01)) + 2 for txport, rxport in portList: pkts = [] txIntf = self.get_interface(txport) rxIntf = self.get_interface(rxport) print GREEN( "Preparing transmit packets, please wait few minutes...") for num in range(pktnum): # chose random packet pkt_type = random.choice(random_type) pkt = pkt_c(pkt_type=pkt_type, pkt_len=random.randint(pkt_minlen[pkt_type], 1514), ran_payload=True) # config packet if has parameters if params and len(portList) == len(params): for param in params: layer, config = param pkt.config_layer(layer, config) # hardcode src/dst port for some protocal may cause issue if "TCP" in pkt_type: pkt.config_layer('tcp', {'src': 65535, 'dst': 65535}) else: pkt.config_layer('udp', {'src': 65535, 'dst': 65535}) # sequence saved in layer3 source ip if "IPv6" in pkt_type: ip_str = convert_int2ip(num, 6) pkt.config_layer('ipv6', {'src': ip_str}) else: ip_str = convert_int2ip(num, 4) pkt.config_layer('ipv4', {'src': ip_str}) pkts.append(pkt) tx_pkts[txport] = pkts # send and sniff packets save_f(pkts=pkts, filename="/tmp/%s_tx.pcap" % txIntf) inst = sniff_f(intf=rxIntf, count=pktnum, timeout=timeout) rx_inst[rxport] = inst # Transmit packet simultaneously processes = [] for txport, _ in portList: txIntf = self.get_interface(txport) processes.append( Process(target=self.parallel_transmit_ptks, args=(send_f, txIntf, tx_pkts[txport], interval))) for transmit_proc in processes: transmit_proc.start() for transmit_proc in processes: transmit_proc.join() # Verify all packets prev_id = -1 for txport, rxport in portList: recv_pkts = load_f(rx_inst[rxport]) # only report when recevied number not matched if len(tx_pkts[txport]) > len(recv_pkts): print ("Pkt number not matched,%d sent and %d received\n" \ % (len(tx_pkts[txport]), len(recv_pkts))) if allow_miss is False: return False # check each received packet content print GREEN( "Comparing sniffed packets, please wait few minutes...") for idx in range(len(recv_pkts)): try: l3_type = recv_pkts[idx].strip_element_layer2('type') sip = recv_pkts[idx].strip_element_layer3('src') except: continue # ipv4 packet if l3_type == 2048: t_idx = convert_ip2int(sip, 4) # ipv6 packet elif l3_type == 34525: t_idx = convert_ip2int(sip, 6) else: continue if seq_check: if t_idx <= prev_id: print "Packet %d sequence not correct" % t_idx return False else: prev_id = t_idx if compare_f(tx_pkts[txport][t_idx], recv_pkts[idx], "L4") is False: print "Pkt recevied index %d not match original " \ "index %d" % (idx, t_idx) print "Sent: %s" % strip_f(tx_pkts[txport][t_idx], "L4") print "Recv: %s" % strip_f(recv_pkts[idx], "L4") return False return True