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

Uploaded Source

Built Distributions

exec_helpers-1.1.2-cp36-cp36m-manylinux1_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.6m

exec_helpers-1.1.2-cp36-cp36m-manylinux1_i686.whl (1.5 MB view details)

Uploaded CPython 3.6m

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

Uploaded CPython 3.5m

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

Uploaded CPython 3.5m

exec_helpers-1.1.2-cp34-cp34m-manylinux1_x86_64.whl (1.6 MB view details)

Uploaded CPython 3.4m

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

Uploaded CPython 3.4m

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

Uploaded CPython 2.7mu

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

Uploaded CPython 2.7mu

File details

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

File metadata

File hashes

Hashes for exec-helpers-1.1.2.tar.gz
Algorithm Hash digest
SHA256 13330887f2e6f1bfada5d265b2e1f8a69df9b48de36e9280cbc70a961a202e44
MD5 91abd7ee9d03b24ddfc19aba64a5b84f
BLAKE2b-256 51b5c274f239961078a781f577b63247ecff7064a8189d5a6443be083013355d

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 3f202f685d9d4bb9c41b5b2e5fbcb4658ca394900e6374387bff8c1fdbb46c7a
MD5 d9f81bcfd5ffdc782a75ef69b67ee979
BLAKE2b-256 26f55bd63e9c656f52d7d41e74588c3011e22f753d806ab1358992fc881569cd

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp36-cp36m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 eb3be1aded71cf01bfd463c3e524537a5f141b45b826f350af6880c082c63ec3
MD5 7ec557ed0a1004be3c0bfb268fc210e6
BLAKE2b-256 fd007a6e953ae4842a3d2aca09df8058263ff5b35e8ddb962810d9a447fed4a1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 7169ee4484bc3b5df2507cb751774e74fd846e457c989a628058fc636c0533e6
MD5 463c4723ec93db3f976c5b5a6e28978d
BLAKE2b-256 a5d1ef81ab3a1bbbcdbb24e9239b8b2cf870bacf931e8a444f4461b3e5940028

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp35-cp35m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 b340a8cccb45398d3b803dcfeccbbf50b2a5dd399bc56b742fb282727918f6d9
MD5 2bae19b986e8b1539b50f626c06b05d0
BLAKE2b-256 6ebebdfcf687e0a08017d342d6bdbebabfff72cc1f9af3d64c75565840f0a1e6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp34-cp34m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 92d8d98afb6d6f4b65e80288c75cbc554ab5f1c2602b0717174967cbedee4732
MD5 8baded43065dd15dbd929826cd7cf283
BLAKE2b-256 f7452d463dbbf00a4be5e5f046d821b112554d0f1cc4b4630cf36be8bb824fc3

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp34-cp34m-manylinux1_i686.whl
Algorithm Hash digest
SHA256 01a20e8d41e883706420f64dd4bd2d67d1f285c546ff2cea952158c693ee6ad2
MD5 8e68787436784c754df3fffd2a223250
BLAKE2b-256 351ce0bb1e2b3f8d6a75888373b1e0eef8df9c17ec77142c99404d5329bb64cb

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp27-cp27mu-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 fa6238c64035aaead2e47534cc56a08535b6bee34da7184b2e1205885afae65d
MD5 d56ac9951a6ab72e5533e4560185ecaf
BLAKE2b-256 240419b40fe7feaa02879b1dc6d69430a4d03c478ce9e5c6f5bbbbb2cb563d5b

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for exec_helpers-1.1.2-cp27-cp27mu-manylinux1_i686.whl
Algorithm Hash digest
SHA256 4daa9a5cc147acccf95a89b789053de5ccd9ef8097e8b0ed73a56b8781b3a2e8
MD5 79e1c2ba4cb6c6a2b20dabcd82611c41
BLAKE2b-256 6abf1bcfec7204547e2152062e460a47a5843bbb911367417302aca421f9bccc

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