/_unsorted/_core_new/localhost.py
Python | 108 lines | 80 code | 23 blank | 5 comment | 19 complexity | 719042775b5a6fd8a31979fbc788800f MD5 | raw file
- """ssh_agent module
- """
- __all__ = (
- "run_command",
- "psutil_filtered",
- "USER",
- "CommandError", "CommandFailedError", "UnexpectedOutput",
- )
- import os
- import re
- from subprocess import Popen, PIPE
- from psutil import process_iter
- from core.error import Error
- USER = os.getlogin()
- RE_TYPE = type(re.compile(""))
- class CommandError(Error):
- MSG = "something wrong with a command"
- def __init__(self, command, msg=None, kws=None, **kwargs):
- if kws:
- kwargs.update(kws)
- super(type(self), self).__init__(msg, command=command, **kwargs)
- self.kws = kws
- def _lines(self):
- return [
- " (given: %s)" % self.kws,
- "command: %s" % self.command,
- ]
- class CommandFailedError(Error):
- MSG = "a subcommand failed"
- def __init__(self, command, error, retcode, **kwargs):
- super(type(self), self).__init__(command, error=error,
- retcode=retcode, kws=args)
- def _lines(self):
- return super(type(self), self)._lines() + [
- "retcode: %s" % self.retcode,
- "error:\n %s" % "\n ".join(self.error.splitlines()),
- ]
- class UnexpectedOutput(Error):
- MSG = "received unexpected output from command"
- def __init__(self, command, output, **kwargs):
- super(type(self), self).__init__(command, output=output, kws=args)
- def _lines(self):
- return super(type(self), self)._lines() + [
- "output: %s" % self.retcode,
- "output:\n %s" % "\n ".join(self.output.splitlines()),
- ]
- def psutil_filtered(user=None, command=None):
- for process in process_iter():
- if user and process.username != user:
- continue
- if command and process.name != command:
- continue
- yield process
- def run_command(command, expected=None, sudo=False, **kwargs):
- if sudo:
- command = "sudo sh -c '%s'" % command
- # run the command
- subproc = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
- retcode = subproc.wait()
- if retcode:
- args = (command, subproc.stderr.read(), retcode)
- raise CommandFailedError(*args, **kwargs)
- output = subproc.stdout.read()
- # check the output, given various values of 'expected'
- if expected is None:
- return output.splitlines()
- if isinstance(expected, RE_TYPE):
- match = expected.match(output)
- if not match:
- raise UnexpectedOutput(command, output)
- return match
- lines = output.splitlines()
- if isinstance(expected, int) and len(lines) != expected:
- raise UnexpectedOutput(command, output)
- expected = tuple(expected)
- if len(expected) == 2:
- if (len(lines) < expected[0] or len(lines) > expected[1]):
- raise UnexpectedOutput(command, output)
- return lines
- if len(expected) == 3:
- if expected[0] < len(lines) < expected[2]:
- raise UnexpectedOutput(command, output)
- return lines
- raise TypeError("unexpected value for 'expected': %s" % expected)