Python/Fabric

From Omnia
Jump to navigation Jump to search

Fabric2

See Python/Fabric2

Simple Local

# local(command, capture=False, shell=None)
from fabric.api import local
local('hostname')

Simple Remote

from fabric.api import env
from fabric.api import run

env.host_string = 'some_node'
env.user = 'some_user'
env.password = 'some_pass'
run('hostname')

Kind of ugly:

from fabric.api import env
from fabric.api import settings
from fabric.api import run

crash_host = {'host_string': 'some-node',
                              'user': 'root',
                              'password': 'password',
                              'command_timeout': 10,
                              'connection_attempts': 1,
                              'abort_on_prompts': True}


with settings(**crash_host):
  run('hostname')

Handle a non zero return code

Normally Fabric aborts the program on a failure, which is just stupid

For all:

env.warn_only = True

or per command:

rc = run('aaa', warn_only=True)
if rc.failed:
   print("failure with {}".format(rc.return_code))
if rc.succeeded:
   print("Happy")

change directory

from fabric.api import env, run
from fabric.context_managers import cd

env.host_string = 'localhost'

with cd('welcome'):
    run("echo 'hi' > hello.txt")

ref: [1]

Sample Put / Get

#!/usr/bin/python

from fabric.api import env
from fabric.operations import run, put, get

env.host_string = "somenode"
env.user = "user"
env.password = "password"

# put local file on remote node
put('test.zip', '/tmp/test.zip')

# copy remote file on local
get('/tmp/test.zip', 'test2.zip')

# verify md5sum
run('md5sum /tmp/test.zip', timeout=1)
result = run('pwd')
print(result.return_code)
print(result)  # combined output
print(result.stdout)
print(result.stderr)
print(result.failed) # True or False

Windows struggles, but this seemed to work:

from fabric import api as fab  # pylint: disable=import-error
from fabric.exceptions import CommandTimeout # Gets the class for CommandTimeout exception
import sys

fab_test_settings = fab.settings(
        host_string='HOSTNAME',
        user='USER',
        password='PASSWORD',
        abort_on_prompts=True,
        keepalive=30)

with fab_test_settings:
    fab.run('dir', shell=False, pty=False, warn_only=False, timeout=None, quiet=False, stdout=sys.stdout, combine_stderr=True)

API

https://docs.fabfile.org/en/1.14/api/core/operations.html

run() also has a timeout in seconds

fabric.operations.run(command, shell=True, pty=True, combine_stderr=None, quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None, shell_escape=None, capture_buffer_size=None)

Other ENV paramters:

https://docs.fabfile.org/en/1.14/usage/env.html

Paramiko Logging

import logging
logging.basicConfig(level=logging.DEBUG)

Lots of logs, but no logs during the actual copy.

keywords