Execution helpers for simplified usage of subprocess and ssh.
Project description
exec-helpers
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:
STDOUT and STDERR polling during command execution - no deadlocks.
The same API for subprocess and ssh.
Connection memorize.
Free software: Apache license
Open Source: https://github.com/python-useful-helpers/exec-helpers
PyPI packaged: https://pypi-hypernode.com/pypi/exec-helpers
Self-documented code: docstrings with types in comments
Tested: see badges on top
Support multiple Python versions:
Python 3.6 Python 3.7
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).
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, 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
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.
result: ExecResult = helper.execute(
command, # type: str
verbose=False, # type: bool
timeout=1 * 60 * 60, # type: typing.Union[int, float, None]
# Keyword only:
log_mask_re=None, # type: typing.Optional[str]
stdin=None, # type: typing.Union[bytes, str, bytearray, None]
**kwargs
)
result: ExecResult = 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=(0,), # type: typing.Iterable[typing.Union[int, ExitCodes]]
raise_on_err=True, # type: bool
# Keyword only:
log_mask_re=None, # type: typing.Optional[str]
stdin=None, # type: typing.Union[bytes, str, bytearray, None]
exception_class=CalledProcessError, # typing.Type[CalledProcessError]
**kwargs
)
result: ExecResult = 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
# Keyword only:
expected=(0,), # typing.Iterable[typing.Union[int, ExitCodes]]
log_mask_re=None, # type: typing.Optional[str]
stdin=None, # type: typing.Union[bytes, str, bytearray, None]
exception_class=CalledProcessError, # typing.Type[CalledProcessError]
)
result: ExecResult = helper( # Lazy way: instances are callable and uses `execute`.
command, # type: str
verbose=False, # type: bool
timeout=1 * 60 * 60, # type: typing.Union[int, float, None]
# Keyword only:
log_mask_re=None, # type: typing.Optional[str]
stdin=None, # type: typing.Union[bytes, str, bytearray, None]
**kwargs
)
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*>’.
result: ExecResult = 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.
stdout_xml - STDOUT decoded as XML to ElementTree using defusedxml library.
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 keyword arguments, dimensions in pixels are always 0x0.
Possible to call commands in parallel on multiple hosts if it’s not produce huge output:
results: Dict[Tuple[str, int], ExecResult] = SSHClient.execute_together(
remotes, # type: typing.Iterable[SSHClient]
command, # type: str
timeout=1 * 60 * 60, # type: type: typing.Union[int, float, None]
expected=(0,), # type: typing.Iterable[typing.Union[int, ExitCodes]]
raise_on_err=True, # type: bool
# Keyword only:
stdin=None, # type: typing.Union[bytes, str, bytearray, None]
log_mask_re=None, # type: typing.Optional[str]
exception_class=ParallelCallProcessError # typing.Type[ParallelCallProcessError]
)
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: ExecResult = 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
# Keyword only:
stdin=None, # type: typing.Union[bytes, str, bytearray, None]
log_mask_re=None, # type: typing.Optional[str]
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: 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
Keyword arguments:
cwd - working directory.
env - environment variables dict.
async_api.Subprocess specific
All standard methods are coroutines. Async context manager also available.
Example:
async with helper:
result: ExecResult = await helper.execute(
command, # type: str
verbose=False, # type: bool
timeout=1 * 60 * 60, # type: typing.Union[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:
Travis CI: is used for checking: PEP8, pylint, bandit, installation possibility and unit tests. Also it’s publishes coverage on coveralls.
Azure Pipelines: is used for windows compatibility checking.
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
Built Distributions
File details
Details for the file exec-helpers-4.3.1.tar.gz
.
File metadata
- Download URL: exec-helpers-4.3.1.tar.gz
- Upload date:
- Size: 60.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | fbc307b2aaa525618d3c087d6959e03a1de5b6a27e99302e9902c4c0100c2515 |
|
MD5 | 9735e5b4049c83950931ac5f00f10c6e |
|
BLAKE2b-256 | 0401ff9dc73107ff0922ab5212cb9280414af8c1e63fc887e5b99ed9ba7104b5 |
File details
Details for the file exec_helpers-4.3.1-py3-none-any.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-py3-none-any.whl
- Upload date:
- Size: 53.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 11c6dac78b3f61d56fb7c521133fcbfeeb8838a82c2f7a90701ab46f6a4991e7 |
|
MD5 | 07612f2ec1c6b026aa1ff77deafba772 |
|
BLAKE2b-256 | 0c98be684d77c2da53312275ab90d4df6c7993321ee7ce9d50981d4254dd8a70 |
File details
Details for the file exec_helpers-4.3.1-cp37-cp37m-win_amd64.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp37-cp37m-win_amd64.whl
- Upload date:
- Size: 757.8 kB
- Tags: CPython 3.7m, Windows x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | e3d91f5cbcb620b7ccc8a619b1cd34284e791bea05e43dd15f123c36da45af43 |
|
MD5 | f274576bd62cff61671ee45fe9006a0f |
|
BLAKE2b-256 | 8129a5a9e1ffff41ad6d7cfc65310f8770dc32de60eb354c80ce9dd3e3c6a098 |
File details
Details for the file exec_helpers-4.3.1-cp37-cp37m-win32.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp37-cp37m-win32.whl
- Upload date:
- Size: 656.3 kB
- Tags: CPython 3.7m, Windows x86
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8da8e7173f378a2c71745f5659f6e4d83fe50d3d1e2222fa12bd0d7f1786cddd |
|
MD5 | 479252457136cf56c350340d8c10234b |
|
BLAKE2b-256 | 771235fa3fa6176d8d86235f99e074029639b78433c413c3b33f40f4e66f2127 |
File details
Details for the file exec_helpers-4.3.1-cp37-cp37m-manylinux1_x86_64.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp37-cp37m-manylinux1_x86_64.whl
- Upload date:
- Size: 3.2 MB
- Tags: CPython 3.7m
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 41622dc4a33d3b750bd9664d5177535d900b646e7405788744e84ff90a686151 |
|
MD5 | a936914d40fe7f4866c0afeed30187ba |
|
BLAKE2b-256 | e7d081aa3f32c98503eed86a42f722ac5e3d636b730e2bd05dffcb70ac6f704f |
File details
Details for the file exec_helpers-4.3.1-cp37-cp37m-manylinux1_i686.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp37-cp37m-manylinux1_i686.whl
- Upload date:
- Size: 2.9 MB
- Tags: CPython 3.7m
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 548adad3c0d47e4e41d5f7f85e089785f3d553f64c6edc3cf1550b8cbf353a6c |
|
MD5 | 5be498949f63a0be2382a286e8502d13 |
|
BLAKE2b-256 | 06f304608c88631afa3e03977911a37db4a2919e70196f8ab1c76bf3601999ca |
File details
Details for the file exec_helpers-4.3.1-cp36-cp36m-win_amd64.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp36-cp36m-win_amd64.whl
- Upload date:
- Size: 757.5 kB
- Tags: CPython 3.6m, Windows x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.6.8
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1d93eeed60a6920b02e448f72ebcabe3c15943bb2e9d42e9deed8fa2111e351c |
|
MD5 | 38432bda9bcefcbedb46187cfa6d7870 |
|
BLAKE2b-256 | 5dcf0795bf5c60cba90780d0674856df90f252ad7b28b8b0341ee3fc07745331 |
File details
Details for the file exec_helpers-4.3.1-cp36-cp36m-win32.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp36-cp36m-win32.whl
- Upload date:
- Size: 656.2 kB
- Tags: CPython 3.6m, Windows x86
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.6.8
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 33e2bcf2997b7fa8c27e1630e71f423ef7a1abf5a3ba7b7394eec1d0b8bec147 |
|
MD5 | 93e2bec9038d1d02652a52909b4a66ad |
|
BLAKE2b-256 | e931eca844212de74b59e532b7c058172bf43bc05a46daaa024bade72a7b77ca |
File details
Details for the file exec_helpers-4.3.1-cp36-cp36m-manylinux1_x86_64.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp36-cp36m-manylinux1_x86_64.whl
- Upload date:
- Size: 3.2 MB
- Tags: CPython 3.6m
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | efb99d060c083c041e05f6545d7bfdc64138b445000c0ff2d88abeb8a11b1046 |
|
MD5 | 915010c796eed4c02e4bd00bb637d9f9 |
|
BLAKE2b-256 | 4cf2596f6716efe17a1153b8d50f48754fcc0baf48e9b4f35e4b0d6419ef3ed9 |
File details
Details for the file exec_helpers-4.3.1-cp36-cp36m-manylinux1_i686.whl
.
File metadata
- Download URL: exec_helpers-4.3.1-cp36-cp36m-manylinux1_i686.whl
- Upload date:
- Size: 3.0 MB
- Tags: CPython 3.6m
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.0.1 requests-toolbelt/0.9.1 tqdm/4.32.1 CPython/3.7.1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b3d0b8d23f727627170b599cf3a589de5cc9ae2aa245ae2a7fab44b988410359 |
|
MD5 | 89c84e884a7cd2af5a9a9f0a56eaa73b |
|
BLAKE2b-256 | 6ba60fc86f8b4487dd184c6775421537899ccbed04e0752872f32b89847eab40 |