Skip to main content

Execution helpers for simplified usage of subprocess and ssh.

Project description

exec-helpers

https://travis-ci.org/penguinolog/exec-helpers.svg?branch=master https://img.shields.io/appveyor/ci/penguinolog/exec-helpers.svg https://coveralls.io/repos/github/penguinolog/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/penguinolog/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
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=None,  # type: typing.Optional[int]
    **kwargs
)
result = helper.check_call(
    command,  # type: str
    verbose=False,  # type: bool
    timeout=None,  # 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=None,  # type: typing.Optional[int]
    error_info=None,  # type: typing.Optional[str]
    raise_on_err=True,  # type: bool
)

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.

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.

  • 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=None,  # 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=None,  # 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. Test environments available:

pep8
py27
py34
py35
py36
pypy
pypy3
pylint
pep257

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

  3. 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-1.1.0.tar.gz (492.2 kB view details)

Uploaded Source

Built Distributions

exec_helpers-1.1.0-cp36-none-win_amd64.whl (375.9 kB view details)

Uploaded CPython 3.6 Windows x86-64

exec_helpers-1.1.0-cp36-none-win32.whl (327.2 kB view details)

Uploaded CPython 3.6 Windows x86

exec_helpers-1.1.0-cp36-cp36m-manylinux1_x86_64.whl (1.7 MB view details)

Uploaded CPython 3.6m

exec_helpers-1.1.0-cp36-cp36m-manylinux1_i686.whl (1.6 MB view details)

Uploaded CPython 3.6m

exec_helpers-1.1.0-cp35-none-win_amd64.whl (366.7 kB view details)

Uploaded CPython 3.5 Windows x86-64

exec_helpers-1.1.0-cp35-none-win32.whl (320.7 kB view details)

Uploaded CPython 3.5 Windows x86

exec_helpers-1.1.0-cp35-cp35m-manylinux1_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.5m

exec_helpers-1.1.0-cp35-cp35m-manylinux1_i686.whl (1.5 MB view details)

Uploaded CPython 3.5m

exec_helpers-1.1.0-cp34-none-win_amd64.whl (359.3 kB view details)

Uploaded CPython 3.4 Windows x86-64

exec_helpers-1.1.0-cp34-none-win32.whl (326.7 kB view details)

Uploaded CPython 3.4 Windows x86

exec_helpers-1.1.0-cp34-cp34m-manylinux1_x86_64.whl (1.7 MB view details)

Uploaded CPython 3.4m

exec_helpers-1.1.0-cp34-cp34m-manylinux1_i686.whl (1.5 MB view details)

Uploaded CPython 3.4m

exec_helpers-1.1.0-cp27-none-win_amd64.whl (372.0 kB view details)

Uploaded CPython 2.7 Windows x86-64

exec_helpers-1.1.0-cp27-none-win32.whl (327.6 kB view details)

Uploaded CPython 2.7 Windows x86

exec_helpers-1.1.0-cp27-cp27mu-manylinux1_x86_64.whl (1.5 MB view details)

Uploaded CPython 2.7mu

exec_helpers-1.1.0-cp27-cp27mu-manylinux1_i686.whl (1.3 MB view details)

Uploaded CPython 2.7mu

File details

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

File metadata

File hashes

Hashes for exec-helpers-1.1.0.tar.gz
Algorithm Hash digest
SHA256 d4ccbe9477f64db74fe85089df89aefd7f04f16ba8fc11cd4f480da7f649fcff
MD5 a104f3088fa7b4c43c4ace2ff47c8a01
BLAKE2b-256 1195ed7b49f3dde1a0aa7392d61781656e9894ab11cfbd166b6e2f6916701196

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp36-none-win_amd64.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp36-none-win_amd64.whl
Algorithm Hash digest
SHA256 a739750ee2b214e4aaab4f4247709226dfcf4a9f2dde773d989793fed13b86f5
MD5 ea6b8385ac45fafc356edfba787e64e1
BLAKE2b-256 389cf21f78cab53408de141d269aef83950c69fa2d5c49e911a7ca793b4a3874

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp36-none-win32.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp36-none-win32.whl
Algorithm Hash digest
SHA256 50c71558b148670cefedfbd9a91172fe0007242680a9ae3c07b28626e2c5fcd9
MD5 7249a483ca7951b31aace8ce86cc7d50
BLAKE2b-256 3e00f620ade50bd94c401cb2ba009d197abfe57194ca1db0401a14b6f9a153a8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 0fb7acf42c50b06acc47854771d9581a5cb30caac12f03d2faec9cd422578a3d
MD5 302842bd463412e1bca3aae13e74a687
BLAKE2b-256 ce5e08d52c794265b3d9b8b0742c5c14496a6d1b3a8c0c3507ee948956f3fc30

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 e9bb9644864427428a845dfa18883b61cbc3d76c7fe80ce74855af8c7031e4aa
MD5 33ce68da098eb141a23b17fc6e7d8c5b
BLAKE2b-256 23e5d576e82cd381041dcb88b10aa70046a8112817c5a8779d745a2ef87d3c32

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp35-none-win_amd64.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp35-none-win_amd64.whl
Algorithm Hash digest
SHA256 f33a60adfc171dbf2fc31710163c04853ef74fe9e19fcbcc87e23b1c0efc5810
MD5 feb784eb3ebf58f4b3903c4afcb0ce2c
BLAKE2b-256 177480928b1cab228c6b41ec71fb71376f91c6ea407a95c2f8a4b902a7f671da

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp35-none-win32.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp35-none-win32.whl
Algorithm Hash digest
SHA256 b54e7bbd4d147746519cb86736aeea7a2c7ad2eaf8ce031eda2114732db504c4
MD5 24c9fb23080d739cdd316a366d8c7588
BLAKE2b-256 749bb1fc196f73faf408fd092c6e88bb74d57db3ea80103734b4439d162807c5

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 4fbb1a25db717931fbc015619ecbfda1c0121e8fca1bec1e1b66185110766319
MD5 50567d627f795b9732e1c63c6d5cad13
BLAKE2b-256 df3c85bb44ae51cd52318d0b2edf1780c16398830d1a9d4d590f236d68d2ce6b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 fbd7d9cff38f3bd1c4ece266d725dbc4d1948825dcd44850e672482c46920845
MD5 2013d538231e4fe293aacf04b4600422
BLAKE2b-256 11fc14ac74a86f74458558dd8f0316d85a475649f87fd1fa644c474cd5008d1f

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp34-none-win_amd64.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp34-none-win_amd64.whl
Algorithm Hash digest
SHA256 9fc13b6690356c66a92d71556b1416182ea756c5db89f7f3b27f5b5791083c4e
MD5 66683954479a25292cb87f684d6b0cbc
BLAKE2b-256 58f7cd55120e01ee6f90a4c312aa636ae88d7bcf585b6fcf951718108033ab0a

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp34-none-win32.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp34-none-win32.whl
Algorithm Hash digest
SHA256 c372e4433ff825c34e8b381b4b500bfc634c7b3f47028b0754db67e776434655
MD5 fd3404a327380cf61e32936536542f37
BLAKE2b-256 dd50b9348a906bc3fc317e08ff164835fbde142b110306cb0d1eab378cd5a085

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp34-cp34m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 a9771ca96513a210b2a55e47ae8bad80d50dc9dd39e48fb1f4bf61dd6343c507
MD5 155e46928f826fb3c75e3331175932bd
BLAKE2b-256 88c3e61d9fc180a66c5ed5d8cf43a60d857a3d5d80e67b87313913b4c60de870

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp34-cp34m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 1a40fc6ffa010a43623e9fe02612fbe1c21bfd4b340c94ed9b06f9f23e6efd48
MD5 9fe765e62eaa360b3ed68ce154d2bc1e
BLAKE2b-256 3c18d132cad8d6f85f8ef7aa96e0badc4131f75e1fe9e8a3285eb828038ea499

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp27-none-win_amd64.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp27-none-win_amd64.whl
Algorithm Hash digest
SHA256 b405dcd72999a5d68f4405dcb37c35cf85e07fa7ae7326755cfa4b3c445888b6
MD5 574f8b1176f624d4aba324a7a2242a16
BLAKE2b-256 bdd458448591064f46cf05df63fbb54129a1004439fea24c6fd0ebf40c5c2323

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp27-none-win32.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp27-none-win32.whl
Algorithm Hash digest
SHA256 9c8853ba4d5a27c8ab528fde007bd6fae78f4505f7188a05f1b05233a3a3efe7
MD5 f4a1ab1a1e911258ef1eac4afc1992c1
BLAKE2b-256 5bfb6386540277e09eee2f1822901dc9298e43ed7298fb6ab0a9b41e3bdb466b

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp27-cp27mu-manylinux1_x86_64.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp27-cp27mu-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 86caa58a74096ffa9cb766134c61e96ff6bc568ab298938a1b200110a7133cce
MD5 a71864b2deddbb9f636ad1972b19e446
BLAKE2b-256 62a92cc4fbdc2c57d484b9629d1e228db123cff98043a65e14464ddbc29bac3c

See more details on using hashes here.

File details

Details for the file exec_helpers-1.1.0-cp27-cp27mu-manylinux1_i686.whl.

File metadata

File hashes

Hashes for exec_helpers-1.1.0-cp27-cp27mu-manylinux1_i686.whl
Algorithm Hash digest
SHA256 6f6645f071a6752500a8995906481889be95bafa1e949a256fe8406893d63e5f
MD5 9ace6b4ec74c50db2e25216bd439720c
BLAKE2b-256 5be3cf585fe689faf583096a99c610b216fc2714e33663431ecb79f7667619aa

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