如何使用Fabric将目录复制到远程计算机?

时间:2011-03-15 16:23:03

标签: python fabric

我在本地计算机上有一个目录,我希望使用Fabric将其复制到远程计算机(并重命名)。我知道我可以使用put()复制文件,但是目录呢。我知道使用 scp 很容易,但如果可能的话,我更愿意在fabfile.py内进行。

4 个答案:

答案 0 :(得分:110)

您也可以使用put(至少在1.0.0中):

  

local_path可能是相对或绝对本地文件或目录路径,并且可能包含 shell样式通配符,如Python所理解的那样 glob 模块。还执行了Tilde扩展(由os.path.expanduser实现)。

请参阅:http://docs.fabfile.org/en/1.0.0/api/core/operations.html#fabric.operations.put


更新:此示例在1.0.0上运行正常(对我而言):

from fabric.api import env
from fabric.operations import run, put

env.hosts = ['frodo@middleearth.com']

def copy():
    # make sure the directory is there!
    run('mkdir -p /home/frodo/tmp')

    # our local 'testdirectory' - it may contain files or subdirectories ...
    put('testdirectory', '/home/frodo/tmp')

# [frodo@middleearth.com] Executing task 'copy'
# [frodo@middleearth.com] run: mkdir -p /home/frodo/tmp
# [frodo@middleearth.com] put: testdirectory/HELLO -> \
#     /home/frodo/tmp/testdirectory/HELLO
# [frodo@middleearth.com] put: testdirectory/WORLD -> \
#     /home/frodo/tmp/testdirectory/WORLD
# ...

答案 1 :(得分:31)

我还会看一下Project Tools模块:fabric.contrib.project Documentation

这有一个upload_project函数,它接受源和目标目录。更好的是,有rsync_project函数使用rsync。这很好,因为它只更新已更改的文件,并且它接受额外的args,例如“exclude”,这对于排除.git目录这样做很有用。

例如:

from fabric.contrib.project import rsync_project

def _deploy_ec2(loc):

    rsync_project(local_dir=loc, remote_dir='/var/www', exclude='.git')

答案 2 :(得分:4)

对于使用Fabric 2的用户,put不能再上传目录,只能上传文件。另外,rsync_project不再是Fabric主包的一部分。 contrib软件包已被删除,as explained here。现在,rsync_project已重命名为rsync,并且您需要安装另一个软件包才能使用它:

pip install patchwork

现在,假设您已经创建了到服务器的连接:

cxn = fabric.Connection('username@server:22')

您可以按以下方式使用rsync

import patchwork.transfers
patchwork.transfers.rsync(cxn, '/my/local/dir', target, exclude='.git')

有关更多信息,请参阅fabric-patchwork documentation

答案 3 :(得分:0)

扩展TGO的答案,如果您想在rsync上使用它,则需要rsync的源,例如cygwin  Windows系统。