| 1 |
#!/usr/bin/env python |
| 2 |
# |
| 3 |
# Executes the given command and returns the captured output. |
| 4 |
# |
| 5 |
# Author: Frank Steggink |
| 6 |
# |
| 7 |
import subprocess |
| 8 |
import os |
| 9 |
from stetl.component import Config |
| 10 |
from stetl.filter import Filter |
| 11 |
from stetl.util import Util |
| 12 |
from stetl.packet import FORMAT |
| 13 |
|
| 14 |
log = Util.get_log('execfilter') |
| 15 |
|
| 16 |
|
| 17 |
class ExecFilter(Filter): |
| 18 |
""" |
| 19 |
Executes any command (abstract base class). |
| 20 |
""" |
| 21 |
|
| 22 |
@Config(ptype=str, default='', required=False) |
| 23 |
def env_args(self): |
| 24 |
""" |
| 25 |
Provides of list of environment variables which will be used when executing the given command. |
| 26 |
|
| 27 |
Example: env_args = pgpassword=postgres othersetting=value~with~spaces |
| 28 |
""" |
| 29 |
pass |
| 30 |
|
| 31 |
@Config(ptype=str, default='=', required=False) |
| 32 |
def env_separator(self): |
| 33 |
""" |
| 34 |
Provides the separator to split the environment variable names from their values. |
| 35 |
""" |
| 36 |
pass |
| 37 |
|
| 38 |
def __init__(self, configdict, section, consumes, produces): |
| 39 |
Filter.__init__(self, configdict, section, consumes, produces) |
| 40 |
|
| 41 |
def invoke(self, packet): |
| 42 |
return packet |
| 43 |
|
| 44 |
def execute_cmd(self, cmd): |
| 45 |
env_vars = Util.string_to_dict(self.env_args, self.env_separator) |
| 46 |
old_environ = os.environ.copy() |
| 47 |
|
| 48 |
try: |
| 49 |
os.environ.update(env_vars) |
| 50 |
log.info("executing cmd=%s" % cmd) |
| 51 |
result = subprocess.check_output(cmd, shell=True) |
| 52 |
log.info("execute done") |
| 53 |
return result |
| 54 |
finally: |
| 55 |
os.environ = old_environ |
| 56 |
|
| 57 |
|
| 58 |
class CommandExecFilter(ExecFilter): |
| 59 |
""" |
| 60 |
Executes an arbitrary command and captures the output |
| 61 |
|
| 62 |
consumes=FORMAT.string, produces=FORMAT.string |
| 63 |
""" |
| 64 |
|
| 65 |
def __init__(self, configdict, section): |
| 66 |
ExecFilter.__init__(self, configdict, section, consumes=FORMAT.string, produces=FORMAT.string) |
| 67 |
|
| 68 |
def invoke(self, packet): |
| 69 |
if packet.data is not None: |
| 70 |
packet.data = self.execute_cmd(packet.data) |
| 71 |
|
| 72 |
return packet |