exec-helpers


Nameexec-helpers JSON
Version 8.0.1 PyPI version JSON
download
home_pagehttps://github.com/python-useful-helpers/exec-helpers
SummaryExecution helpers for simplified usage of subprocess and ssh.
upload_time2023-11-17 09:46:49
maintainer
docs_urlNone
author
requires_python>=3.8.0
licenseApache-2.0
keywords subprocess ssh
VCS
bugtrack_url
requirements paramiko tenacity psutil
Travis-CI No Travis.
coveralls test coverage No coveralls.
            exec-helpers
============

.. image:: https://github.com/python-useful-helpers/exec-helpers/workflows/Python%20package/badge.svg
    :target: https://github.com/python-useful-helpers/exec-helpers/actions
.. image:: https://readthedocs.org/projects/exec-helpers/badge/?version=latest
    :target: https://exec-helpers.readthedocs.io/
    :alt: Documentation Status
.. image:: https://img.shields.io/pypi/v/exec-helpers.svg
    :target: https://pypi.python.org/pypi/exec-helpers
.. image:: https://img.shields.io/pypi/pyversions/exec-helpers.svg
    :target: https://pypi.python.org/pypi/exec-helpers
.. image:: https://img.shields.io/pypi/status/exec-helpers.svg
    :target: https://pypi.python.org/pypi/exec-helpers
.. image:: https://img.shields.io/github/license/python-useful-helpers/exec-helpers.svg
    :target: https://raw.githubusercontent.com/python-useful-helpers/exec-helpers/master/LICENSE
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
    :target: https://github.com/ambv/black

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 deadlock free polling and friendly result objects
(with inline decoding of XML Element tree, 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:

* STDOUT and STDERR polling during command execution - no deadlocks.
* The same API for subprocess and ssh.
* Free software: Apache license
* Open Source: https://github.com/python-useful-helpers/exec-helpers
* PyPI packaged: https://pypi.python.org/pypi/exec-helpers
* Self-documented code: docstrings with types in comments
* Tested: see badges on top
* Support multiple Python versions:

::

    Python 3.8
    Python 3.9
    Python 3.10
    Python 3.11
    Python 3.12

This package includes:

* `SSHClient` - historically the first one helper, which used for SSH connections.
  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, XML (and LXML) element tree, string, bytearray
  and brief strings (up to 7 lines).

* `ExitCodes` - enumerator for standard Linux exit codes. BASH return codes (produced from signal codes) also available.

Installation
============

Standard: `pip install exec-helpers`
Extras:

* ``yaml`` - install `PyYaml` for yaml decoding (`PyYAML` is main decoder, `ruamel.YAML` also supported as fallback.)

* ``xml`` - install `defusedxml` for safe XML parsing to `xml.etree.ElementTree.Element`.

* ``lxml`` - install `lxml` for advanced XML parsing. Can be unsafe.

* ``ALL_FORMATS`` (``all-formats``) - install all parsers. When new parsers will be added, it will ne also supported.

Usage
=====

SSHClient
---------

Basic initialization of `SSHClient` can be done without construction of specific objects:

.. code-block:: python

    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.PKey`.

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:

.. code-block:: python

    auth = exec_helpers.SSHAuth(
        username='username',  # str | None
        password='password',  # str | None
        key=None,  # type: paramiko.PKey | None
        keys=None,  # type: Iterable[paramiko.PKey] | None
        key_filename=None,  # type: list[str] | None
        passphrase=None,  # str | None
    )

Key is a main connection key (always tried first) and keys are alternate keys.
Key filename is a filename 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.

.. note:: context manager is strictly not recommended in scenarios with fast reconnect to the same host with te same credentials.

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.

.. note:: By default ALL methods have timeout 1 hour, infinite waiting can be enabled, but it's special case.

.. code-block:: python

    result: ExecResult = helper.execute(
        command,  # type: str | Iterable[str]
        verbose=False,  # type: bool
        timeout=1 * 60 * 60,  # type: int | float | None
        # Keyword only:
        log_mask_re=None,  # str | None
        stdin=None,  # type: bytes | str | bytearray | None
        open_stdout=True,  # type: bool
        log_stdout=True,  # type: bool
        open_stderr=True,  # type: bool
        log_stderr=True,  # type: bool
        **kwargs
    )


.. code-block:: python

    result: ExecResult = helper.check_call(
        command,  # type: str | Iterable[str]
        verbose=False,  # type: bool
        timeout=1 * 60 * 60,  # type: type: int | float | None
        error_info=None,  # str | None
        expected=(0,),  # type: Iterable[int | ExitCodes]
        raise_on_err=True,  # type: bool
        # Keyword only:
        log_mask_re=None,  # str | None
        stdin=None,  # type: bytes | str | bytearray | None
        open_stdout=True,  # type: bool
        log_stdout=True,  # type: bool
        open_stderr=True,  # type: bool
        log_stderr=True,  # type: bool
        exception_class=CalledProcessError,  # type[CalledProcessError]
        **kwargs
    )

.. code-block:: python

    result: ExecResult = helper.check_stderr(
        command,  # type: str | Iterable[str]
        verbose=False,  # type: bool
        timeout=1 * 60 * 60,  # type: type: int | float | None
        error_info=None,  # str | None
        raise_on_err=True,  # type: bool
        # Keyword only:
        expected=(0,),  # Iterable[int | ExitCodes]
        log_mask_re=None,  # str | None
        stdin=None,  # type: bytes | str | bytearray | None
        open_stdout=True,  # type: bool
        log_stdout=True,  # type: bool
        open_stderr=True,  # type: bool
        log_stderr=True,  # type: bool
        exception_class=CalledProcessError,  # type[CalledProcessError]
    )

.. code-block:: python

    result: ExecResult = helper(  # Lazy way: instances are callable and uses `execute`.
        command,  # type: str | Iterable[str]
        verbose=False,  # type: bool
        timeout=1 * 60 * 60,  # type: int | float | None
        # Keyword only:
        log_mask_re=None,  # str | None
        stdin=None,  # type: bytes | str | bytearray | None
        open_stdout=True,  # type: bool
        log_stdout=True,  # type: bool
        open_stderr=True,  # type: bool
        log_stderr=True,  # type: bool
        **kwargs
    )

.. note::

  If command is provided as `Iterable[str]`, `shell=True` will be still used,
  but all command components will be joined with escaping to protect from shell processing.

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*>'`.

.. code-block:: python

    result: ExecResult = helper.execute(
        command="AUTH='top_secret_key'; run command",  # type: str | Iterable[str]
        verbose=False,  # type: bool
        timeout=1 * 60 * 60,  # type: Optional[int]
        log_mask_re=r"AUTH\s*=\s*'(\w+)'"  # str | None
    )

`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.
* `ok` -> `bool`. Command return code is 0 (EX_OK).
* `stdin` -> `str`. Text representation of stdin.
* `stdout` -> `tuple[bytes]`. Raw stdout output.
* `stderr` -> `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. Accessible only if `PyYAML` or `ruamel.YAML` library installed.
  (Extras: ``yaml``)

* `stdout_xml` - STDOUT decoded as XML to `ElementTree` using `defusedxml` library. Accessible only if `defusedxml` library installed.
  (Extras: ``xml``)

* `stdout_lxml` - STDOUT decoded as XML to `ElementTree` using `lxml` library. Accessible only if `lxml` library installed.
  (Extras: ``lxml``) Can be insecure.

* `timestamp` -> `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:

.. code-block:: python

    results: dict[tuple[str, int], ExecResult] = SSHClient.execute_together(
        remotes,  # type: Iterable[SSHClient]
        command,  # type: str | Iterable[str]
        timeout=1 * 60 * 60,  # type: type: int | float | None
        expected=(0,),  # type: Iterable[int | ExitCodes]
        raise_on_err=True,  # type: bool
        # Keyword only:
        stdin=None,  # type: bytes | str | bytearray | None
        open_stdout=True,  # type: bool
        open_stderr=True,  # type: bool
        log_mask_re=None,  # str | None
        exception_class=ParallelCallProcessError  # type[ParallelCallProcessError]
    )
    results  # type: dict[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.

To open new connection using current as proxy is accessible method `proxy_to`. Basic usage example:

.. code-block:: python

    conn: SSHClient = client.proxy_to(host, username="username", password="password")

.. note:: for full command API please rely API documentation.

For execute through SSH host can be used `execute_through_host` method:

.. code-block:: python

    result: ExecResult = client.execute_through_host(
        hostname,  # type: str
        command,  # type: str | Iterable[str]
        # Keyword only:
        auth=None,  # type: SSHAuth | None
        port=22,  # type: int
        timeout=1 * 60 * 60,  # type: type: int | float | None
        verbose=False,  # type: bool
        stdin=None,  # type: bytes | str | bytearray | None
        open_stdout=True,  # type: bool
        log_stdout=True,  # type: bool
        open_stderr=True,  # type: bool
        log_stderr=True,  # type: bool
        log_mask_re=None,  # str | None
        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:

.. note:: In case of combination sudo + chroot, chroot will be applied first. For alternative order write command with chroot manually.

Commands will be run with sudo enforced independently from client settings for normal usage:

.. code-block:: python

    with client.sudo(enforce=True):
        ...


Commands will be run *without sudo* independently from client settings for normal usage:

.. code-block:: python

    with client.sudo(enforce=False):
        ...

"Permanent client setting":

.. code-block:: python

    client.sudo_mode = mode  # where mode is True or False

SSH Client supports sFTP for working with remote files:

.. code-block:: python

    with client.open(path, mode='r') as f:
        ...

For fast remote paths checks available methods:

- `exists(path)` -> `bool`

.. code-block:: python

    >>> conn.exists('/etc/passwd')
    True

- `stat(path)` -> `paramiko.sftp_attr.SFTPAttributes`

.. code-block:: python

    >>> 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`

.. code-block:: python

    >>> conn.isfile('/etc/passwd')
    True

- `isdir(path)` -> `bool`

.. code-block:: python

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

.. note:: `shell=true` is always set.

async_api.Subprocess specific
-----------------------------

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

Example:

.. code-block:: python

    async with helper:
      result: ExecResult = await helper.execute(
          command,  # type: str | Iterable[str]
          verbose=False,  # type: bool
          timeout=1 * 60 * 60,  # type: 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. `GitHub actions: <https://github.com/python-useful-helpers/exec-helpers/actions>`_ is used for checking: PEP8, pylint, bandit, installation possibility and unit tests.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/python-useful-helpers/exec-helpers",
    "name": "exec-helpers",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8.0",
    "maintainer_email": "Aleksei Stepanov <penguinolog@gmail.com>, Antonio Esposito <esposito.cloud@gmail.com>, Dennis Dmitriev <dis-xcom@gmail.com>",
    "keywords": "subprocess,ssh",
    "author": "",
    "author_email": "Alexey Stepanov <penguinolog@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/6f/1f/976e5624a3ef2a8640520402f0cdc349f71b668c15f6e9734e42114d4744/exec-helpers-8.0.1.tar.gz",
    "platform": null,
    "description": "exec-helpers\n============\n\n.. image:: https://github.com/python-useful-helpers/exec-helpers/workflows/Python%20package/badge.svg\n    :target: https://github.com/python-useful-helpers/exec-helpers/actions\n.. image:: https://readthedocs.org/projects/exec-helpers/badge/?version=latest\n    :target: https://exec-helpers.readthedocs.io/\n    :alt: Documentation Status\n.. image:: https://img.shields.io/pypi/v/exec-helpers.svg\n    :target: https://pypi.python.org/pypi/exec-helpers\n.. image:: https://img.shields.io/pypi/pyversions/exec-helpers.svg\n    :target: https://pypi.python.org/pypi/exec-helpers\n.. image:: https://img.shields.io/pypi/status/exec-helpers.svg\n    :target: https://pypi.python.org/pypi/exec-helpers\n.. image:: https://img.shields.io/github/license/python-useful-helpers/exec-helpers.svg\n    :target: https://raw.githubusercontent.com/python-useful-helpers/exec-helpers/master/LICENSE\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n    :target: https://github.com/ambv/black\n\nExecution helpers for simplified usage of subprocess and ssh.\nWhy another subprocess wrapper and why no clear `paramiko`?\n\nHistorically `paramiko` offers good ssh client, but with specific limitations:\nyou can call command with timeout, but without receiving return code,\nor call command and wait for return code, but without timeout processing.\n\nIn the most cases, we are need just simple SSH client with comfortable API for calls, calls via SSH proxy and checking return code/stderr.\nThis library offers this functionality with deadlock free polling and friendly result objects\n(with inline decoding of XML Element tree, YAML, JSON, binary or just strings).\nIn addition this library offers the same API for subprocess calls, but with specific limitation: no parallel calls\n(for protection from race conditions).\n\nPros:\n\n* STDOUT and STDERR polling during command execution - no deadlocks.\n* The same API for subprocess and ssh.\n* Free software: Apache license\n* Open Source: https://github.com/python-useful-helpers/exec-helpers\n* PyPI packaged: https://pypi.python.org/pypi/exec-helpers\n* Self-documented code: docstrings with types in comments\n* Tested: see badges on top\n* Support multiple Python versions:\n\n::\n\n    Python 3.8\n    Python 3.9\n    Python 3.10\n    Python 3.11\n    Python 3.12\n\nThis package includes:\n\n* `SSHClient` - historically the first one helper, which used for SSH connections.\n  Several API calls for sFTP also presents.\n\n* `SSHAuth` - class for credentials storage. `SSHClient` does not store credentials as-is, but uses `SSHAuth` for it.\n  Objects of this class can be copied between ssh connection objects, also it used for `execute_through_host`.\n\n* `Subprocess` - `subprocess.Popen` wrapper with timeouts, polling and almost the same API, as `SSHClient`\n  (except specific flags, like `cwd` for subprocess and `get_tty` for ssh).\n\n* `async_api.Subprocess` - the same, as `Subprocess` helper, but works with asyncio.\n  .. note:: for Windows `ProactorEventLoop` or another non-standard event loop should be used!\n\n* `ExecResult` - class for execution results storage.\n  Contains exit code, stdout, stderr and getters for decoding as JSON, YAML, XML (and LXML) element tree, string, bytearray\n  and brief strings (up to 7 lines).\n\n* `ExitCodes` - enumerator for standard Linux exit codes. BASH return codes (produced from signal codes) also available.\n\nInstallation\n============\n\nStandard: `pip install exec-helpers`\nExtras:\n\n* ``yaml`` - install `PyYaml` for yaml decoding (`PyYAML` is main decoder, `ruamel.YAML` also supported as fallback.)\n\n* ``xml`` - install `defusedxml` for safe XML parsing to `xml.etree.ElementTree.Element`.\n\n* ``lxml`` - install `lxml` for advanced XML parsing. Can be unsafe.\n\n* ``ALL_FORMATS`` (``all-formats``) - install all parsers. When new parsers will be added, it will ne also supported.\n\nUsage\n=====\n\nSSHClient\n---------\n\nBasic initialization of `SSHClient` can be done without construction of specific objects:\n\n.. code-block:: python\n\n    client = exec_helpers.SSHClient(host, username=\"username\", password=\"password\")\n\nIf ssh agent is running - keys will be collected by paramiko automatically,\nbut if keys are in specific location  - it should be loaded manually and provided as iterable object of `paramiko.PKey`.\n\nFor advanced cases or re-use of credentials, `SSHAuth` object should be used.\nIt can be collected from connection object via property `auth`.\n\nCreation from scratch:\n\n.. code-block:: python\n\n    auth = exec_helpers.SSHAuth(\n        username='username',  # str | None\n        password='password',  # str | None\n        key=None,  # type: paramiko.PKey | None\n        keys=None,  # type: Iterable[paramiko.PKey] | None\n        key_filename=None,  # type: list[str] | None\n        passphrase=None,  # str | None\n    )\n\nKey is a main connection key (always tried first) and keys are alternate keys.\nKey filename is a filename or list of filenames with keys, which should be loaded.\nPassphrase is an alternate password for keys, if it differs from main password.\nIf main key now correct for username - alternate keys tried, if correct key found - it became main.\nIf no working key - password is used and None is set as main key.\n\nContext manager is available, connection is closed and lock is released on exit from context.\n\n.. note:: context manager is strictly not recommended in scenarios with fast reconnect to the same host with te same credentials.\n\nSubprocess\n----------\n\nContext manager is available, subprocess is killed and lock is released on exit from context.\n\nBase methods\n------------\nMain methods are `execute`, `check_call` and `check_stderr` for simple executing, executing and checking return code\nand executing, checking return code and checking for empty stderr output.\nThis methods are almost the same for `SSHClient` and `Subprocess`, except specific flags.\n\n.. note:: By default ALL methods have timeout 1 hour, infinite waiting can be enabled, but it's special case.\n\n.. code-block:: python\n\n    result: ExecResult = helper.execute(\n        command,  # type: str | Iterable[str]\n        verbose=False,  # type: bool\n        timeout=1 * 60 * 60,  # type: int | float | None\n        # Keyword only:\n        log_mask_re=None,  # str | None\n        stdin=None,  # type: bytes | str | bytearray | None\n        open_stdout=True,  # type: bool\n        log_stdout=True,  # type: bool\n        open_stderr=True,  # type: bool\n        log_stderr=True,  # type: bool\n        **kwargs\n    )\n\n\n.. code-block:: python\n\n    result: ExecResult = helper.check_call(\n        command,  # type: str | Iterable[str]\n        verbose=False,  # type: bool\n        timeout=1 * 60 * 60,  # type: type: int | float | None\n        error_info=None,  # str | None\n        expected=(0,),  # type: Iterable[int | ExitCodes]\n        raise_on_err=True,  # type: bool\n        # Keyword only:\n        log_mask_re=None,  # str | None\n        stdin=None,  # type: bytes | str | bytearray | None\n        open_stdout=True,  # type: bool\n        log_stdout=True,  # type: bool\n        open_stderr=True,  # type: bool\n        log_stderr=True,  # type: bool\n        exception_class=CalledProcessError,  # type[CalledProcessError]\n        **kwargs\n    )\n\n.. code-block:: python\n\n    result: ExecResult = helper.check_stderr(\n        command,  # type: str | Iterable[str]\n        verbose=False,  # type: bool\n        timeout=1 * 60 * 60,  # type: type: int | float | None\n        error_info=None,  # str | None\n        raise_on_err=True,  # type: bool\n        # Keyword only:\n        expected=(0,),  # Iterable[int | ExitCodes]\n        log_mask_re=None,  # str | None\n        stdin=None,  # type: bytes | str | bytearray | None\n        open_stdout=True,  # type: bool\n        log_stdout=True,  # type: bool\n        open_stderr=True,  # type: bool\n        log_stderr=True,  # type: bool\n        exception_class=CalledProcessError,  # type[CalledProcessError]\n    )\n\n.. code-block:: python\n\n    result: ExecResult = helper(  # Lazy way: instances are callable and uses `execute`.\n        command,  # type: str | Iterable[str]\n        verbose=False,  # type: bool\n        timeout=1 * 60 * 60,  # type: int | float | None\n        # Keyword only:\n        log_mask_re=None,  # str | None\n        stdin=None,  # type: bytes | str | bytearray | None\n        open_stdout=True,  # type: bool\n        log_stdout=True,  # type: bool\n        open_stderr=True,  # type: bool\n        log_stderr=True,  # type: bool\n        **kwargs\n    )\n\n.. note::\n\n  If command is provided as `Iterable[str]`, `shell=True` will be still used,\n  but all command components will be joined with escaping to protect from shell processing.\n\nIf no STDOUT or STDERR required, it is possible to disable this FIFO pipes via `**kwargs` with flags `open_stdout=False` and `open_stderr=False`.\n\nThe next command level uses lower level and kwargs are forwarded, so expected exit codes are forwarded from `check_stderr`.\nImplementation specific flags are always set via kwargs.\n\nIf required to mask part of command from logging, `log_mask_re` attribute can be set global over instance or provided with command.\nAll regex matched groups will be replaced by `'<*masked*>'`.\n\n.. code-block:: python\n\n    result: ExecResult = helper.execute(\n        command=\"AUTH='top_secret_key'; run command\",  # type: str | Iterable[str]\n        verbose=False,  # type: bool\n        timeout=1 * 60 * 60,  # type: Optional[int]\n        log_mask_re=r\"AUTH\\s*=\\s*'(\\w+)'\"  # str | None\n    )\n\n`result.cmd` will be equal to `AUTH='<*masked*>'; run command`\n\nExecResult\n----------\n\nExecution result object has a set of useful properties:\n\n* `cmd` - Command\n* `exit_code` - Command return code. If possible to decode using enumerators for Linux -> it used.\n* `ok` -> `bool`. Command return code is 0 (EX_OK).\n* `stdin` -> `str`. Text representation of stdin.\n* `stdout` -> `tuple[bytes]`. Raw stdout output.\n* `stderr` -> `tuple[bytes]`. Raw stderr output.\n* `stdout_bin` -> `bytearray`. Binary stdout output.\n* `stderr_bin` -> `bytearray`. Binary stderr output.\n* `stdout_str` -> `str`. Text representation of output.\n* `stderr_str` -> `str`. Text representation of output.\n* `stdout_brief` -> `str`. Up to 7 lines from stdout (3 first and 3 last if >7 lines).\n* `stderr_brief` -> `str`. Up to 7 lines from stderr (3 first and 3 last if >7 lines).\n\n* `stdout_json` - STDOUT decoded as JSON.\n\n* `stdout_yaml` - STDOUT decoded as YAML. Accessible only if `PyYAML` or `ruamel.YAML` library installed.\n  (Extras: ``yaml``)\n\n* `stdout_xml` - STDOUT decoded as XML to `ElementTree` using `defusedxml` library. Accessible only if `defusedxml` library installed.\n  (Extras: ``xml``)\n\n* `stdout_lxml` - STDOUT decoded as XML to `ElementTree` using `lxml` library. Accessible only if `lxml` library installed.\n  (Extras: ``lxml``) Can be insecure.\n\n* `timestamp` -> `Optional(datetime.datetime)`. Timestamp for received exit code.\n\nSSHClient specific\n------------------\n\nSSHClient commands support get_pty flag, which enables PTY open on remote side.\nPTY width and height can be set via keyword arguments, dimensions in pixels are always 0x0.\n\nPossible to call commands in parallel on multiple hosts if it's not produce huge output:\n\n.. code-block:: python\n\n    results: dict[tuple[str, int], ExecResult] = SSHClient.execute_together(\n        remotes,  # type: Iterable[SSHClient]\n        command,  # type: str | Iterable[str]\n        timeout=1 * 60 * 60,  # type: type: int | float | None\n        expected=(0,),  # type: Iterable[int | ExitCodes]\n        raise_on_err=True,  # type: bool\n        # Keyword only:\n        stdin=None,  # type: bytes | str | bytearray | None\n        open_stdout=True,  # type: bool\n        open_stderr=True,  # type: bool\n        log_mask_re=None,  # str | None\n        exception_class=ParallelCallProcessError  # type[ParallelCallProcessError]\n    )\n    results  # type: dict[tuple[str, int], exec_result.ExecResult]\n\nResults is a dict with keys = (hostname, port) and and results in values.\nBy default execute_together raises exception if unexpected return code on any remote.\n\nTo open new connection using current as proxy is accessible method `proxy_to`. Basic usage example:\n\n.. code-block:: python\n\n    conn: SSHClient = client.proxy_to(host, username=\"username\", password=\"password\")\n\n.. note:: for full command API please rely API documentation.\n\nFor execute through SSH host can be used `execute_through_host` method:\n\n.. code-block:: python\n\n    result: ExecResult = client.execute_through_host(\n        hostname,  # type: str\n        command,  # type: str | Iterable[str]\n        # Keyword only:\n        auth=None,  # type: SSHAuth | None\n        port=22,  # type: int\n        timeout=1 * 60 * 60,  # type: type: int | float | None\n        verbose=False,  # type: bool\n        stdin=None,  # type: bytes | str | bytearray | None\n        open_stdout=True,  # type: bool\n        log_stdout=True,  # type: bool\n        open_stderr=True,  # type: bool\n        log_stderr=True,  # type: bool\n        log_mask_re=None,  # str | None\n        get_pty=False,  # type: bool\n        width=80,  # type: int\n        height=24  # type: int\n    )\n\nWhere hostname is a target hostname, auth is an alternate credentials for target host.\n\nSSH client implements fast sudo support via context manager:\n\n.. note:: In case of combination sudo + chroot, chroot will be applied first. For alternative order write command with chroot manually.\n\nCommands will be run with sudo enforced independently from client settings for normal usage:\n\n.. code-block:: python\n\n    with client.sudo(enforce=True):\n        ...\n\n\nCommands will be run *without sudo* independently from client settings for normal usage:\n\n.. code-block:: python\n\n    with client.sudo(enforce=False):\n        ...\n\n\"Permanent client setting\":\n\n.. code-block:: python\n\n    client.sudo_mode = mode  # where mode is True or False\n\nSSH Client supports sFTP for working with remote files:\n\n.. code-block:: python\n\n    with client.open(path, mode='r') as f:\n        ...\n\nFor fast remote paths checks available methods:\n\n- `exists(path)` -> `bool`\n\n.. code-block:: python\n\n    >>> conn.exists('/etc/passwd')\n    True\n\n- `stat(path)` -> `paramiko.sftp_attr.SFTPAttributes`\n\n.. code-block:: python\n\n    >>> conn.stat('/etc/passwd')\n    <SFTPAttributes: [ size=1882 uid=0 gid=0 mode=0o100644 atime=1521618061 mtime=1449733241 ]>\n    >>> str(conn.stat('/etc/passwd'))\n    '-rw-r--r--   1 0        0            1882 10 Dec 2015  ?'\n\n- `isfile(path)` -> `bool`\n\n.. code-block:: python\n\n    >>> conn.isfile('/etc/passwd')\n    True\n\n- `isdir(path)` -> `bool`\n\n.. code-block:: python\n\n    >>> conn.isdir('/etc/passwd')\n    False\n\nAdditional (non-standard) helpers:\n\n- `mkdir(path: str)` - execute mkdir -p path\n- `rm_rf(path: str)` - execute rm -rf path\n- `upload(source: str, target: str)` - upload file or from source to target using sFTP.\n- `download(destination: str, target: str)` - download file from target to destination using sFTP.\n\nSubprocess specific\n-------------------\nKeyword arguments:\n\n- cwd - working directory.\n- env - environment variables dict.\n\n.. note:: `shell=true` is always set.\n\nasync_api.Subprocess specific\n-----------------------------\n\nAll standard methods are coroutines. Async context manager also available.\n\nExample:\n\n.. code-block:: python\n\n    async with helper:\n      result: ExecResult = await helper.execute(\n          command,  # type: str | Iterable[str]\n          verbose=False,  # type: bool\n          timeout=1 * 60 * 60,  # type: int | float | None\n          **kwargs\n      )\n\nTesting\n=======\nThe main test mechanism for the package `exec-helpers` is using `tox`.\nAvailable environments can be collected via `tox -l`\n\nCI systems\n==========\nFor code checking several CI systems is used in parallel:\n\n1. `GitHub actions: <https://github.com/python-useful-helpers/exec-helpers/actions>`_ is used for checking: PEP8, pylint, bandit, installation possibility and unit tests.\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Execution helpers for simplified usage of subprocess and ssh.",
    "version": "8.0.1",
    "project_urls": {
        "Bug Tracker": "https://github.com/python-useful-helpers/exec-helpers/issues",
        "Documentation": "https://exec-helpers.readthedocs.io/",
        "Homepage": "https://github.com/python-useful-helpers/exec-helpers",
        "Repository": "https://github.com/python-useful-helpers/exec-helpers"
    },
    "split_keywords": [
        "subprocess",
        "ssh"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "126da73445282def4cf996b04fc75c249d7c0f71be12423e8f548a9e2cba82cf",
                "md5": "165dd3cdc4520be1b43221c8936b0ed7",
                "sha256": "3412581834371892c4d16a05d4457687b365b38f321129422ca5090ae89faa2d"
            },
            "downloads": -1,
            "filename": "exec_helpers-8.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "165dd3cdc4520be1b43221c8936b0ed7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8.0",
            "size": 75438,
            "upload_time": "2023-11-17T09:46:46",
            "upload_time_iso_8601": "2023-11-17T09:46:46.801000Z",
            "url": "https://files.pythonhosted.org/packages/12/6d/a73445282def4cf996b04fc75c249d7c0f71be12423e8f548a9e2cba82cf/exec_helpers-8.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6f1f976e5624a3ef2a8640520402f0cdc349f71b668c15f6e9734e42114d4744",
                "md5": "c270c6780ebc8f75c087cbee9a80e7dc",
                "sha256": "2a46de20e9a568d62aa9cac1cf4fb894a145bda08e3ff294890743e7b4bbfcee"
            },
            "downloads": -1,
            "filename": "exec-helpers-8.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "c270c6780ebc8f75c087cbee9a80e7dc",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8.0",
            "size": 69372,
            "upload_time": "2023-11-17T09:46:49",
            "upload_time_iso_8601": "2023-11-17T09:46:49.553347Z",
            "url": "https://files.pythonhosted.org/packages/6f/1f/976e5624a3ef2a8640520402f0cdc349f71b668c15f6e9734e42114d4744/exec-helpers-8.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-17 09:46:49",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "python-useful-helpers",
    "github_project": "exec-helpers",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "paramiko",
            "specs": [
                [
                    ">=",
                    "2.4"
                ]
            ]
        },
        {
            "name": "tenacity",
            "specs": [
                [
                    ">=",
                    "4.4.0"
                ]
            ]
        },
        {
            "name": "psutil",
            "specs": [
                [
                    ">=",
                    "5.0"
                ]
            ]
        }
    ],
    "tox": true,
    "lcname": "exec-helpers"
}
        
Elapsed time: 0.20322s