Beispiel #1
0
 def test_does_file_exists_exception(self, m_connect, m_opensftp, m_stat):
     ssh_util = ssh_utilities.RemoteConnection(self.hostname, self.user,
                                                self.passwd)
     m_opensftp.return_value = SFTPFile("sftp", "handle")
     m_stat.side_effect = [IOError]
     self.assertRaises(IOError, ssh_util.does_file_exist,
                       "/etc/hos/osconfig")
    def open(self, filename, mode="r", bufsize=-1):
        """
        Open a file on the remote server.  The arguments are the same as for
        Python's built-in `python:file` (aka `python:open`).  A file-like
        object is returned, which closely mimics the behavior of a normal
        Python file object, including the ability to be used as a context
        manager.

        The mode indicates how the file is to be opened: ``'r'`` for reading,
        ``'w'`` for writing (truncating an existing file), ``'a'`` for
        appending, ``'r+'`` for reading/writing, ``'w+'`` for reading/writing
        (truncating an existing file), ``'a+'`` for reading/appending.  The
        Python ``'b'`` flag is ignored, since SSH treats all files as binary.
        The ``'U'`` flag is supported in a compatible way.

        Since 1.5.2, an ``'x'`` flag indicates that the operation should only
        succeed if the file was created and did not previously exist.  This has
        no direct mapping to Python's file flags, but is commonly known as the
        ``O_EXCL`` flag in posix.

        The file will be buffered in standard Python style by default, but
        can be altered with the ``bufsize`` parameter.  ``0`` turns off
        buffering, ``1`` uses line buffering, and any number greater than 1
        (``>1``) uses that specific buffer size.

        :param str filename: name of the file to open
        :param str mode: mode (Python-style) to open in
        :param int bufsize: desired buffering (-1 = default buffer size)
        :return: an `.SFTPFile` object representing the open file

        :raises: ``IOError`` -- if the file could not be opened.
        """
        filename = self._adjust_cwd(filename)
        self._log(DEBUG, "open({!r}, {!r})".format(filename, mode))
        imode = 0
        if ("r" in mode) or ("+" in mode):
            imode |= SFTP_FLAG_READ
        if ("w" in mode) or ("+" in mode) or ("a" in mode):
            imode |= SFTP_FLAG_WRITE
        if "w" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_TRUNC
        if "a" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_APPEND
        if "x" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_EXCL
        attrblock = SFTPAttributes()
        t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
        if t != CMD_HANDLE:
            raise SFTPError("Expected handle")
        handle = msg.get_binary()
        self._log(
            DEBUG,
            "open({!r}, {!r}) -> {}".format(
                filename, mode, u(hexlify(handle))
            ),
        )
        return SFTPFile(self, handle, mode, bufsize)
Beispiel #3
0
    def open(self, filename, mode='r', bufsize=-1):
        """
        Open a file on the remote server.  The arguments are the same as for
        python's built-in C{file} (aka C{open}).  A file-like object is
        returned, which closely mimics the behavior of a normal python file
        object, including the ability to be used as a context manager.

        The mode indicates how the file is to be opened: C{'r'} for reading,
        C{'w'} for writing (truncating an existing file), C{'a'} for appending,
        C{'r+'} for reading/writing, C{'w+'} for reading/writing (truncating an
        existing file), C{'a+'} for reading/appending.  The python C{'b'} flag
        is ignored, since SSH treats all files as binary.  The C{'U'} flag is
        supported in a compatible way.

        Since 1.5.2, an C{'x'} flag indicates that the operation should only
        succeed if the file was created and did not previously exist.  This has
        no direct mapping to python's file flags, but is commonly known as the
        C{O_EXCL} flag in posix.

        The file will be buffered in standard python style by default, but
        can be altered with the C{bufsize} parameter.  C{0} turns off
        buffering, C{1} uses line buffering, and any number greater than 1
        (C{>1}) uses that specific buffer size.

        @param filename: name of the file to open
        @type filename: str
        @param mode: mode (python-style) to open in
        @type mode: str
        @param bufsize: desired buffering (-1 = default buffer size)
        @type bufsize: int
        @return: a file object representing the open file
        @rtype: SFTPFile

        @raise IOError: if the file could not be opened.
        """
        filename = self._adjust_cwd(filename)
        self._log(DEBUG, 'open(%r, %r)' % (filename, mode))
        imode = 0
        if ('r' in mode) or ('+' in mode):
            imode |= SFTP_FLAG_READ
        if ('w' in mode) or ('+' in mode) or ('a' in mode):
            imode |= SFTP_FLAG_WRITE
        if ('w' in mode):
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_TRUNC
        if ('a' in mode):
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_APPEND
        if ('x' in mode):
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_EXCL
        attrblock = SFTPAttributes()
        t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
        if t != CMD_HANDLE:
            raise SFTPError('Expected handle')
        handle = msg.get_string()
        self._log(DEBUG,
                  'open(%r, %r) -> %s' % (filename, mode, hexlify(handle)))
        return SFTPFile(self, handle, mode, bufsize)
Beispiel #4
0
 def test_does_file_exists_true(self, m_connect, m_opensftp, m_stat):
     ssh_util = ssh_utilities.RemoteConnection(self.hostname, self.user,
                                                self.passwd)
     m_opensftp.return_value = SFTPFile("sftp", "handle")
     exists = ssh_util.does_file_exist("/etc/hos/osconfig-ran")
     self.assertEquals(exists, True)
     calls = [call(self.hostname, password=self.passwd,
                   pkey=None, timeout=120, username=self.user)]
     m_connect.assert_has_calls(calls)
     self.assertEquals(m_connect.call_count, 1)
     m_opensftp.assert_called_once_with()
     m_stat.assert_called_once_with("/etc/hos/osconfig-ran")
Beispiel #5
0
    def _sftp_open_exclusive(self, abspath, mode=None):
        """Open a remote path exclusively.

        SFTP supports O_EXCL (SFTP_FLAG_EXCL), which fails if
        the file already exists. However it does not expose this
        at the higher level of SFTPClient.open(), so we have to
        sneak away with it.

        WARNING: This breaks the SFTPClient abstraction, so it
        could easily break against an updated version of paramiko.

        :param abspath: The remote absolute path where the file should be opened
        :param mode: The mode permissions bits for the new file
        """
        # TODO: jam 20060816 Paramiko >= 1.6.2 (probably earlier) supports
        #       using the 'x' flag to indicate SFTP_FLAG_EXCL.
        #       However, there is no way to set the permission mode at open
        #       time using the sftp_client.file() functionality.
        path = self._get_sftp()._adjust_cwd(abspath)
        # mutter('sftp abspath %s => %s', abspath, path)
        attr = SFTPAttributes()
        if mode is not None:
            attr.st_mode = mode
        omode = (SFTP_FLAG_WRITE | SFTP_FLAG_CREATE
                 | SFTP_FLAG_TRUNC | SFTP_FLAG_EXCL)
        try:
            t, msg = self._get_sftp()._request(CMD_OPEN, path, omode, attr)
            if t != CMD_HANDLE:
                raise TransportError('Expected an SFTP handle')
            handle = msg.get_string()
            return SFTPFile(self._get_sftp(), handle, 'wb', -1)
        except (paramiko.SSHException, IOError), e:
            self._translate_io_exception(e,
                                         abspath,
                                         ': unable to open',
                                         failure_exc=FileExists)