Exemple #1
0
 def run(self, cmd, wait=True, timeout=10):
     """
     This is the main command only real operation.  It runs a command
     and returns the result.
     """
     logger.debug(cmd)
     if not self.connected:
         raise ConnectionError("not connected")
     # To handle long commands greater than 50 chars long, change winsize
     if len(cmd) >= 50:
         winsize = self.getwinsize()
         self.setwinsize(winsize[0], len(cmd) + 80)
         self.sendline(cmd)
     else:
         self.sendline(cmd)
     if not wait:
         if len(cmd) >= 50:
             self.setwinsize(winsize[0], winsize[1])
         logger.debug("**didn't wait for a response**")
         return self.before.strip()
     self.expect_exact(cmd)  # read until you see the command just entered
     self.expect(self.prompt, timeout)
     response = self.before.strip()  # remove the prompt
     if len(cmd) >= 50:
         self.setwinsize(winsize[0], winsize[1])
     logger.debug(response)
     return response
Exemple #2
0
 def ls(self, path=None, expectation=True):
     """
     return a list of files in path.  If path is not specified cwd will be used.  If
     path does not exist an exception will be raised unless expectation is False. Works
     in conjunction with the cd context manager.
     """
     sftp = self.open_sftp()
     if not path:
         path = ""
     try:
         if path:
             if path[0] == '/':
                 return sftp.listdir(path=path)
             else:
                 return sftp.listdir(path="%s%s" % (self.cwd, path))
         else:
             if self.cwd:
                 return sftp.listdir(path=self.cwd)
             else:
                 return sftp.listdir()
     except IOError as e:
         if not expectation:
             return []
         else:
             raise ConnectionError("ls %s failed: %s" % (path, e))
Exemple #3
0
    def run(self, cmd, timeout=None, bufsize=-1):
        """
        :param cmd: command to run on remote host
        :type cmd: str

        :param timeout: timeout on blocking read/write operations when exceeded socket error will be raised
        :type timeout: float
        :param bufsize: byte size of the buffer for the filehandle returned
        :type bufsize: int
        :rtype: ReturnCode
        """
        ret = ReturnCode(False)
        if not self.connected:
            raise ConnectionError(
                "Run was called on an unconnected host. Did you check the result of connect()?"
            )
        try:
            if self.environmentals:
                envstring = str()
                for var, value in self.environmentals.items():
                    statement = "%s=%s " % (var, value)
                    envstring += statement
                cmd = "%s%s" % (envstring, cmd)
            if self.cwd:
                cmd = "cd %s && %s" % (self.cwd, cmd)
            self._log(logging.DEBUG, 'running command: "%s"' % cmd)
            stdin, stdout, stderr = self.exec_command(command=cmd,
                                                      timeout=timeout,
                                                      bufsize=bufsize)
        except paramiko.SSHException as e:
            err = "Couldn't complete the command: %s" % str(e)
            logger.critical(err)
            ret.message = err
            return ret

        # we must read stderr _before_ stdout
        # otherwise paramiko losses the stdout data
        try:
            ret.raw = Data(ret.raw.status, ret.raw.stdout, stderr.read())
        except socket.timeout:
            ret.message = "Timeout"
            return ret

        status = stdout.channel.recv_exit_status()
        ret.raw = Data(status, stdout.read(), ret.raw.stderr)

        if status != 0:
            ret.message = ret.raw.stderr
        else:
            ret.status = True
            ret.message = ret.raw.stdout

        stdin.close()

        return ret
Exemple #4
0
    def connect(self, timeout=10, args=None, nolog=False):
        """Connect to and authenticate with host."""

        cmd = "ssh"

        if args is None:
            args = [
                "-q", "-o PubkeyAuthentication no",
                "-o UserKnownHostsFile=/dev/null",
                "-o UserKnownHostsFile2=/dev/null",
                "-o StrictHostKeyChecking=no"
            ]

        args.append("-l" + self.user)
        args.append(self.host)
        if not nolog:
            logger.debug("%s %s" % (cmd, str(args)))

        try:
            spawn.__init__(self, cmd, args, timeout)

            prompt = self.expect(["(?i)password: "******"(?i)password"])

            if prompt in [0, 1]:
                self.sendline(self.password)

            else:
                self.close()
                return False
            try:
                if self.prompt == ':\>':
                    self.expect_exact(self.prompt)
                else:
                    self.expect(self.prompt)
            except TIMEOUT:
                raise ConnectionError(
                    "Connected but didn't find prompt '%s'\n instead self.before was:\n%s"
                    % (self.prompt, self.before))
            self.connected = True
        except KeyError as e:
            if not nolog:
                logger.critical("Couldn't complete connection")
                if e.message:
                    logger.error(e.message)
            return False
        except (EOF, TIMEOUT) as e:
            if not nolog:
                logger.critical("Couldn't complete connection to %s@%s" %
                                (self.user, self.host))
                if e.message:
                    logger.error(e.message)
            return ReturnCode(False, message=e.message)

        return ReturnCode(True, message=self.before)
Exemple #5
0
    def mkdir(self, dirname, mode=511, expectation=True):
        sftp = self.open_sftp()

        try:
            if dirname[0] == '/':
                return sftp.mkdir(path=dirname, mode=mode)
            else:
                return sftp.mkdir(path="%s%s" % (self.cwd, dirname), mode=mode)

        except IOError as e:
            if not expectation:
                return []
            else:
                raise ConnectionError("mkdir %s failed: %s" % (dirname, e))
Exemple #6
0
 def open(self, fname, mode='r', bufsize=-1, expectation=True):
     """
     return a file-like object of fname on the remote
     """
     sftp = self.open_sftp()
     try:
         ret = sftp.file(
             fname,
             mode,
             bufsize,
         )
     except IOError as e:
         if not expectation:
             ret = ReturnCode(False, "file failed: %s" % e)
         else:
             raise ConnectionError(str(e))
     return ret
Exemple #7
0
    def rmdir(self, dirname, expectation=True):
        """
        remove a directory named by a string
        """
        sftp = self.open_sftp()

        try:
            if dirname[0] == '/':
                return sftp.rmdir(path=dirname)
            else:
                return sftp.rmdir(path="%s%s" % (self.cwd, dirname))

        except IOError as e:
            if not expectation:
                return []
            else:
                raise ConnectionError("rmdir %s failed: %s" % (dirname, e))
Exemple #8
0
    def rm(self, path, expectation=True):
        """
        remove a file named by a string
        """
        sftp = self.open_sftp()

        try:

            if path[0] == '/':
                return sftp.remove(path=path)
            else:
                return sftp.remove(path="%s%s" % (self.cwd, path))

        except IOError as e:
            if not expectation:
                return []
            else:
                raise ConnectionError("rm %s failed: %s" % (path, e))
Exemple #9
0
    def connect(self, timeout=10, expectation=True):
        """
        Connect to and authenticate with host.
        """
        cmd = "cec"
        args = list()
        args.append("-s%s" % self.shelf)
        args.append(self.iface)
        logger.debug("%s %s" % (cmd, str(args)))
        connectstr = re.compile('Escape is.*')
        try:
            if hasattr(self, 'closed'):
                self.close()  # this may break if this is interrupted
                spawn.__init__(self, cmd, args=args, timeout=timeout)
            else:
                logger.debug("object had no attribute closed ... hmm")
                spawn.__init__(self, cmd, args=args, timeout=timeout)
            # tricky because cec doesn't return a prompt
            # it just connects
            try:
                self.expect(connectstr)

            except EOF:
                emesg = self.before.strip().splitlines()[0]

                if "can't netopen" in self.before:
                    if expectation:
                        raise ConnectionError(
                            "%s:\n try something like 'sudo chmod u+s /usr/sbin/cec'"
                            % emesg)
                    return False
                elif "none found" in self.before:
                    if expectation:
                        raise ConnectionError(
                            "%s\n could not reach shelf address %s" %
                            (emesg, self.shelf))
                    return False
            self.sendline()
            self.sendline()
            # must now account for possible login prompt
            i = self.expect(["Password", self.prompt], timeout=3)
            if i == 0:
                if self.password is None:
                    self.password = "******"
                self.sendline(self.password)
                self.expect(self.prompt)
            elif i == 1:
                pass
        except KeyError as e:
            logger.critical("CEC couldn't complete connection")
            if e.message:
                logger.error(e.message)
            if e.args:
                logger.debug(e.args)
            if expectation:
                raise ConnectionError(str(e))
            return False
        except ExceptionPexpect as e:
            if "The command was not found or was not executable" in e:
                raise ConnectionError(
                    "%s:\n is cec installed at /usr/sbin/cec?" % e)
            else:
                raise e
        return True
Exemple #10
0
    def run(self, cmd, wait=True, force=False, ans='y', timeout=60):
        """
        This is the main command/only real operation.
        It runs a command and returns the result.
        """
        logger.debug("%s\n\twait %d force %d ans %s timeout %d" %
                     (cmd, wait, force, ans, timeout))
        if self.closed:
            raise ConnectionError("Not connected to shelf %s" % self.shelf)
        self.sendline(cmd)

        if not wait:
            return self.before.strip()  # async messages could appear in here
        try:
            self.expect_exact(cmd, timeout)
        except TIMEOUT:
            r = self.__checkasync(self.before, cmd)
            if not r:
                raise ConnectionError("looking for: %s in %s" %
                                      (cmd, self.before))
        # We only compile this regex once per instance
        if not self.cpl:
            self.cpl = self.compile_pattern_list([
                r"\[n\]",
                r"\[N\]",
                r"Continue\? \(y/n\) (.*)",
                r"(.*)" + self.prompt,
                r"Would you like to update the LUN format, or quit\? y/n/q\? \[q\]",
                r"'y' to update to new format, 'n' to create LUN with old format, "
                "or 'q' to quit\[Q\]:",
                r"'n' to cancel, 'a' for all, or 'y' to .*:",
                r"IPv4 destination address .*:",
                r"IPv4 source address .*:",
                r"Local syslog interface .*:",
            ])

        response = None
        if force:
            while 1:
                i = self.expect_list(self.cpl, timeout)
                if i == 0 or i == 1:
                    if force:
                        self.sendline(ans)
                if i == 2:
                    if force:
                        self.sendline(ans)
                    response = ""
                    break
                elif i == 3:
                    response = self.match.group(1).strip()
                    break
                elif i == 4 or i == 5:
                    self.sendline(ans)
                    response = ""
                # Adding the following to handle syslog -c in srx 6.x to input destination_ip
                elif i == 7:
                    self.sendline(ans)
                    response = ""
                    break
                # Adding the following to handle syslog -c in srx 6.x to input source_ip
                elif i == 8:
                    self.sendline(ans)
                    response = ""
                    break
                # Adding the following to handle syslog -c in srx 6.x to input interface
                elif i == 9:
                    self.sendline(ans)
                    self.expect(self.prompt, timeout)
                    response = self.before
                    break
        else:
            self.expect(self.prompt, timeout)
            response = self.before

        ret = response
        for msg in self.amsgs:
            match = re.search(r"(%s)(\r\n)*" % msg, response)
            if not match:
                continue
            logger.debug("CHECKASYNC: FOUND MATCH: '%s'" % msg)
            start = response.find(match.group(1))
            end = len(match.group(1))
            if match.lastindex == 3:
                # include the matched newline
                end += len(match.group(3))

            # what surrounds the match (hopefully the expected cmd)
            ret = response[:start] + response[start + end:]

            # the matched async message
            # aysncmsg = response[start:start + end]
            break
        ret = ret.strip().replace('\r\r\n', '\r\n')
        return ret