Пример #1
0
 def reset(self):
     self.sendline("reboot")
     self.expect(["going down", "disconnected"])
     try:
         self.expect(self.prompt, timeout=10)
     except Exception:
         pass
     time.sleep(15)  # Wait for the network to go down.
     for i in range(0, 20):
         try:
             bft_pexpect_helper.spawn("ping -w 1 -c 1 " + self.name).expect(
                 "64 bytes", timeout=1)
         except Exception:
             logger.error(self.name + " not up yet, after %s seconds." %
                          (i + 15))
         else:
             logger.info(
                 "%s is back after %s seconds, waiting for network daemons to spawn."
                 % (self.name, i + 14))
             time.sleep(15)
             break
     self.__init__(
         self.name,
         self.color,
         self.output,
         self.username,
         self.password,
         self.port,
         reboot=False,
     )
Пример #2
0
 def reset(self):
     self.sendline('reboot')
     self.expect(['going down', 'disconnected'])
     try:
         self.expect(self.prompt, timeout=10)
     except:
         pass
     time.sleep(15)  # Wait for the network to go down.
     for i in range(0, 20):
         try:
             bft_pexpect_helper.spawn('ping -w 1 -c 1 ' + self.name).expect(
                 '64 bytes', timeout=1)
         except:
             print(self.name + " not up yet, after %s seconds." % (i + 15))
         else:
             print(
                 "%s is back after %s seconds, waiting for network daemons to spawn."
                 % (self.name, i + 14))
             time.sleep(15)
             break
     self.__init__(self.name,
                   self.color,
                   self.output,
                   self.username,
                   self.password,
                   self.port,
                   reboot=False)
Пример #3
0
 def _connect(self):
     self.pcon = bft_pexpect_helper.spawn("telnet %s" % self.ip_address)
     self.pcon.expect("User Name :")
     self.pcon.send(self.username + "\r\n")
     self.pcon.expect("Password  :"******"\r\n")
     self.pcon.expect("> ")
Пример #4
0
        def temp_download(url):
            """Download the image to the temp folder over the QEMU device.

            :param url: URL where the file is location (URL path of the file to be downloaded), defaults to None
            :type url: string
            :returns: The filename of the downloaded file.
            :rtype: string
            """
            dl_console = bft_pexpect_helper.spawn("bash --noprofile --norc")
            dl_console.sendline('export PS1="prompt>>"')
            dl_console.expect_exact("prompt>>")
            dl_console.sendline('mktemp')
            dl_console.expect('/tmp/tmp.*')
            fname = dl_console.match.group(0).strip()
            dl_console.expect_exact("prompt>>")
            self.cleanup_files.append(fname)
            atexit.register(self.run_cleanup_cmd)
            dl_console.logfile_read = sys.stdout
            print("Temp downloaded file = %s" % url)
            dl_console.sendline("curl -n -L -k '%s' > %s" % (url, fname))
            dl_console.expect_exact("prompt>>", timeout=500)
            dl_console.logfile_read = None
            dl_console.sendline('exit')
            dl_console.expect(pexpect.EOF)
            return fname
Пример #5
0
 def run_cleanup_cmd(self):
     sys.stdout.write("Running cleanup_cmd on %s..." % self.name)
     sys.stdout.flush()
     cc = bft_pexpect_helper.spawn(command='bash',
                                   args=['-c', self.cleanup_cmd],
                                   env=env)
     cc.expect(pexpect.EOF, timeout=120)
     print("cleanup_cmd done.")
Пример #6
0
 def _connect(self):
     self.pcon = bft_pexpect_helper.spawn("telnet %s" % self.ip_address)
     self.pcon.expect(r"Login for PX\d CLI")
     self.pcon.expect("Username:"******"Password:"******"Welcome to PX\d CLI!")
     self.pcon.expect("# ")
Пример #7
0
 def run_cleanup_cmd(self):
     """To clear the buffer."""
     sys.stdout.write("Running cleanup_cmd on %s..." % self.name)
     sys.stdout.flush()
     cc = bft_pexpect_helper.spawn(command="bash",
                                   args=["-c", self.cleanup_cmd],
                                   env=self.dev.env)
     cc.expect(pexpect.EOF, timeout=120)
     print("cleanup_cmd done.")
Пример #8
0
    def do_login(self):
        pcon = bft_pexpect_helper.spawn('telnet %s' % self.ip_address)
        pcon.expect('Login for PX\d CLI')
        pcon.expect('Username:'******'Password:'******'Welcome to PX\d CLI!')
        pcon.expect('# ')

        self.pcon = pcon
Пример #9
0
 def __connect(self):
     pcon = bft_pexpect_helper.spawn('telnet %s' % self.ip_address)
     pcon.expect('Sentry Switched CDU Version', timeout=15)
     pcon.expect('Username:'******'Password:'******'Switched CDU:', 'Critical Alert'])
     if i == 0:
         return pcon
     else:
         print("\nCritical failure in %s, skipping PDU\n" % self.power_ip)
         raise Exception("critical failure in %s" % self.power_ip)
Пример #10
0
 def _connect(self):
     pcon = bft_pexpect_helper.spawn("telnet %s" % self.ip_address)
     pcon.expect("Sentry Switched CDU Version", timeout=15)
     pcon.expect("Username:"******"Password:"******"Switched CDU:", "Critical Alert"])
     if i == 0:
         self.pcon = pcon
     else:
         logger.error("\nCritical failure in %s, skipping PDU\n" %
                      self.ip_address)
         raise Exception("critical failure in %s" % self.ip_address)
Пример #11
0
 def reset(self):
     '''Connect, login, and send commands to reset power on an outlet.'''
     pcon = bft_pexpect_helper.spawn('telnet %s' % self.ip_address)
     pcon.expect("User Name :")
     pcon.send(self.username + "\r\n")
     pcon.expect("Password  :"******"\r\n")
     pcon.expect("> ")
     pcon.send("1" + "\r\n")
     pcon.expect("> ")
     pcon.send("2" + "\r\n")
     pcon.expect("> ")
     pcon.send("1" + "\r\n")
     pcon.expect("> ")
     pcon.send(self.outlet + "\r\n")
     pcon.expect("> ")
     pcon.send("1" + "\r\n")
     pcon.expect("> ")
     pcon.send("6" + "\r\n")
     pcon.send("YES")
     pcon.send("" + "\r\n")
     pcon.expect("> ")
Пример #12
0
    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        name = kwargs.pop('name', None)
        ipaddr = kwargs.pop('ipaddr', None)
        color = kwargs.pop('color', 'black')
        username = kwargs.pop('username', 'root')
        password = kwargs.pop('password', 'bigfoot1')
        port = kwargs.pop('port', '22')
        output = kwargs.pop('output', sys.stdout)
        reboot = kwargs.pop('reboot', False)
        location = kwargs.pop('location', None)
        pre_cmd_host = kwargs.pop('pre_cmd_host', None)
        cmd = kwargs.pop('cmd', None)
        post_cmd_host = kwargs.pop('post_cmd_host', None)
        post_cmd = kwargs.pop('post_cmd', None)
        cleanup_cmd = kwargs.pop('cleanup_cmd', None)
        lan_network = ipaddress.IPv4Interface(
            six.text_type(kwargs.pop('lan_network', "192.168.1.0/24"))).network
        lan_gateway = ipaddress.IPv4Interface(
            six.text_type(kwargs.pop('lan_gateway', "192.168.1.1/24"))).ip

        self.http_proxy = kwargs.pop('http_proxy', None)

        if pre_cmd_host is not None:
            sys.stdout.write("\tRunning pre_cmd_host.... ")
            sys.stdout.flush()
            phc = bft_pexpect_helper.spawn(command='bash',
                                           args=['-c', pre_cmd_host],
                                           env=env)
            phc.expect(pexpect.EOF, timeout=120)
            print("\tpre_cmd_host done")

        if ipaddr is not None:
            bft_pexpect_helper.spawn.__init__(
                self,
                command="ssh",
                args=[
                    '%s@%s' % (username, ipaddr), '-p', port, '-o',
                    'StrictHostKeyChecking=no', '-o',
                    'UserKnownHostsFile=/dev/null', '-o',
                    'ServerAliveInterval=60', '-o', 'ServerAliveCountMax=5'
                ])

            self.ipaddr = ipaddr

        if cleanup_cmd is not None:
            self.cleanup_cmd = cleanup_cmd
            atexit.register(self.run_cleanup_cmd)

        if cmd is not None:
            sys.stdout.write("\tRunning cmd.... ")
            sys.stdout.flush()
            bft_pexpect_helper.spawn.__init__(self,
                                              command="bash",
                                              args=['-c', cmd],
                                              env=env)
            self.ipaddr = None
            print("\tcmd done")

        self.name = name
        self.color = color
        self.output = output
        self.username = username
        if username != "root":
            self.prompt.append('%s\\@.*:.*$' % username)
        self.password = password
        self.port = port
        self.location = location
        self.lan_network = lan_network
        self.lan_gateway = lan_gateway
        self.tftp_device = self

        self.check_connection(username, name, password)

        # attempts to fix the cli colums size
        self.set_cli_size(200)

        # we need to pick a non-conflicting private network here
        # also we want it to be consistant and not random for a particular
        # board
        if self.gw is None:
            if (lan_gateway - lan_network.num_addresses).is_private:
                self.gw = lan_gateway - lan_network.num_addresses
            else:
                self.gw = lan_gateway + lan_network.num_addresses

        self.gw_ng = ipaddress.IPv4Interface(
            six.text_type(str(self.gw) + '/' + str(lan_network.prefixlen)))
        self.nw = self.gw_ng.network
        self.gw_prefixlen = self.nw.prefixlen

        # override above values if set in wan options
        if 'options' in kwargs:
            options = [x.strip() for x in kwargs['options'].split(',')]
            for opt in options:
                if opt.startswith('wan-static-ip:'):
                    value = six.text_type(opt.replace('wan-static-ip:', ''))
                    if '/' not in value:
                        value = value + (u'/24')
                    self.gw_ng = ipaddress.IPv4Interface(value)
                    self.nw = self.gw_ng.network
                    self.gw_prefixlen = self.nw._prefixlen
                    self.gw = self.gw_ng.ip
                    self.static_ip = True
                if opt.startswith('wan-static-ipv6:'):
                    ipv6_address = six.text_type(
                        opt.replace('wan-static-ipv6:', ''))
                    if "/" not in opt:
                        ipv6_address += "/%s" % six.text_type(
                            str(self.ipv6_prefix))
                    self.ipv6_interface = ipaddress.IPv6Interface(ipv6_address)
                    self.ipv6_prefix = self.ipv6_interface._prefixlen
                    self.gwv6 = self.ipv6_interface.ip
                if opt.startswith('wan-static-route:'):
                    self.static_route = opt.replace('wan-static-route:',
                                                    '').replace('-', ' via ')
                # TODO: remove wan-static-route at some point above
                if opt.startswith('static-route:'):
                    self.static_route = opt.replace('static-route:',
                                                    '').replace('-', ' via ')
                if opt == 'wan-dhcp-client':
                    self.wan_dhcp = True
                if opt == 'wan-no-eth0':
                    self.wan_no_eth0 = True
                if opt == 'wan-no-dhcp-sever':
                    self.wan_dhcp_server = False
                if opt == 'wan-dhcp-client-v6':
                    self.wan_dhcpv6 = True
                if opt.startswith('mgmt-dns:'):
                    value = six.text_type(opt.replace('mgmt-dns:', ''))
                    self.mgmt_dns = ipaddress.IPv4Interface(value).ip
                else:
                    self.mgmt_dns = "8.8.8.8"

        if ipaddr is None:
            self.sendline('hostname')
            self.expect('hostname')
            self.expect(self.prompt)
            ipaddr = self.ipaddr = self.before.strip()

        self.sendline('alias mgmt')
        idx = self.expect(
            ['alias mgmt=', 'alias: mgmt: not found', pexpect.TIMEOUT],
            timeout=10)
        if idx == 0:
            self.expect(self.prompt)
            self.shim = "mgmt"
            self.sendline('alias apt="mgmt apt"; alias apt-get="mgmt apt-get"')
            self.expect_exact(
                'alias apt="mgmt apt"; alias apt-get="mgmt apt-get"')
        self.expect(self.prompt)

        self.print_connected_console_msg(ipaddr, port, color, name)

        if post_cmd_host is not None:
            sys.stdout.write("\tRunning post_cmd_host.... ")
            sys.stdout.flush()
            phc = bft_pexpect_helper.spawn(command='bash',
                                           args=['-c', post_cmd_host],
                                           env=env)
            i = phc.expect([pexpect.EOF, pexpect.TIMEOUT, 'password'])
            if i > 0:
                print("\tpost_cmd_host did not complete, it likely failed\n")
            else:
                print("\tpost_cmd_host done")

        if post_cmd is not None:
            sys.stdout.write("\tRunning post_cmd.... ")
            sys.stdout.flush()
            env_prefix = ""
            for k, v in env.items():
                env_prefix += "export %s=%s; " % (k, v)

            self.sendline(env_prefix + post_cmd)
            self.expect(self.prompt)
            print("\tpost_cmd done")

        if reboot:
            self.reset()

        self.logfile_read = output
Пример #13
0
 def _connect(self):
     self.pcon = bft_pexpect_helper.spawn(
         f"telnet {self.ip_address} {self.conn_port}")
     self.pcon.expect("100 HELLO 00000000 - KSHELL V1.5")
     self.pcon.sendline(f"login {self.username} {self.password}")
     self.pcon.expect("250 OK")
Пример #14
0
    def __init__(self, *args, **kwargs):
        """Instance initialization."""
        self.args = args
        self.kwargs = kwargs
        name = kwargs.pop("name", None)
        ipaddr = kwargs.pop("ipaddr", None)
        color = kwargs.pop("color", "black")
        username = kwargs.pop("username", "root")
        password = kwargs.pop("password", "bigfoot1")
        port = kwargs.pop("port", "22")
        output = kwargs.pop("output", sys.stdout)
        reboot = kwargs.pop("reboot", False)
        location = kwargs.pop("location", None)
        self.dev_array = kwargs.pop("dev_array", None)
        pre_cmd_host = kwargs.pop("pre_cmd_host", None)
        cmd = kwargs.pop("cmd", None)
        post_cmd_host = kwargs.pop("post_cmd_host", None)
        post_cmd = kwargs.pop("post_cmd", None)
        cleanup_cmd = kwargs.pop("cleanup_cmd", None)
        lan_network = ipaddress.IPv4Interface(
            six.text_type(kwargs.pop("lan_network", "192.168.1.0/24"))).network
        lan_gateway = ipaddress.IPv4Interface(
            six.text_type(kwargs.pop("lan_gateway", "192.168.1.1/24"))).ip

        self.http_proxy = kwargs.pop("http_proxy", ipaddr + ':8080')

        if pre_cmd_host is not None:
            sys.stdout.write("\tRunning pre_cmd_host.... ")
            sys.stdout.flush()
            phc = bft_pexpect_helper.spawn(command="bash",
                                           args=["-c", pre_cmd_host],
                                           env=self.dev.env)
            phc.expect(pexpect.EOF, timeout=120)
            print("\tpre_cmd_host done")

        self.legacy_add = False
        # introducing a hack till json schema does not get updated
        if not self.dev_array:
            self.legacy_add = True
            arr_names = {"lan": "lan_clients", "wan": "wan_clients"}
            for k, v in arr_names.items():
                if k in name:
                    self.dev_array = v

        if ipaddr is not None:
            bft_pexpect_helper.spawn.__init__(
                self,
                command="ssh",
                args=[
                    "%s@%s" % (username, ipaddr),
                    "-p",
                    port,
                    "-o",
                    "StrictHostKeyChecking=no",
                    "-o",
                    "UserKnownHostsFile=/dev/null",
                    "-o",
                    "ServerAliveInterval=60",
                    "-o",
                    "ServerAliveCountMax=5",
                ],
            )

            self.ipaddr = ipaddr

        if cleanup_cmd is not None:
            self.cleanup_cmd = cleanup_cmd
            atexit.register(self.run_cleanup_cmd)

        if cmd is not None:
            sys.stdout.write("\tRunning cmd.... ")
            sys.stdout.flush()
            bft_pexpect_helper.spawn.__init__(self,
                                              command="bash",
                                              args=["-c", cmd],
                                              env=self.dev.env)
            self.ipaddr = None
            print("\tcmd done")

        self.name = name
        self.color = color
        self.output = output
        self.username = username
        if username != "root":
            self.prompt.append("%s\\@.*:.*$" % username)
        self.password = password
        self.port = port
        self.location = location
        self.lan_network = lan_network
        self.lan_gateway = lan_gateway
        self.tftp_device = self
        self.dante = False

        self.check_connection(username, name, password)

        # attempts to fix the cli colums size
        self.set_cli_size(200)

        # we need to pick a non-conflicting private network here
        # also we want it to be consistant and not random for a particular
        # board
        if self.gw is None:
            if (lan_gateway - lan_network.num_addresses).is_private:
                self.gw = lan_gateway - lan_network.num_addresses
            else:
                self.gw = lan_gateway + lan_network.num_addresses

        self.gw_ng = ipaddress.IPv4Interface(
            six.text_type(str(self.gw) + "/" + str(lan_network.prefixlen)))
        self.nw = self.gw_ng.network
        self.gw_prefixlen = self.nw.prefixlen

        # override above values if set in wan options
        if "options" in kwargs:
            options = [x.strip() for x in kwargs["options"].split(",")]
            for opt in options:
                if opt.startswith("wan-static-ip:"):
                    value = six.text_type(opt.replace("wan-static-ip:", ""))
                    if "/" not in value:
                        value = value + (u"/24")
                    self.gw_ng = ipaddress.IPv4Interface(value)
                    self.nw = self.gw_ng.network
                    self.gw_prefixlen = self.nw._prefixlen
                    self.gw = self.gw_ng.ip
                    self.static_ip = True
                if opt.startswith("wan-static-ipv6:"):
                    ipv6_address = six.text_type(
                        opt.replace("wan-static-ipv6:", ""))
                    if "/" not in opt:
                        ipv6_address += "/%s" % six.text_type(
                            str(self.ipv6_prefix))
                    self.ipv6_interface = ipaddress.IPv6Interface(ipv6_address)
                    self.ipv6_prefix = self.ipv6_interface._prefixlen
                    self.gwv6 = self.ipv6_interface.ip
                if opt.startswith("wan-static-route:"):
                    self.static_route = opt.replace("wan-static-route:",
                                                    "").replace("-", " via ")
                # TODO: remove wan-static-route at some point above
                if opt.startswith("static-route:"):
                    self.static_route = opt.replace("static-route:",
                                                    "").replace("-", " via ")
                if opt == "wan-dhcp-client":
                    self.wan_dhcp = True
                if opt == "wan-no-eth0":
                    self.wan_no_eth0 = True
                if opt == "wan-no-dhcp-sever":
                    self.wan_dhcp_server = False
                if opt == "wan-dhcp-client-v6":
                    self.wan_dhcpv6 = True
                if opt.startswith("mgmt-dns:"):
                    value = six.text_type(opt.replace("mgmt-dns:", ""))
                    self.mgmt_dns = ipaddress.IPv4Interface(value).ip
                else:
                    self.mgmt_dns = "8.8.8.8"
                if opt == 'dante':
                    self.dante = True

        if ipaddr is None:
            self.sendline("hostname")
            self.expect("hostname")
            self.expect(self.prompt)
            ipaddr = self.ipaddr = self.before.strip()

        self.sendline("alias mgmt")
        idx = self.expect(
            ["alias mgmt=", "alias: mgmt: not found", pexpect.TIMEOUT],
            timeout=10)
        if idx == 0:
            self.expect(self.prompt)
            self.shim = "mgmt"
            self.sendline('alias apt="mgmt apt"; alias apt-get="mgmt apt-get"')
            self.expect_exact(
                'alias apt="mgmt apt"; alias apt-get="mgmt apt-get"')
        self.expect(self.prompt)

        self.print_connected_console_msg(ipaddr, port, color, name)

        if post_cmd_host is not None:
            sys.stdout.write("\tRunning post_cmd_host.... ")
            sys.stdout.flush()
            phc = bft_pexpect_helper.spawn(command="bash",
                                           args=["-c", post_cmd_host],
                                           env=self.dev.env)
            i = phc.expect([pexpect.EOF, pexpect.TIMEOUT, "password"])
            if i > 0:
                print("\tpost_cmd_host did not complete, it likely failed\n")
            else:
                print("\tpost_cmd_host done")

        if post_cmd is not None:
            sys.stdout.write("\tRunning post_cmd.... ")
            sys.stdout.flush()
            env_prefix = ""
            for k, v in self.dev.env.items():
                env_prefix += "export %s=%s; " % (k, v)

            self.sendline(env_prefix + post_cmd)
            self.expect(self.prompt)
            print("\tpost_cmd done")

        if reboot:
            self.reset()

        self.logfile_read = output
Пример #15
0
    def parse_device_options(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.username = kwargs.pop("username", "root")
        self.password = kwargs.pop("password", "bigfoot1")
        self.output = kwargs.pop("output", sys.stdout)
        self.dev_array = kwargs.pop("dev_array", None)
        name = kwargs.pop("name", None)
        ipaddr = kwargs.pop("ipaddr", None)
        color = kwargs.pop("color", "black")
        port = kwargs.pop("port", "22")
        reboot = kwargs.pop("reboot", False)
        location = kwargs.pop("location", None)
        cmd = kwargs.pop("cmd", None)
        pre_cmd_host = kwargs.pop("pre_cmd_host", None)
        post_cmd_host = kwargs.pop("post_cmd_host", None)
        post_cmd = kwargs.pop("post_cmd", None)
        cleanup_cmd = kwargs.pop("cleanup_cmd", None)

        self.http_proxy = kwargs.pop("http_proxy", ipaddr + ":8080")
        self.tftp_device = self
        self.dante = False
        self.legacy_add = False
        if "options" in kwargs:
            for opt in kwargs["options"].split(","):
                opt = opt.strip()
                if opt == "dante":
                    self.dante = True
                elif opt == "wan-dhcp-client-v6":
                    self.wan_dhcpv6 = True
                elif opt == "wan-no-dhcp-server":
                    self.wan_dhcp_server = False
                elif opt == "wan-no-eth0":
                    self.wan_no_eth0 = True
                elif opt == "wan-dhcp-client":
                    self.wan_dhcp = True
                elif opt.startswith("wan-static-ipv6:"):
                    ipv6_address = six.text_type(  # noqa : F821
                        opt.replace("wan-static-ipv6:", ""))
                    if "/" not in opt:
                        ipv6_address += "/%s" % six.text_type(  # noqa : F821
                            str(self.ipv6_prefix))
                    self.ipv6_interface = ipaddress.IPv6Interface(  # noqa : F821
                        ipv6_address)
                    self.ipv6_prefix = self.ipv6_interface._prefixlen
                    self.gwv6 = self.ipv6_interface.ip
                elif opt.startswith("wan-static-ip:"):
                    value = six.text_type(  # noqa : F401
                        opt.replace("wan-static-ip:", ""))
                    if "/" not in value:
                        value = value + ("/24")
                    self.gw_ng = ipaddress.IPv4Interface(value)  # noqa : F821
                    self.nw = self.gw_ng.network
                    self.gw_prefixlen = self.nw._prefixlen
                    self.gw = self.gw_ng.ip
                    self.static_ip = True
                # TODO: remove wan-static-route at some point above
                elif opt.startswith("static-route:"):
                    self.static_route = opt.replace("static-route:",
                                                    "").replace("-", " via ")
                elif opt.startswith("wan-static-route:"):
                    self.static_route = opt.replace("wan-static-route:",
                                                    "").replace("-", " via ")
                elif opt.startswith("mgmt_dns:"):
                    value = opt.replace("mgmt_dns:", "").strip()
                    self.mgmt_dns = ipaddress.IPv4Interface(
                        value).ip  # noqa : F821
                elif opt == "lan-fixed-route-to-wan":
                    self.lan_fixed_route_to_wan = self.options[opt]

        if pre_cmd_host is not None:
            sys.stdout.write("\tRunning pre_cmd_host.... ")
            sys.stdout.flush()
            phc = bft_pexpect_helper.spawn(command="bash",
                                           args=["-c", pre_cmd_host],
                                           env=self.dev.env)
            phc.expect(pexpect.EOF, timeout=120)
            logger.info("\tpre_cmd_host done")

        if ipaddr is not None:
            bft_pexpect_helper.spawn.__init__(
                self,
                command="ssh",
                args=[
                    "%s@%s" % (self.username, ipaddr),
                    "-p",
                    port,
                    "-o",
                    "StrictHostKeyChecking=no",
                    "-o",
                    "UserKnownHostsFile=/dev/null",
                    "-o",
                    "ServerAliveInterval=60",
                    "-o",
                    "ServerAliveCountMax=5",
                ],
            )

            self.ipaddr = ipaddr

        if cleanup_cmd is not None:
            self.cleanup_cmd = cleanup_cmd
            atexit.register(self.run_cleanup_cmd)

        if cmd is not None:
            sys.stdout.write("\tRunning cmd.... ")
            sys.stdout.flush()
            bft_pexpect_helper.spawn.__init__(self,
                                              command="bash",
                                              args=["-c", cmd],
                                              env=self.dev.env)
            self.ipaddr = None
            logger.info("\tcmd done")

        self.name = name
        self.color = color
        if self.username != "root":
            self.prompt.append("%s\\@.*:.*$" % self.username)
        self.port = port
        self.location = location

        self.check_connection(self.username, name, self.password)

        # attempts to fix the cli colums size
        self.set_cli_size(200)

        if ipaddr is None:
            self.sendline("hostname")
            self.expect("hostname")
            self.expect(self.prompt)
            ipaddr = self.ipaddr = self.before.strip()

        self.print_connected_console_msg(ipaddr, port, color, name)

        if post_cmd_host is not None:
            sys.stdout.write("\tRunning post_cmd_host.... ")
            sys.stdout.flush()
            phc = bft_pexpect_helper.spawn(command="bash",
                                           args=["-c", post_cmd_host],
                                           env=self.dev.env)
            i = phc.expect([pexpect.EOF, pexpect.TIMEOUT, "password"])
            if i > 0:
                logger.error(
                    "\tpost_cmd_host did not complete, it likely failed\n")
            else:
                logger.info("\tpost_cmd_host done")

        if post_cmd is not None:
            sys.stdout.write("\tRunning post_cmd.... ")
            sys.stdout.flush()
            env_prefix = ""
            for k, v in self.dev.env.items():
                env_prefix += "export %s=%s; " % (k, v)

            self.sendline(env_prefix + post_cmd)
            self.expect(self.prompt)
            logger.info("\tpost_cmd done")

        if reboot:
            self.reset()

        self.logfile_read = self.output
        self.configure_gw_ip()
Пример #16
0
 def reset(self):
     '''Send off command, wait 5 seconds, send on command.'''
     bft_pexpect_helper.spawn(self.off_cmd).expect(pexpect.EOF)
     time.sleep(5)
     bft_pexpect_helper.spawn(self.on_cmd).expect(pexpect.EOF)
Пример #17
0
    def __init__(self,
                 model,
                 conn_cmd,
                 power_ip,
                 power_outlet,
                 output=sys.stdout,
                 password='******',
                 web_proxy=None,
                 tftp_server=None,
                 tftp_username=None,
                 tftp_password=None,
                 tftp_port=None,
                 connection_type=None,
                 power_username=None,
                 power_password=None,
                 rootfs=None,
                 kernel=None,
                 mgr=None,
                 **kwargs):
        """Intialize the variables that are used across function which include the tftp_server, credential, power_ip, credentials etc..

        :param model: Model of the QEMU device.
        :type model: string
        :param conn_cmd: The connection command that is used to connect to QEMU device
        :type conn_cmd: string
        :param power_ip: IP Address of power unit to which this device is connected
        :type power_ip: string
        :param power_outlet: Outlet # this device is connected
        :type power_outlet: string
        :param output: Stores the system standard output, defaults to sys.stdout
        :type output: string
        :param password: The password used to connect to the device, defaults to "bigfoot1"
        :type password: string
        :param web_proxy: The web proxy to be used, defaults to None
        :type web_proxy: string
        :param tftp_server: The tftp_server ip address, defaults to None
        :type tftp_server: string
        :param tftp_username: The tftp server userame, defaults to None
        :type tftp_username: string
        :param tftp_password: The tftp server password to be used, defaults to None
        :type tftp_password: string
        :param tftp_port: The port number that can be used to connect to tftp, defaults to None
        :type tftp_port: string
        :param connection_type: The connection type to used to connect.
        :type connection_type: string
        :param power_username: The username to be used over power unit connection to the device, defaults to None
        :type power_username: string
        :param power_password: The password to be used over power unit connection to the device, defaults to None
        :type power_password: string
        :param rootfs: The complete url of the image to be loaded, defaults to None
        :type rootfs: string
        :param kernel: The kernel image path to be used to flash to the device, defaults to None
        :type kernel: string
        :param ``**kwargs``: Extra set of arguements to be used if any.
        :type ``**kwargs``: dict
        :raises: Exception "The QEMU device type requires specifying a rootfs"
        """
        self.consoles = [self]
        self.dev = mgr

        assert cmd_exists('qemu-system-i386')

        if rootfs is None:
            raise Exception(
                "The QEMU device type requires specifying a rootfs")

        def temp_download(url):
            """Download the image to the temp folder over the QEMU device.

            :param url: URL where the file is location (URL path of the file to be downloaded), defaults to None
            :type url: string
            :returns: The filename of the downloaded file.
            :rtype: string
            """
            dl_console = bft_pexpect_helper.spawn("bash --noprofile --norc")
            dl_console.sendline('export PS1="prompt>>"')
            dl_console.expect_exact("prompt>>")
            dl_console.sendline('mktemp')
            dl_console.expect('/tmp/tmp.*')
            fname = dl_console.match.group(0).strip()
            dl_console.expect_exact("prompt>>")
            self.cleanup_files.append(fname)
            atexit.register(self.run_cleanup_cmd)
            dl_console.logfile_read = sys.stdout
            print("Temp downloaded file = %s" % url)
            dl_console.sendline("curl -n -L -k '%s' > %s" % (url, fname))
            dl_console.expect_exact("prompt>>", timeout=500)
            dl_console.logfile_read = None
            dl_console.sendline('exit')
            dl_console.expect(pexpect.EOF)
            return fname

        if rootfs.startswith("http://") or rootfs.startswith("https://"):
            rootfs = temp_download(rootfs)

        cmd = "%s %s" % (conn_cmd, rootfs)

        if kernel is not None:
            if kernel.startswith("http://") or kernel.startswith("https://"):
                kernel = temp_download(kernel)
            cmd += " -kernel %s --append root=/dev/hda2" % kernel

        # check if we can run kvm
        kvm_chk = bft_pexpect_helper.spawn('sudo kvm-ok')
        if 0 != kvm_chk.expect(['KVM acceleration can be used', pexpect.EOF]):
            cmd = cmd.replace('--enable-kvm ', '')
            self.kvm = False

        # TODO: add script=no,downscript=no to taps

        try:
            bft_pexpect_helper.spawn.__init__(self,
                                              command='/bin/bash',
                                              args=["-c", cmd],
                                              env=self.dev.env)
            self.expect(pexpect.TIMEOUT, timeout=1)
        except pexpect.EOF:
            self.pid = None
            if 'failed to initialize KVM: Device or resource busy' in self.before or \
                    'failed to initialize KVM: Cannot allocate memory' in self.before:
                cmd = cmd.replace('--enable-kvm ', '')
                self.kvm = False
                bft_pexpect_helper.spawn.__init__(self,
                                                  command='/bin/bash',
                                                  args=["-c", cmd],
                                                  env=self.dev.env)
            else:
                raise

        self.cmd = cmd
        if kernel is None:
            self.expect(["SYSLINUX", "GNU GRUB"])
        self.logfile_read = output

        atexit.register(self.kill_console_at_exit)