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

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

This version

2.0.2

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

Uploaded Source

Built Distributions

exec_helpers-2.0.2-py3-none-any.whl (34.1 kB view details)

Uploaded Python 3

exec_helpers-2.0.2-cp37-cp37m-manylinux1_x86_64.whl (1.9 MB view details)

Uploaded CPython 3.7m

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

Uploaded CPython 3.7m

exec_helpers-2.0.2-cp36-cp36m-manylinux1_x86_64.whl (1.9 MB view details)

Uploaded CPython 3.6m

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

Uploaded CPython 3.6m

exec_helpers-2.0.2-cp35-cp35m-manylinux1_x86_64.whl (1.9 MB view details)

Uploaded CPython 3.5m

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

Uploaded CPython 3.5m

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

Uploaded CPython 3.4m

exec_helpers-2.0.2-cp34-cp34m-manylinux1_i686.whl (1.9 MB view details)

Uploaded CPython 3.4m

File details

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

File metadata

  • Download URL: exec-helpers-2.0.2.tar.gz
  • Upload date:
  • Size: 36.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 PyPy/5.10.1

File hashes

Hashes for exec-helpers-2.0.2.tar.gz
Algorithm Hash digest
SHA256 3c2886ce39420db7a365f9b68d96cdc32e9673fe787ce6ca45baac4700fe46c1
MD5 83ff7aeb6e5b81928271e75d2194c58f
BLAKE2b-256 c03dd2852dc4662f608e90567e310f4e3d54b8c5fd6695ee98db549b3e674f88

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-py3-none-any.whl
  • Upload date:
  • Size: 34.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 PyPy/5.10.1

File hashes

Hashes for exec_helpers-2.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 73d6f902829010ec4175f299f7cd82abe0ef67725fc735b37c7c705cc6506767
MD5 42b85e1e309f0ade33c278a07b2dd920
BLAKE2b-256 4e954de0ce73bc53892a7ca0f11d74c13ec3f33996da628a1e4de4a148362a61

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-cp37-cp37m-manylinux1_x86_64.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.0.2-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 8a5be45a0a694eec56f220d39c197e608fd7ee2969e4e164bd74906da5a2cdd7
MD5 2cb4e8718f02b8f1b4731aed41028855
BLAKE2b-256 e909c5d66a2980e9f0de710d72d535af589878a8e28c4ac2ba2453694163aa8c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-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.0.2-cp37-cp37m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 d765bc71a20f9d62dc9f9dfa1553041d4ed64680fb3d12e7edb2fe333d84eddd
MD5 d9aa0b1e92831d8b177b4537e1de47f4
BLAKE2b-256 d0e9d4691761c5cb85080598650f3c5f97b85ce0d9337d892449097fa195ffdc

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-cp36-cp36m-manylinux1_x86_64.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.0.2-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c6cf66e34d59fc6c0194b8b5826e566d547123c73b6fcd3425f14a23633e7c79
MD5 1e46fb09ec23240b0ad05c86164d29f2
BLAKE2b-256 24ad3c93bc5e7f10ca1a32ac389c0ceb6de13045ef107fb891cdbef015253bad

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-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.0.2-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 3429ae1f1d464cdb2d30c21d58fb7c0536a24c6d764427ac802f0a5c2d63dd66
MD5 762cc23255b191990e2e2634cf103402
BLAKE2b-256 a4ec973199aa77a2c652838e60c17be0ec471a6082b68d85d70efe44a1049631

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-cp35-cp35m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 1.9 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.0.2-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 df70f6ccb054c9317156a0fb96f468df5e38c9b04216bfffff68c653e52bb1f3
MD5 aeaa5266621a1828aef567bb30e7ae57
BLAKE2b-256 6847969a47ad42d201a5d7af0c34af63b8a92c53ad451a57e57c0abd2aef2182

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-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.0.2-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 e6a3836a6b48ca22bb6cb7385837e55bf54a0b39f4d7e32035e7bdb253b5073a
MD5 ab53666cd682559a5d65846dcff798b0
BLAKE2b-256 52f6428bd4cb501d68c51525a011970fe0cf4732aef6840ac2519eb088175d3a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-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.0.2-cp34-cp34m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 11e835297a94778463217b6e3b00c11b7a903fb5ca2b3bf2290addb188f4edeb
MD5 a93d46c246168c7fe92c9f3936e3fe08
BLAKE2b-256 68b402e35d76b5d1b93a87406e0e32da41e4a8b322f580ede967ac6c979db1d3

See more details on using hashes here.

File details

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

File metadata

  • Download URL: exec_helpers-2.0.2-cp34-cp34m-manylinux1_i686.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.0.2-cp34-cp34m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 076f759937d4e08a4d14bf67782b4b7478356691a0090f02c6afbff1afb64437
MD5 b6bac19bcd08f66c75c18b00a15a6437
BLAKE2b-256 280079aa8f6701c105d954f0fce5d64b79b6b51c07a0b5d92e236fc6dac29028

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