什么是Fabric?
Fabric 是一个高级 Python(2.7, 3.4+)库,设计的目的是远程SSH执行命令行,返回可用的Python对象。
>>> from fabric import Connection
>>> result = Connection('web1.example.com').run('uname -s', hide=True)
>>> msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
>>> print(msg.format(result))
Ran 'uname -s' on web1.example.com, got stdout:
Linux
他建立在Invoke和Paramiko之上,扩充了他们的API以相互补充提供附件的功能。Invoke提供了一系列子进程命令执行和命令行特性。Paramiko是SSH协议的实现。
如何使用?
核心用法包括但不限于
- 在单机上执行命令
>>> result = Connection('web1').run('hostname')
web1
>>> result
<Result cmd='hostname' exited=0>
- 在多个主机上执行单条命令 (并行或串行等)
>>> from fabric import SerialGroup
>>> result = SerialGroup('web1', 'web2').run('hostname')
web1
web2
>>> # Sorting for consistency...it's a dict!
>>> sorted(result.items())
[(<Connection host=web1>, <Result cmd='hostname' exited=0>), ...]
- 执行代码块(方法/函数)
>>> def disk_free(c):
... uname = c.run('uname -s', hide=True)
... if 'Linux' in uname.stdout:
... command = "df -h / | tail -n1 | awk '{print $5}'"
... return c.run(command, hide=True).stdout.strip()
... err = "No idea how to get disk space on {}!".format(uname)
... raise Exit(err)
...
>>> print(disk_free(Connection('web1')))
33%
- 在多台主机执行代码块
>>> # NOTE: Same code as above!
>>> def disk_free(c):
... uname = c.run('uname -s', hide=True)
... if 'Linux' in uname.stdout:
... command = "df -h / | tail -n1 | awk '{print $5}'"
... return c.run(command, hide=True).stdout.strip()
... err = "No idea how to get disk space on {}!".format(uname)
... raise Exit(err)
...
>>> for cxn in SerialGroup('web1', 'web2', 'db1'):
... print("{}: {}".format(cxn, disk_free(cxn)))
<Connection host=web1>: 33%
<Connection host=web2>: 17%
<Connection host=db1>: 2%