1
|
|
|
from subprocess import check_output, CalledProcessError, STDOUT |
2
|
|
|
from re import finditer |
3
|
|
|
|
4
|
|
|
from groundwork_validation.patterns import GwValidatorsPattern |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
class GwCmdValidatorsPattern(GwValidatorsPattern): |
8
|
|
|
|
9
|
|
|
def __init__(self, app, **kwargs): |
10
|
|
|
super(GwCmdValidatorsPattern, self).__init__(app, **kwargs) |
11
|
|
|
self.app = app |
12
|
|
|
self.validators.cmd = CmdValidatorsPlugin(self) |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
class CmdValidatorsPlugin: |
16
|
|
|
|
17
|
|
|
def __init__(self, plugin): |
18
|
|
|
self.plugin = plugin |
19
|
|
|
|
20
|
|
|
def validate(self, command, search=None, regex=None, timeout=2, allowed_return_codes=None): |
21
|
|
|
if search is None and regex is None: |
22
|
|
|
raise ValueError("Parameter search or regex must be set.") |
23
|
|
|
if search is not None and regex is not None: |
24
|
|
|
raise ValueError("Only search OR regex is allowed to be used. Not both!") |
25
|
|
|
|
26
|
|
|
if allowed_return_codes is None: |
27
|
|
|
allowed_return_codes = [] |
28
|
|
|
if isinstance(allowed_return_codes, int): |
29
|
|
|
allowed_return_codes = [allowed_return_codes] |
30
|
|
|
if not isinstance(allowed_return_codes, list): |
31
|
|
|
raise TypeError("allowed_return_code must be a list of integers") |
32
|
|
|
|
33
|
|
|
try: |
34
|
|
|
output = check_output(command, stderr=STDOUT, shell=True, timeout=timeout) |
35
|
|
|
return_code = 0 |
36
|
|
|
except CalledProcessError as e: |
37
|
|
|
output = e.output |
38
|
|
|
return_code = e.returncode |
39
|
|
|
|
40
|
|
|
if len(allowed_return_codes) > 0 and return_code not in allowed_return_codes: |
41
|
|
|
raise NotAllowedReturnCode("For command %s got return code '%s', which is not in %s" |
42
|
|
|
% (command, return_code, allowed_return_codes)) |
43
|
|
|
|
44
|
|
|
self.plugin.log.debug("Executed '%s' with return code: %s" % (command, return_code)) |
45
|
|
|
|
46
|
|
|
output = output.decode("utf-8") |
47
|
|
|
found = False |
48
|
|
|
if search is not None: |
49
|
|
|
if search in output: |
50
|
|
|
found = True |
51
|
|
|
elif regex is not None: |
52
|
|
|
for m in finditer(regex, output): |
53
|
|
|
self.plugin.log.debug("Found cmd validation '%s' at %02d-%02d" % (m.group(0), m.start(), m.end())) |
54
|
|
|
found = True |
55
|
|
|
return found |
56
|
|
|
|
57
|
|
|
|
58
|
|
|
class NotAllowedReturnCode(BaseException): |
59
|
|
|
pass |
60
|
|
|
|