Skip to main content

Execution helpers for simplified usage of subprocess and ssh.

Project description

exec-helpers

https://travis-ci.org/python-useful-helpers/exec-helpers.svg?branch=master https://coveralls.io/repos/github/python-useful-helpers/exec-helpers/badge.svg?branch=master Documentation Status https://img.shields.io/pypi/v/exec-helpers.svg https://img.shields.io/pypi/pyversions/exec-helpers.svg https://img.shields.io/pypi/status/exec-helpers.svg https://img.shields.io/github/license/python-useful-helpers/exec-helpers.svg https://img.shields.io/badge/code%20style-black-000000.svg

Execution helpers for simplified usage of subprocess and ssh. Why another subprocess wrapper and why no clear paramiko?

Historically paramiko offers good ssh client, but with specific limitations: you can call command with timeout, but without receiving return code, or call command and wait for return code, but without timeout processing.

In the most cases, we are need just simple SSH client with comfortable API for calls, calls via SSH proxy and checking return code/stderr. This library offers this functionality with connection memorizing, deadlock free polling and friendly result objects (with inline decoding of YAML, JSON, binary or just strings). In addition this library offers the same API for subprocess calls, but with specific limitation: no parallel calls (for protection from race conditions).

Pros:

Python 3.4
Python 3.5
Python 3.6
Python 3.7
PyPy3 3.5+

This package includes:

  • SSHClient - historically the first one helper, which used for SSH connections and requires memorization due to impossibility of connection close prediction. Several API calls for sFTP also presents.

  • SSHAuth - class for credentials storage. SSHClient does not store credentials as-is, but uses SSHAuth for it. Objects of this class can be copied between ssh connection objects, also it used for execute_through_host.

  • Subprocess - subprocess.Popen wrapper with timeouts, polling and almost the same API, as SSHClient (except specific flags, like cwd for subprocess and get_tty for ssh).

  • ExecResult - class for execution results storage. Contains exit code, stdout, stderr and getters for decoding as JSON, YAML, string, bytearray and brief strings (up to 7 lines).

  • ExitCodes - enumerator for standard Linux exit codes. BASH return codes (broduced from signal codes) also available.

Usage

SSHClient

Basic initialization of SSHClient can be done without construction of specific objects:

client = exec_helpers.SSHClient(host, username="username", password="password")

If ssh agent is running - keys will be collected by paramiko automatically, but if keys are in specific location - it should be loaded manually and provided as iterable object of paramiko.RSAKey.

For advanced cases or re-use of credentials, SSHAuth object should be used. It can be collected from connection object via property auth.

Creation from scratch:

auth = exec_helpers.SSHAuth(
    username='username',  # type: typing.Optional[str]
    password='password',  # type: typing.Optional[str]
    key=None,  # type: typing.Optional[paramiko.RSAKey]
    keys=None,  # type: typing.Optional[typing.Iterable[paramiko.RSAKey]],
    key_filename=None,  # type: typing.Union[typing.List[str], str, None]
    passphrase=None,  # type: typing.Optional[str]
)

Key is a main connection key (always tried first) and keys are alternate keys. Key filename is afilename or list of filenames with keys, which should be loaded. Passphrase is an alternate password for keys, if it differs from main password. If main key now correct for username - alternate keys tried, if correct key found - it became main. If no working key - password is used and None is set as main key.

Context manager is available, connection is closed and lock is released on exit from context.

Subprocess

No initialization required. Context manager is available, subprocess is killed and lock is released on exit from context.

Base methods

Main methods are execute, check_call and check_stderr for simple executing, executing and checking return code and executing, checking return code and checking for empty stderr output. This methods are almost the same for SSHCleint and Subprocess, except specific flags.

result = helper.execute(
    command,  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: typing.Union[int, float, None]
    **kwargs
)
result = helper.check_call(
    command,  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: type: typing.Union[int, float, None]
    error_info=None,  # type: typing.Optional[str]
    expected=None,  # type: typing.Optional[typing.Iterable[int]]
    raise_on_err=True,  # type: bool
    **kwargs
)
result = helper.check_stderr(
    command,  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: type: typing.Union[int, float, None]
    error_info=None,  # type: typing.Optional[str]
    raise_on_err=True,  # type: bool
)

If no STDOUT or STDERR required, it is possible to disable this FIFO pipes via **kwargs with flags open_stdout=False and open_stderr=False.

The next command level uses lower level and kwargs are forwarded, so expected exit codes are forwarded from check_stderr. Implementation specific flags are always set via kwargs.

If required to mask part of command from logging, log_mask_re attribute can be set global over instance or providden with command. All regex matched groups will be replaced by ‘<*masked*>’.

result = helper.execute(
    command="AUTH='top_secret_key'; run command",  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: typing.Optional[int]
    log_mask_re=r"AUTH\s*=\s*'(\w+)'"  # type: typing.Optional[str]
)

result.cmd will be equal to AUTH=’<*masked*>’; run command

ExecResult

Execution result object has a set of useful properties:

  • cmd - Command

  • exit_code - Command return code. If possible to decode using enumerators for Linux -> it used.

  • stdin -> str. Text representation of stdin.

  • stdout -> typing.Tuple[bytes]. Raw stdout output.

  • stderr -> typing.Tuple[bytes]. Raw stderr output.

  • stdout_bin -> bytearray. Binary stdout output.

  • stderr_bin -> bytearray. Binary stderr output.

  • stdout_str -> str. Text representation of output.

  • stderr_str -> str. Text representation of output.

  • stdout_brief -> str. Up to 7 lines from stdout (3 first and 3 last if >7 lines).

  • stderr_brief -> str. Up to 7 lines from stderr (3 first and 3 last if >7 lines).

  • stdout_json - STDOUT decoded as JSON.

  • stdout_yaml - STDOUT decoded as YAML.

  • timestamp -> typing.Optional(datetime.datetime). Timestamp for received exit code.

SSHClient specific

SSHClient commands support get_pty flag, which enables PTY open on remote side. PTY width and height can be set via kwargs, dimensions in pixels are always 0x0.

Possible to call commands in parallel on multiple hosts if it’s not produce huge output:

results = SSHClient.execute_together(
    remotes,  # type: typing.Iterable[SSHClient]
    command,  # type: str
    timeout=1 * 60 * 60,  # type: type: typing.Union[int, float, None]
    expected=None,  # type: typing.Optional[typing.Iterable[int]]
    raise_on_err=True  # type: bool
)
results  # type: typing.Dict[typing.Tuple[str, int], exec_result.ExecResult]

Results is a dict with keys = (hostname, port) and and results in values. By default execute_together raises exception if unexpected return code on any remote.

For execute through SSH host can be used execute_through_host method:

result = client.execute_through_host(
    hostname,  # type: str
    command,  # type: str
    auth=None,  # type: typing.Optional[SSHAuth]
    target_port=22,  # type: int
    timeout=1 * 60 * 60,  # type: type: typing.Union[int, float, None]
    verbose=False,  # type: bool
    get_pty=False,  # type: bool
)

Where hostname is a target hostname, auth is an alternate credentials for target host.

SSH client implements fast sudo support via context manager: Commands will be run with sudo enforced independently from client settings for normal usage:

with client.sudo(enforce=True):
    ...

Commands will be run without sudo independently from client settings for normal usage:

with client.sudo(enforce=False):
    ...

“Permanent client setting”:

client.sudo_mode = mode  # where mode is True or False

SSH Client supports sFTP for working with remote files:

with client.open(path, mode='r') as f:
    ...

For fast remote paths checks available methods:

  • exists(path) -> bool

>>> conn.exists('/etc/passwd')
True
  • stat(path) -> paramiko.sftp_attr.SFTPAttributes

>>> conn.stat('/etc/passwd')
<SFTPAttributes: [ size=1882 uid=0 gid=0 mode=0o100644 atime=1521618061 mtime=1449733241 ]>
>>> str(conn.stat('/etc/passwd'))
'-rw-r--r--   1 0        0            1882 10 Dec 2015  ?'
  • isfile(path) -> bool

>>> conn.isfile('/etc/passwd')
True
  • isdir(path) -> bool

>>> conn.isdir('/etc/passwd')
False

Additional (non-standard) helpers:

  • mkdir(path: str) - execute mkdir -p path

  • rm_rf(path: str) - execute rm -rf path

  • upload(source: str, target: str) - upload file or from source to target using sFTP.

  • download(destination: str, target: str) - download file from target to destination using sFTP.

Subprocess specific

Kwargs set properties:

  • cwd - working directory.

  • env - environment variables dict.

Testing

The main test mechanism for the package exec-helpers is using tox. Available environments can be collected via tox -l

CI systems

For code checking several CI systems is used in parallel:

  1. Travis CI: is used for checking: PEP8, pylint, bandit, installation possibility and unit tests. Also it’s publishes coverage on coveralls.

  2. coveralls: is used for coverage display.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

exec-helpers-2.1.3.tar.gz (37.9 kB view details)

Uploaded Source

Built Distributions

exec_helpers-2.1.3-py3-none-any.whl (39.6 kB view details)

Uploaded Python 3

exec_helpers-2.1.3-cp37-cp37m-manylinux1_x86_64.whl (2.1 MB view details)

Uploaded CPython 3.7m

exec_helpers-2.1.3-cp37-cp37m-manylinux1_i686.whl (1.9 MB view details)

Uploaded CPython 3.7m

exec_helpers-2.1.3-cp36-cp36m-manylinux1_x86_64.whl (2.1 MB view details)

Uploaded CPython 3.6m

exec_helpers-2.1.3-cp36-cp36m-manylinux1_i686.whl (1.9 MB view details)

Uploaded CPython 3.6m

exec_helpers-2.1.3-cp35-cp35m-manylinux1_x86_64.whl (2.0 MB view details)

Uploaded CPython 3.5m

exec_helpers-2.1.3-cp35-cp35m-manylinux1_i686.whl (1.8 MB view details)

Uploaded CPython 3.5m

exec_helpers-2.1.3-cp34-cp34m-manylinux1_x86_64.whl (1.9 MB view details)

Uploaded CPython 3.4m

exec_helpers-2.1.3-cp34-cp34m-manylinux1_i686.whl (1.8 MB view details)

Uploaded CPython 3.4m

File details

Details for the file exec-helpers-2.1.3.tar.gz.

File metadata

  • Download URL: exec-helpers-2.1.3.tar.gz
  • Upload date:
  • Size: 37.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.20.0 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.28.1 PyPy/5.10.1

File hashes

Hashes for exec-helpers-2.1.3.tar.gz
Algorithm Hash digest
SHA256 56cee9e41d5f947629846c94ee803cfe97170aa97a7aa434c925d9b38f026bff
MD5 e4affd052524c8dea43f38314b417cae
BLAKE2b-256 ae7405215a8dd356b6d5cfa7f8674a173bc2fbc95ed290afcbbe2b2983950d1b

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-py3-none-any.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-py3-none-any.whl
  • Upload date:
  • Size: 39.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.12.1 pkginfo/1.4.2 requests/2.20.0 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.28.1 PyPy/5.10.1

File hashes

Hashes for exec_helpers-2.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 15598c1b84a845bc62e7d21ad95fe4f5e1ac3935867f7d520f39209662263232
MD5 b6ca2d47e628dc5b2437e022bd34d2fc
BLAKE2b-256 227e1e2e828aab31f85fe05758016bcbe31e12eb8167a8f5cd2e2ff7156cc000

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp37-cp37m-manylinux1_x86_64.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp37-cp37m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 2.1 MB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 b2adbd5295d980ad9adf57ec19335f2a9be9223d52c39a7435d359fbbe8febcc
MD5 25803d5bd11ffe3e400ad3eb3e83a285
BLAKE2b-256 6b860b67ac8939a4777b87c37b776d831e085fe34d54a985583dcdfeb59d9948

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp37-cp37m-manylinux1_i686.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp37-cp37m-manylinux1_i686.whl
  • Upload date:
  • Size: 1.9 MB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp37-cp37m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 8eda00129b3c02ad655dc8a6ad92880555b61651403272788bd9eb5399d3777d
MD5 e7a324f0893e2ba4c7b5618bfb5a352e
BLAKE2b-256 cf0ec6694ba84ddecfe96dbb2c35110de3436d78879278613056080197b83219

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp36-cp36m-manylinux1_x86_64.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp36-cp36m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 2.1 MB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7f68c26ace07f54c82c967e67b4bd67c72ea8512e7afd9e8c6ca61f05fe7be25
MD5 d6bb771c3c62fb466b12f2addd958dd9
BLAKE2b-256 e50c04282dfaf25d31eeff7153b12776c8807da698d3c4b6c45bac833cf67f3c

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp36-cp36m-manylinux1_i686.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp36-cp36m-manylinux1_i686.whl
  • Upload date:
  • Size: 1.9 MB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 eb5fb062dc46f7335431984b667ebdc63292c480b967e91b1ea0f12314b7a333
MD5 344bfdeb9e4c0ee1c177350f34b5e381
BLAKE2b-256 dda13670e1a8cf6eff284155d8a32857a0d39205b9e91d5b8bea720900763c65

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp35-cp35m-manylinux1_x86_64.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp35-cp35m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 2.0 MB
  • Tags: CPython 3.5m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 9fa5d630d20b4ec5d05b07c3cc335f0a90ac2b4d867608f16f6856658992a5da
MD5 5260b60d151804efcf861f101924f45d
BLAKE2b-256 76c0221c0f7c2883b048f3cafbfaddfc89c33a4bc7c478de823affb3dbeea93a

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp35-cp35m-manylinux1_i686.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp35-cp35m-manylinux1_i686.whl
  • Upload date:
  • Size: 1.8 MB
  • Tags: CPython 3.5m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 83433c630c6603a560fa657c38d19d60e833e5fcff01e5d352091167401497d1
MD5 872aae5e6c352075dec31cc29b83eb59
BLAKE2b-256 d20a300972352bfc846d6755b1e78ce25a1788ab382415f77cb8644b045fe2b6

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp34-cp34m-manylinux1_x86_64.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp34-cp34m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 1.9 MB
  • Tags: CPython 3.4m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp34-cp34m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 113547d0da673af7a006f7f73c5ccad78f0d209f4de6e8d5a54b12302b02bdea
MD5 02108aab357b0bc4f09266c8f3c83ba9
BLAKE2b-256 ffcf33698557d1bf69186eee461a44fe4b6dec10d1f950267476ffc8d6d71c8c

See more details on using hashes here.

File details

Details for the file exec_helpers-2.1.3-cp34-cp34m-manylinux1_i686.whl.

File metadata

  • Download URL: exec_helpers-2.1.3-cp34-cp34m-manylinux1_i686.whl
  • Upload date:
  • Size: 1.8 MB
  • Tags: CPython 3.4m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.6

File hashes

Hashes for exec_helpers-2.1.3-cp34-cp34m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 34150ec14695aa2b39643bb30a99087ce59e33a9dc95f64d7d570618e351dc2e
MD5 ab9e2dfec64ed93bdd2f5e3f9d277f18
BLAKE2b-256 a2536fa93f0dffaf64efe699554263adb77dfad8c929e241ed8f0eec35ed69b0

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page