Programing/Python

Python Fabric

BUST 2018. 7. 29. 12:17

Python Fabric


Single Command

>>> 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>), ...]


Command with python code

>>> 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%


'Programing > Python' 카테고리의 다른 글

OpenpyXL를 이용하여 Excel 파일 읽기  (1) 2017.06.27