Python - Fabric簡介


1 - Fabric

Fabric是一個Python的庫,提供了豐富的同SSH交互的接口,可以用來在本地或遠程機器上自動化、流水化地執行Shell命令。

非常適合用來做應用的遠程部署及系統維護。簡單易用,只需懂得基本的Shell命令。

2 - 版本區分

目前,從PyPI可以搜索到主要的fabric庫為“ Fabric 2.1.3 ”、“ fabric2 2.1.3 ”和“ Fabric3 1.14.post1 ”。

  • Fabric:官方Fabric,兼容 Python 2 & Python 3,但不兼容Fabric 1.x的fabfile;
  • fabric2: 與Fabric相同,僅作為平滑遷移(使用Fabric包安裝1.x 版本,使用Fabric2包安裝2.x版本,來實現1.x和2.x的共存);
  • Fabric3:是一個基於Fabric 1.x 的fork,兼容Python2 & Python3,兼容 Fabric1.x 的 fabfile;

 
Fabric 1.x 與2.x版本的主要區別:
  • Fabric 1.x只支持Python2.5-2.7,而Fabric2支持Python (2.7, 3.4+);
  • Fabric 2.x是重寫Fabric 1.x的版本,不再兼容1.x 版本的fabfile,而且有些模塊和用法也發生了很大改變;
  • 具體信息請見:Rewrite for 2.0! See Upgrading from Fabric 1.x

3 - 關於Fabric3

Fabric3 is a Python (2.7 or 3.4+) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.
This is a fork of the original Fabric (git) with the intention of providing support for Python3, while maintaining support for all non-archaic versions of Python2.
 
 
注意
  • 當前版本“Fabric3 1.14.post1”的功能和使用方法仍然與“Fabric 1.x.”基本一致。
  • 安裝fabric3之前,需要先卸載fabric。
 1 $ pip2 uninstall fabric
 2 $ pip2 install fabric3 --proxy="10.144.1.10:8080"
 3 
 4 $ pip2 show fabric3
 5 Name: Fabric3
 6 Version: 1.14.post1
 7 Summary: Fabric is a simple, Pythonic tool for remote execution and deployment (py2.7/py3.4+ compatible fork).
 8 Home-page: https://github.com/mathiasertl/fabric/
 9 Author: Mathias Ertl
10 Author-email: mati@er.tl
11 License: UNKNOWN
12 Location: c:\python27\lib\site-packages
13 Requires: paramiko, six
14 Required-by:

 

4 - 問題處理

1 - 導入fabric.api提示報錯“No module named api”
1 >>> from fabric.api import run
2 Traceback (most recent call last):
3   File "<stdin>", line 1, in <module>
4 ImportError: No module named api
5 >>>

處理方法:

  確認fabric版本信息,“from fabric.api import run”的方式只適用fabric1.x版本。

 

2 - 運行fabric示例提示報錯“No idea what 'hello' is!”

 1 $ cat fabfile.py
 2 # coding:utf-8
 3 
 4 
 5 def hello():
 6         print("hello fabric!")
 7 
 8 $ fab hello
 9 No idea what 'hello' is!
10 
11 $ fab --list
12 No tasks found in collection 'fabfile'!
處理方法:
  確認fabric版本信息,fabric2.x版本不兼容Fabric 1.x的fabfile。遵照fabric 2.x要求,更改fabfile文件內容格式,重新運行即可。
 1 $ pip show fabric
 2 Name: fabric
 3 Version: 2.1.3
 4 Summary: High level SSH command execution
 5 Home-page: http://fabfile.org
 6 Author: Jeff Forcier
 7 Author-email: jeff@bitprophet.org
 8 License: BSD
 9 Location: c:\python27\lib\site-packages
10 Requires: paramiko, invoke, cryptography
11 Required-by:
12 
13 $ cat fabfile.py
14 from invoke import task
15 
16 @task
17 def hello(c):
18         c.run("echo 'hello fabric'")
19         print("hello fabric!")
20 
21 $
22 
23 $ fab --list
24 Available tasks:
25 
26   hello
27 
28 
29 $ fab hello
30 'hello fabric'
31 hello fabric!
32 
33 $

 

5 - 參考信息

以下內容主要適用於Fabric 1.x 和 Fabric3。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM