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。

 

posted @ 2018-06-15 13:52  Anliven  阅读(3797)  评论(0编辑  收藏  举报