在两个远程服务器之间传输文件(在本地启动连接)

时间:2019-02-13 17:06:25

标签: python python-3.x paramiko transfer

有这个答案How to use paramiko to transfer files between two remote servers?

但是它并不能真正回答这个问题。

我想做的是从第三个位置(例如,我的笔记本电脑)启动两个连接,并将某些文件从一个位置传输到另一个位置,而无需先在本地下载这些文件。

那么首先,这有可能吗?如果是这样,它与从本地下载然后将其上传到另一个远程设备所需的时间相比,是否根本改善了时间?而且我不想将脚本放在远程位置。我想控制我计算机上的传输。

我已经实现了从一个远程获取文件,在本地下载文件然后上传到远程文件的实现。但是我需要移动大量文件,这可能需要一些时间,因此想知道是否有更好的方法。

所以我有这个实现(它不起作用,因为它需要本地路径):

def rpath_exists(path, sftp):
    """Check if remote path exists.

    Checking is done using paramiko connection.
    """
    try:
        sftp.stat(path)
    except IOError as e:
        if e.errno == errno.ENOENT:
            return False
        raise
    else:
        return True

def _is_rfile(remote_file_obj):
    """Check if remote path is file."""
    if stat.S_ISDIR(remote_file_obj.st_mode):
        return False
    return True


def transfer_dir(source, target, sftp_from, sftp_to, create_dir=True):
    """Transfer directory between two remotes using sftps."""
    if create_dir:
        _create_rdir(target, sftp_to)
    for item in sftp_from.listdir_attr(source):
        filename = item.filename
        source_path = os.path.join(source, filename)
        target_path = os.path.join(target, filename)
        if _is_rfile(item):
            # obviously this won't work, because it expects local path,
            # but I'm specifying remote path from sftp_from.
            sftp_to.put(source_path, target_path)
        else:
            if not rpath_exists(target_path, sftp_to):
                sftp_to.mkdir(target_path)
            # We specify create_dir=False, because only root dir can
            # be created.
            transfer_dir(
                source_path, target_path, sftp_from, sftp_to, create_dir=False)

0 个答案:

没有答案