Python/Fabric2

From Omnia
Revision as of 01:13, 20 August 2023 by Kenneth (talk | contribs) (→‎Sudo)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Fabric 2

https://www.fabfile.org/
>>> 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

Installation

Basic install:

pip install fabric

To not conflict with v1 (have both installed):

pip3 install fabric2

Basic Connection

import fabric2

cn = fabric2.Connection('user@somesystem')
cn.config.run.warn=True  # don't abort on failure
cn.run('hostname')  # remote execution
cn.local('hostname')  # local execution

Specify Password and Port

    conn = Connection(
    "{username}@{ip}:{port}".format(
        username=username,
        ip=ip,
        port=port,
        ),
    connect_kwargs={"password": password},
)

ref: [1]

Don't throw exception of failure

# Fabric runner connection to Crashbox
self.crashbox = fabric2.Connection(f"{self.crashboxuser}@{self.crashboxip}:{self.sshport}", connect_kwargs={"password": self.crashboxpass})
self.crashbox.config.run.warn = True
self.crashbox.config.run.echo = True

run

f = fabric2.Connection('localhost')
f.run('ls')
# handle a non 0 return code, if run.warn
if f.run(cmd).failed:
  print("failure")
# timeout
f.run(cmd, timeout=seconds)
  # throws invoke.exceptions.CommandTimedOut

Interesting Parameters:

echo=False  # print command to local stdout?
timeout=seconds  # timeout command - default no timeout
shell='/bin/bash'
warn=False # warn and continue or raise UnexpectedExit on non zero return code


ref: [2] [3]

CD

con = fabric2.Connection('localhost')
with con.cd('/etc'):
  con.run('pwd')  # should display /etc

ref: [4]

Sudo

con = fabric2.Connection('localhost')
con.sudo('mkdir /test')

Interesting parameters:

Should be the same as sudo.run?

ref: [5] [6]

Put

con = fabric2.Connection('localhost')
con.put('test.txt', "/tmp/test.txt")

keywords

Python Fabric Fabric2 Paramiko