session.py 文件源码

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

项目:JumpSSH 作者: AmadeusITGroup 项目源码 文件源码
def get(self,
            remote_path,
            local_path,
            use_sudo=False,
            username=None
            ):
        """Download a file from the remote host

        :param remote_path: remote path of the file to download
        :param local_path: local path where to download the file
        :param use_sudo: allow to download a file from a location current user does not have access
        :param username: sudo user

        Usage::

            # download remote file in local directory
            >>> ssh_session.get(remote_path='/path/to/remote/file', local_path='/local/folder')

            # donload remote file from a path not accessible by current user
            >>> ssh_session.get(local_path='/path/to/local/file', remote_path='/path/to/remote/file', use_sudo=True)
        """
        copy_path = remote_path
        remote_filename = os.path.basename(remote_path)
        sudo_username = username if username else 'root' if use_sudo else None

        # copy first remote file in a temporary location accessible from current user
        if use_sudo:
            copy_path = "/tmp/%s" % util.id_generator(size=15)
            copy_command = "cp %s %s" % (remote_path, copy_path)
            self.run_cmd(copy_command, silent=True, username=sudo_username)

        # if local download path is a directory, local filename will be same as remote
        if os.path.isdir(local_path):
            local_path = os.path.join(local_path, remote_filename)

        sftp_client = self.get_sftp_client()
        try:
            with open(local_path, mode='w') as local_file:
                with sftp_client.file(copy_path) as remote_file:
                    local_file.write(remote_file.read().decode('utf-8'))
        finally:
            if use_sudo:
                # cleanup temporary file
                self.run_cmd('rm %s' % copy_path, silent=True, username=sudo_username)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号