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 2.7
Python 3.4
Python 3.5
Python 3.6
Python 3.7
PyPy
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.Optional[int]
    **kwargs
)
result = helper.check_call(
    command,  # type: str
    verbose=False,  # type: bool
    timeout=1 * 60 * 60,  # type: typing.Optional[int]
    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: typing.Optional[int]
    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 -> six.text_types. Text representation of output.

  • stderr_str -> six.text_types. Text representation of output.

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

  • stderr_brief -> six.text_types. 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: typing.Optional[int]
    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: typing.Optional[int]
    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

1.3.3

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

Uploaded Source

Built Distributions

exec_helpers-1.3.3-py2-none-any.whl (39.8 kB view details)

Uploaded Python 2

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

Uploaded CPython 3.7m

exec_helpers-1.3.3-cp37-cp37m-manylinux1_i686.whl (1.8 MB view details)

Uploaded CPython 3.7m

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

Uploaded CPython 3.6m

exec_helpers-1.3.3-cp36-cp36m-manylinux1_i686.whl (1.8 MB view details)

Uploaded CPython 3.6m

exec_helpers-1.3.3-cp35-cp35m-manylinux1_x86_64.whl (1.8 MB view details)

Uploaded CPython 3.5m

exec_helpers-1.3.3-cp35-cp35m-manylinux1_i686.whl (1.7 MB view details)

Uploaded CPython 3.5m

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

Uploaded CPython 3.4m

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

Uploaded CPython 3.4m

File details

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

File metadata

File hashes

Hashes for exec-helpers-1.3.3.tar.gz
Algorithm Hash digest
SHA256 faee00f0f8530c47743f3b00fde72ca9b35139f1b7d4d048c90573709c6ce4b7
MD5 7cef9f95b65a06f9abb597c1ace16bb3
BLAKE2b-256 98f97b4852106d26586d19902151de93af0af9ee680590241c186cde33494f3a

See more details on using hashes here.

File details

Details for the file exec_helpers-1.3.3-py2-none-any.whl.

File metadata

File hashes

Hashes for exec_helpers-1.3.3-py2-none-any.whl
Algorithm Hash digest
SHA256 d3853276b23e371c8b70cd231269ed2b3ad7d0b30b94b60ba52aad44f5698c64
MD5 f0a9e918ee31a3425b3105fe9f395190
BLAKE2b-256 6b6ac082d5d8fd3095e4b4bd5c570f98bed8e778cc72ae267cfb654979474125

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 1c181cb9895463ca54e107d75113a4c96518997e929e70158dc5c0d19cfcd69f
MD5 72f9883cdb9fe77f2ad77796412233d0
BLAKE2b-256 c45692a8e682af50dd66d26d4d3ded56a2a94ff7c1d1db74329a17a3fc9cde04

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp37-cp37m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 69bc0c7c66bcf44fc43dbd314f7d576f10388ff477c13a7d7b75a89878557ce1
MD5 f423289fb4a4655d5729d4cb6cc9daff
BLAKE2b-256 b53b6254d5c35ced677825a04493324a1c2617dbd704f50169753c73c0ea4f64

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 c71c603e469200cbc29a9e90d6bdcfd96bf09a72029bea734859b1943a74e19f
MD5 7b0c54aee46d8e334b9339449ebdc3cb
BLAKE2b-256 30d1797eea47ab3231be47f1ce95b77757ef657202d2b592924d0ca265544fcb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 be084e117c314dd667770662f54b0024c8cfb1c9fdd5433d574e3ec8e64b6229
MD5 7e1e58651292f9fb0798cf7cd92fee74
BLAKE2b-256 c4ea0dbb7102aed5fee494d9dcbbcc047e86c36d58b8f8b857769119fbdf27f9

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7d7d3618d1d67309d764b412ea0efb9a3097a91428fa0c3440316d099448f139
MD5 33b09b30ef1a9fd950861fb0aad88646
BLAKE2b-256 d0246a16ffcd6e1128c04b88f796c5eaf6a208c8d4c46a70ea51cf4b4dfb051e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 95b04eff207351cd13639af319db3d9a21eb6c454b299e41b76239472709b0dc
MD5 3cdc6d8fc1d3e86c78fab02642fe3246
BLAKE2b-256 614118351d20a00085b6865f21da087313699f211feb7b7c922107fb0d9e6eb8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp34-cp34m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 ae835b9596bfd50a17dc42a1253d4924c606888a290b50818db42ca0fce381ba
MD5 cbd8121aae90590c228078c61498a1fa
BLAKE2b-256 5100fbc1efac24be82a539160067eb0fc2a6225df2f92704d6772c0b9806aec2

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.3.3-cp34-cp34m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 492e8e66462610723a27f947ac4f00482ef698aef156f3518d1ce4878abdaa53
MD5 1edd27d15301886dce803d07d042609e
BLAKE2b-256 28e25f275bf9cddc92453fb6d3881f0dc248efa84d95c316fe077121f6c62610

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