2011-03-15 95 views
70

我在本地機器上有一個目錄,我想使用Fabric將其複製到遠程機器(並對其進行重命名)。我知道我可以使用put()複製文件,但是一個目錄怎麼樣。我知道使用scp很容易,但如果可能的話,我寧願從我的fabfile.py之內完成。如何使用Fabric將目錄複製到遠程計算機?

回答

98

您可以使用put爲該以及(至少在1.0.0):

local_path可能是一個相對或絕對的本地文件或目錄路徑,並可能包含殼式通配符,正如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 = ['[email protected]'] 

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') 

# [[email protected]] Executing task 'copy' 
# [[email protected]] run: mkdir -p /home/frodo/tmp 
# [[email protected]] put: testdirectory/HELLO -> \ 
#  /home/frodo/tmp/testdirectory/HELLO 
# [[email protected]] put: testdirectory/WORLD -> \ 
#  /home/frodo/tmp/testdirectory/WORLD 
# ... 
+0

感謝。我得到一個例外(是一個目錄)的例子嗎? – 2011-03-15 16:42:41

+0

@gaviscon_man:增加了一個(測試過的)例子,但它真的只是香草'fab',沒有任何竅門。如果目標目錄不存在,你會得到錯誤 - 所以我在'put'之前包含了一個簡單的'mkdir -p'。 (但是其他的子目錄,在testdirectory下面會自動在遠程機器上創建)。 – miku 2011-03-15 16:59:42

+0

謝謝,這非常有幫助。 – 2011-03-15 17:03:02

28

我也想看看工程工具模塊正常工作(對我來說):面料.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') 
+2

'fabric.contrib.project' docs for latest version:http://docs.fabfile.org/en/latest/api/contrib/project.html – lsh 2016-04-01 16:14:23

+0

比'put/get'更好的方式。例如('upload = False',它不是顯而易見的,它可以在兩種方式下工作)。 – benzkji 2017-01-17 09:24:03

+0

我不得不在列表中包裝排除的目錄才能使其工作:'exclude = ['。git']' – 2017-05-16 20:05:24

相關問題