From: Michael Tremer Date: Sat, 17 Apr 2010 16:09:12 +0000 (+0200) Subject: Add a event that is able to execute shell commands. X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=39fedabd85a5d9703e7b65204976ee872679ee27;p=oddments%2Fcappie.git Add a event that is able to execute shell commands. --- diff --git a/cappie.py b/cappie.py index 55f3059..5065a9d 100644 --- a/cappie.py +++ b/cappie.py @@ -2,8 +2,10 @@ import logging import logging.handlers +import os import pcapy import struct +import subprocess import sys import time @@ -209,7 +211,7 @@ class QueueFullError(Exception): class Queue(Thread): - heartbeat = 5.0 + heartbeat = 1.0 maxitems = 100 def __init__(self, log): @@ -258,10 +260,14 @@ class Queue(Thread): self.join() +class EventException(Exception): + pass + class Event(object): def __init__(self, interface): self.cappie = interface.cappie self.interface = interface + self.log = interface.log def __str__(self): return self.__class__.__name__ @@ -270,6 +276,49 @@ class Event(object): raise NotImplementedError +class EventTimeout(EventException): + pass + + +class EventShell(Event): + heartbeat = 0.1 + timeout = 10 + + def __init__(self, interface, script): + Event.__init__(self, interface) + + self.script = script + + def run(self): + args = " ".join([self.script, self.interface.dev]) + + start = time.time() + self.log.debug("Running: %s" % args) + + p = subprocess.Popen(args, + close_fds=True, + shell=True, + stdin=open("/dev/null", "r"), + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + + while p.poll() is None: + time.sleep(self.heartbeat) + if (time.time() - start) > self.timeout: + try: + os.killpg(p.pid, 9) + except OSError: + pass + raise EventTimeout, "Script took too long to return" + + for line in p.stdout.read().splitlines(): + if not line: continue + self.log.debug(" %s" % line) + + self.cappie.log.debug("Child process returned with exit code: %s" % p.returncode) + return p.returncode + + class Cappie(object): def __init__(self): self.__interfaces = []