Fabric
Fabric 是一个 python 的远程执行 shell 的库, 同时它也是一个命令行工具. 它提供了丰富的同 SSH 交互的接口, 可以用来在本地或远程机器上自动化, 流水化地执行 Shell 命令.
安装 Fabric
Fabric 的官网是 www.fabfile.org, 源码托管在 GitHub 上. 你可以 clone 源码到本地, 然后通过下面的命令来安装. 但是在源码安装前, 你必须先将 Fabric 的依赖包 Paramiko 装上.
python setup.py develop
同时也可以使用 pip 安装, 因为 fabric 是 python 的一个第三方库, 只需一条命令即可:
pip install fabric
python3 安装时使用的是 fabric3 :( 安装 fabric3 之前, 需要先卸载 fabric.)
- # fabric3 支持 python3
- pip uninstall fabric
- pip3 install fabric3
fabric 不只是一个 Python 模块, fabric 还是一个命令行工具, 可以使用 fab -h 查看帮助信息
- E:\my_data\hk-project>fab -V
- Fabric3 1.14.post1
- Paramiko 2.4.2
- E:\my_data\hk-project>fab -h
入门使用
fabric 的使用方式是通过编写一个 python 文件, 该文件中包含多个函数, 然后使用 fab 命令调用这些函数, 做相应的任务. 这些函数在 fabric 中称为 task.
- # filename:abc.py
- from fabric.API import *
- def task1():
- print("hello")
- def hello():
- print("hello world")
写好这个 python 文件后, 在当前目录的路径下使用 fab 工具执行文件中的函数
[root@localhost python 文件所在的目录]# fab -f abc.py hello
- hello world
- # -f 指定 fabfile 文件, 默认为 fabfile.py, 若文件名是当前目录下的 fabfile.py 则无需指定
任务参数
此时你可能会想, 如果这个函数有参数怎么办呢? 应该如何传递参数给函数呢? Fabric 支持 Shell 兼容的参数用法: <任务名>:<参数>, <关键字参数名>=<参数值>,... 用起来就是这样.
- def hello(name="world"):
- print("hello {}".format(name))
我们可以这样去指定参数
- $ fab hello:name=Jeff # 或者 fab hello:Jeff
- hello Jeff
- Done.
小试牛刀
现在我们假设需要写一个 fabfile.py, 能够在每次 web 项目代码更新后使用 Git 提交并远程服务器拉去最新代码并运行, 需求描述清楚了, 开干吧!
- # fabfile.py
- # 这里建议将该文件放入项目文件的根目录中, 方便 Git 提交
- from fabric.API import local
- def test():
- local('python manage.py test myapp')
- # 测试是否能正常运行
- def commit():
- local('git add -p && git commit -m"for test"')
- def push():
- local('git push')
- def prepare_deploy():
- test()
- commit()
- push()
这个 prepare_deploy 任务可以单独调用, 也可以调用更细粒度的子任务.
故障
Fabric 会检查被调用程序的返回值, 如果这些程序没有干净地退出, Fabric 会终止操作. 我们什么都不用做, Fabric 检测到了错误并终止, 不会继续执行 commit 任务.
我们也可以对故障进行一定的处理和判断
- from fabric.API import local, settings, abort
- from fabric.contrib.console import confirm
- def test():
- with settings(warn_only=True):
- result = local('./manage.py test my_app', capture=True)
- # result.return_code 返回码 (0/1) 和 result.failed
- if result.failed and not confirm("Tests failed. Continue anyway?"): # confirm 判断用户输入
- abort("Aborting at user request.") # 指定错误退出信息
- # 一个名为 warn_only 的设置 (或着说 环境变量 , 通常缩写为 env var ) 可以把退出换为警告, 以提供更灵活的错误处理. 如果设置为 False, 则一条命令运行失败会就会退出, 不再执行后面的命令.
建立连接
终于到了连接了, 这个工具主要作用就是在远程执行命令呀, 学会了这个, 我们就可以在本地执行远程服务器的命令了.
- from fabric.API import *
- env.hosts = ['root@192.168.10.11:22']
- def deploy():
- run('ls') # run()用于执行远程命令, local()执行本地命令
- # 执行后会提示你输入密码, 输入密码即可
至此, 入门结束, 后续还有更多 API 的讲解, 敬请关注!
参考链接:
fabric 官方中文文档: https://fabric-chs.readthedocs.io/zh_CN/chs/tutorial.html
Python 远程部署利器 Fabric 模块详解: https://blog.csdn.net/freeking101/article/details/81103945
来源: https://www.cnblogs.com/welisit/p/10995357.html