session.py 文件源码

python
阅读 28 收藏 0 点赞 0 评论 0

项目:JumpSSH 作者: AmadeusITGroup 项目源码 文件源码
def file(
            self,
            remote_path,
            content,
            use_sudo=False,
            owner=None,
            permissions=None,
            username=None,
            silent=False
    ):
        """ Method to create a remote file with the specified `content`

        :param remote_path: destination folder in which to copy the local file
        :param content: content of the file
        :param use_sudo: allow to copy file in location with restricted permissions
        :param owner: user that will own the file on the remote host
        :param permissions: permissions to apply on the remote file (chmod format)
        :param username: sudo user
        :param silent: disable logging

        Usage::

            # create file on remote host and with specified content at the specified path
            >>> ssh_session.file(remote_path='/path/to/remote/file', content='file content')

            # create file on remote host and with specified content at the specified path needing sudo permissions
            >>> ssh_session.file(remote_path='/path/to/remote/file', content='file content', use_sudo=True)

            # create file on remote host and with specified content at the specified path
            # with specified owner and permissions
            >>> ssh_session.file(remote_path='/path/to/remote/file', content='file content',
            ...                 owner='other_user', permissions='700')
        """
        if not silent:
            logger.debug("Create file '%s' on remote host '%s' as '%s'" % (remote_path, self.host, self.username))
        sftp_client = self.get_sftp_client()

        copy_path = remote_path
        if use_sudo:
            # copy local file on remote host in temporary dir
            copy_path = "/tmp/%s" % util.id_generator(size=15)

        # create file remotely
        with sftp_client.file(copy_path, mode='w+') as remote_file:
            remote_file.write(content)

        # mv this file in the final destination
        if use_sudo:
            move_command = "mv %s %s" % (copy_path, remote_path)
            self.run_cmd(move_command, silent=True, username=username or 'root')

        # file will be owned by the specified user
        if owner:
            full_owner = owner
            if ':' not in owner:
                full_owner = '{0}:{0}'.format(owner)
            self.run_cmd("sudo chown %s %s" % (full_owner, remote_path), silent=True)

        if permissions:
            self.run_cmd("sudo chmod %s %s" % (permissions, remote_path), silent=True)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号