Skip to main content

Execution helpers for simplified usage of subprocess and ssh.

Project description

exec-helpers

https://travis-ci.com/python-useful-helpers/exec-helpers.svg?branch=master https://dev.azure.com/python-useful-helpers/exec-helpers/_apis/build/status/python-useful-helpers.exec-helpers?branchName=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.6
Python 3.7

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

  • async_api.Subprocess - the same, as Subprocess helper, but works with asyncio. .. note:: for Windows ProactorEventLoop or another non-standard event loop should be used!

  • 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

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 SSHClient and Subprocess, except specific flags.

result: ExecResult = helper.execute(
    command,  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: typing.Union[int, float, None]
    # Keyword only:
    log_mask_re=None,  # type: typing.Optional[str]
    stdin=None,  # type: typing.Union[bytes, str, bytearray, None]
    **kwargs
)
result: ExecResult = 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=(0,),  # type: typing.Iterable[typing.Union[int, ExitCodes]]
    raise_on_err=True,  # type: bool
    # Keyword only:
    log_mask_re=None,  # type: typing.Optional[str]
    stdin=None,  # type: typing.Union[bytes, str, bytearray, None]
    exception_class=CalledProcessError,  # typing.Type[CalledProcessError]
    **kwargs
)
result: ExecResult = 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
    # Keyword only:
    expected=(0,),  # typing.Iterable[typing.Union[int, ExitCodes]]
    log_mask_re=None,  # type: typing.Optional[str]
    stdin=None,  # type: typing.Union[bytes, str, bytearray, None]
    exception_class=CalledProcessError,  # typing.Type[CalledProcessError]
)
result: ExecResult = helper(  # Lazy way: instances are callable and uses `execute`.
    command,  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: typing.Union[int, float, None]
    # Keyword only:
    log_mask_re=None,  # type: typing.Optional[str]
    stdin=None,  # type: typing.Union[bytes, str, bytearray, None]
    **kwargs
)

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 provided with command. All regex matched groups will be replaced by ‘<*masked*>’.

result: ExecResult = 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 keyword arguments, dimensions in pixels are always 0x0.

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

results: Dict[Tuple[str, int], ExecResult] = SSHClient.execute_together(
    remotes,  # type: typing.Iterable[SSHClient]
    command,  # type: str
    timeout=1 * 60 * 60,  # type: type: typing.Union[int, float, None]
    expected=(0,),  # type: typing.Iterable[typing.Union[int, ExitCodes]]
    raise_on_err=True,  # type: bool
    # Keyword only:
    stdin=None,  # type: typing.Union[bytes, str, bytearray, None]
    log_mask_re=None,  # type: typing.Optional[str]
    exception_class=ParallelCallProcessError  # typing.Type[ParallelCallProcessError]
)
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: ExecResult = 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
    # Keyword only:
    stdin=None,  # type: typing.Union[bytes, str, bytearray, None]
    log_mask_re=None,  # type: typing.Optional[str]
    get_pty=False,  # type: bool
    width=80,  # type: int
    height=24  # type: int
)

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

Keyword arguments:

  • cwd - working directory.

  • env - environment variables dict.

async_api.Subprocess specific

All standard methods are coroutines. Async context manager also available.

Example:

async with helper:
  result: ExecResult = await helper.execute(
      command,  # type: str
      verbose=False,  # type: bool
      timeout=1 * 60 * 60,  # type: typing.Union[int, float, None]
      **kwargs
  )

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. Azure Pipelines: is used for windows compatibility checking.

  3. coveralls: is used for coverage display.

Project details


Release history Release notifications | RSS feed

This version

4.2.0

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-4.2.0.tar.gz (60.3 kB view details)

Uploaded Source

Built Distributions

exec_helpers-4.2.0-py3-none-any.whl (54.7 kB view details)

Uploaded Python 3

exec_helpers-4.2.0-cp37-cp37m-win_amd64.whl (785.3 kB view details)

Uploaded CPython 3.7m Windows x86-64

exec_helpers-4.2.0-cp37-cp37m-win32.whl (680.1 kB view details)

Uploaded CPython 3.7m Windows x86

exec_helpers-4.2.0-cp37-cp37m-manylinux1_x86_64.whl (3.3 MB view details)

Uploaded CPython 3.7m

exec_helpers-4.2.0-cp37-cp37m-manylinux1_i686.whl (3.0 MB view details)

Uploaded CPython 3.7m

exec_helpers-4.2.0-cp36-cp36m-win_amd64.whl (784.8 kB view details)

Uploaded CPython 3.6m Windows x86-64

exec_helpers-4.2.0-cp36-cp36m-win32.whl (679.8 kB view details)

Uploaded CPython 3.6m Windows x86

exec_helpers-4.2.0-cp36-cp36m-manylinux1_x86_64.whl (3.3 MB view details)

Uploaded CPython 3.6m

exec_helpers-4.2.0-cp36-cp36m-manylinux1_i686.whl (3.0 MB view details)

Uploaded CPython 3.6m

File details

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

File metadata

  • Download URL: exec-helpers-4.2.0.tar.gz
  • Upload date:
  • Size: 60.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for exec-helpers-4.2.0.tar.gz
Algorithm Hash digest
SHA256 2e7889013b087f1be9266566bd524c4b83f03530203d0e3c7cd50c9a0313fef1
MD5 dc9e6076b5a1947e80c28ab04daf6a24
BLAKE2b-256 98e2aceea08d4b51ac6863d3fc9c0fa20a2870c342cc2597e26699158e32b411

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-4.2.0-py3-none-any.whl
  • Upload date:
  • Size: 54.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for exec_helpers-4.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ec8f3cec4b60f50a0da701e212c7d8ce5385a08a8a40fee60f83dd59de64b970
MD5 7567fb0583f38d0a1c2c5af14ae13570
BLAKE2b-256 e12df29c2d3edf8957cd6c8c56facdf1e6e4422cd6b8e36e327eff86e4cdddd4

See more details on using hashes here.

File details

Details for the file exec_helpers-4.2.0-cp37-cp37m-win_amd64.whl.

File metadata

  • Download URL: exec_helpers-4.2.0-cp37-cp37m-win_amd64.whl
  • Upload date:
  • Size: 785.3 kB
  • Tags: CPython 3.7m, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for exec_helpers-4.2.0-cp37-cp37m-win_amd64.whl
Algorithm Hash digest
SHA256 762ba688d22812700c7dc00531b86c8391482ffddc96023e937e2f4cc6c286bf
MD5 122a80ee543417a36b005fc56ec5f3f1
BLAKE2b-256 bbf2d0d972a89e6782c4d6fe0de85f8bda7a2a97a3c196a8f2a985b826edc22f

See more details on using hashes here.

File details

Details for the file exec_helpers-4.2.0-cp37-cp37m-win32.whl.

File metadata

  • Download URL: exec_helpers-4.2.0-cp37-cp37m-win32.whl
  • Upload date:
  • Size: 680.1 kB
  • Tags: CPython 3.7m, Windows x86
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for exec_helpers-4.2.0-cp37-cp37m-win32.whl
Algorithm Hash digest
SHA256 4e241d584bbb96449ff09a75b0f6743da5bf7a04d221266869408d672fa920fd
MD5 9fa45513862051abef36677079c8ec13
BLAKE2b-256 26b91b2355635f5daed3d67f2471f28e15a1b2e892151487baee1d7ce3eed339

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-4.2.0-cp37-cp37m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 3.3 MB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for exec_helpers-4.2.0-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 8999460ab64421932e82caea0ed9b0d30c4ce2e7d658817fc21394e1193f3d48
MD5 5918aca1f910c2b9302a229691cf830d
BLAKE2b-256 e7f7d904ac50c97fa37a61ec34639026d4dfd4933abb8d3ca3feef7a363dfa0d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-4.2.0-cp37-cp37m-manylinux1_i686.whl
  • Upload date:
  • Size: 3.0 MB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for exec_helpers-4.2.0-cp37-cp37m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 c41ee405cc374759daeb633a3ff05fabc23433fbe41647d58705723840d8e9d3
MD5 32537cf97a0f480e60d7937dead5237e
BLAKE2b-256 74d2b3ad2bf8d42cf61d8aab2dbb2725478d1dba296c387d022ec67d8a361552

See more details on using hashes here.

File details

Details for the file exec_helpers-4.2.0-cp36-cp36m-win_amd64.whl.

File metadata

  • Download URL: exec_helpers-4.2.0-cp36-cp36m-win_amd64.whl
  • Upload date:
  • Size: 784.8 kB
  • Tags: CPython 3.6m, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.8

File hashes

Hashes for exec_helpers-4.2.0-cp36-cp36m-win_amd64.whl
Algorithm Hash digest
SHA256 47d91ca3478c335dc6e94dbbc28166d831ef4e1cf518c5070802ff62f35ea83b
MD5 551419df780fc0852ebdb98e893b7552
BLAKE2b-256 9cae5fbcf830f47d31fc39fe495e333efd9c9ffb9721f701e317fbefba1619f2

See more details on using hashes here.

File details

Details for the file exec_helpers-4.2.0-cp36-cp36m-win32.whl.

File metadata

  • Download URL: exec_helpers-4.2.0-cp36-cp36m-win32.whl
  • Upload date:
  • Size: 679.8 kB
  • Tags: CPython 3.6m, Windows x86
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.8

File hashes

Hashes for exec_helpers-4.2.0-cp36-cp36m-win32.whl
Algorithm Hash digest
SHA256 335a1c32d5e23bf2dd9f65014345df52a83ae32181f9408984906428c00a4af0
MD5 0ee776acbcedbf21c2c8e808a48a9af9
BLAKE2b-256 e5049248de18fc7af26b775f63746b275b701bdad680a2fed51e22a64b8e9d17

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-4.2.0-cp36-cp36m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 3.3 MB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for exec_helpers-4.2.0-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 ed90086ca25794075af7b892bc6564a87a8ed3c6167cec67c0d5fb0b45af36bf
MD5 c22fc31666a34f72e2430c86858525f2
BLAKE2b-256 8f58aff216d25b9c5f9f3b7bb4f8f0eeebd014dfee05de24d8cdc5283c83522d

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-4.2.0-cp36-cp36m-manylinux1_i686.whl
  • Upload date:
  • Size: 3.0 MB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.1

File hashes

Hashes for exec_helpers-4.2.0-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 8193c982e23e9d9f086f3a1fd0fdf3275f8d74a7da04cacb28a817f88b99b627
MD5 90093d4716c7fdc7118b49230c832f7d
BLAKE2b-256 3c37ce582cfb1a2de6bc748452034056c0ee6d91c15007bde5c823d451dfb9d8

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