【发布时间】:2019-02-20 08:19:49
【问题描述】:
我的本地计算机上有一个目录,我想使用 Fabric 将其复制到远程计算机(并重命名)。我知道我可以使用put() 复制文件,但是目录呢?我知道使用 scp 很简单,但如果可能的话,我更愿意在我的fabfile.py 中进行。
【问题讨论】:
我的本地计算机上有一个目录,我想使用 Fabric 将其复制到远程计算机(并重命名)。我知道我可以使用put() 复制文件,但是目录呢?我知道使用 scp 很简单,但如果可能的话,我更愿意在我的fabfile.py 中进行。
【问题讨论】:
您也可以为此使用put(至少在 1.0.0 中):
local_path可以是相对或绝对的本地文件或目录路径,并且可能包含 shell 样式通配符,如 Python glob 模块。波浪号扩展(由 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
# ...
【讨论】:
fab,没有任何技巧。如果目标目录还没有到位,你会得到错误——所以我在put 之前包含了一个简单的mkdir -p。 (但testdirectory下面的其他子目录会在远程机器上自动创建)。
put 正在工作。它是否支持在源机器上压缩复制文件夹并在远程机器上解压缩。
我还会查看项目工具模块:fabric.contrib.project Documentation
这有一个upload_project 函数,它接受一个源目录和目标目录。更好的是,有一个使用 rsync 的rsync_project 函数。这很好,因为它只更新已更改的文件,并且它接受额外的参数,如“排除”,这对于排除 .git 目录等操作非常有用。
例如:
from fabric.contrib.project import rsync_project
def _deploy_ec2(loc):
rsync_project(local_dir=loc, remote_dir='/var/www', exclude='.git')
【讨论】:
fabric.contrib.project 最新版本的文档:docs.fabfile.org/en/latest/api/contrib/project.html
put/get好多了。也非常适合从实时网站获取用户上传,例如(upload=False,这两种方式都不明显)。
exclude=['.git']
对于使用 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。
【讨论】:
connect_kwargs。例如:cxn = fabric.Connection('username@server:22', connect_kwargs=dict(password='yourpass'))
put 无法在 Fabric 2 中上传。如果您使用的是 Fabric 1,请参考接受的答案。对于 Fabric 2,我使用答案中提供的示例,使用 rsync。