Python模块学习之fabric

fabric是一个运维经常使用到的一个模块。但是我在python3环境下安装fabric就遇到了坑!

安装包名称是fabric3而不是fabric!

pip install fabric3

利用fab工具来执行代码

vim fabfile.py

def hello():
  print('Hello World!')
def hi():
  print('Hi World!')

现在可以在cli下调用函数了:

fab hi
Hi World!

Done.

一个更为实用的例子:

from fabric.api import run, env

env.hosts = ['host1', 'host2']

def taskA():
    run('ls')

def taskB():
    run('whoami')

执行:

$ fab taskA taskB

执行过程:

  • taskA executed on host1
  • taskA executed on host2
  • taskB executed on host1
  • taskB executed on host2

查看可用的任务

fab --list

向任务中传入参数

def hello(name="world"):
    print("Hello %s!" % name)

执行:

fab taskA:name='tom'

结果:

Hello tom

Done.
原文地址:https://www.cnblogs.com/leomei91/p/7448266.html