Github: fabric/fabric
Doc: Fabric
Fabic 是用于通过SSH 远程执行 shell 命令的封装库. 基于 Invoke (subprocess command execution and command-line features) 和Paramiko (SSH protocol implementation).
安装:
#1.x version
pip install fabric
pip install -e git+https://github.com/fabric/fabric
#2.x version, recommended
pip install fabric2
示例:
from fabric import Connection
result = Connection('192.168.1.100').run('uname -s', hide=True)
msg = "Run {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
print(msg.format(result))
'''
Run 'uname -s' 192.168.1.100, got stdout:
Linux
'''
单机单命令
from fabric import Connection
result = Connection('web1').run('hostname')
#web1
print(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!
print(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')))
多机代码块
# 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%
'''