/_unsorted/_core_new/localhost.py

https://bitbucket.org/ericsnowcurrently/commonlib
Python | 108 lines | 80 code | 23 blank | 5 comment | 19 complexity | 719042775b5a6fd8a31979fbc788800f MD5 | raw file
  1. """ssh_agent module
  2. """
  3. __all__ = (
  4. "run_command",
  5. "psutil_filtered",
  6. "USER",
  7. "CommandError", "CommandFailedError", "UnexpectedOutput",
  8. )
  9. import os
  10. import re
  11. from subprocess import Popen, PIPE
  12. from psutil import process_iter
  13. from core.error import Error
  14. USER = os.getlogin()
  15. RE_TYPE = type(re.compile(""))
  16. class CommandError(Error):
  17. MSG = "something wrong with a command"
  18. def __init__(self, command, msg=None, kws=None, **kwargs):
  19. if kws:
  20. kwargs.update(kws)
  21. super(type(self), self).__init__(msg, command=command, **kwargs)
  22. self.kws = kws
  23. def _lines(self):
  24. return [
  25. " (given: %s)" % self.kws,
  26. "command: %s" % self.command,
  27. ]
  28. class CommandFailedError(Error):
  29. MSG = "a subcommand failed"
  30. def __init__(self, command, error, retcode, **kwargs):
  31. super(type(self), self).__init__(command, error=error,
  32. retcode=retcode, kws=args)
  33. def _lines(self):
  34. return super(type(self), self)._lines() + [
  35. "retcode: %s" % self.retcode,
  36. "error:\n %s" % "\n ".join(self.error.splitlines()),
  37. ]
  38. class UnexpectedOutput(Error):
  39. MSG = "received unexpected output from command"
  40. def __init__(self, command, output, **kwargs):
  41. super(type(self), self).__init__(command, output=output, kws=args)
  42. def _lines(self):
  43. return super(type(self), self)._lines() + [
  44. "output: %s" % self.retcode,
  45. "output:\n %s" % "\n ".join(self.output.splitlines()),
  46. ]
  47. def psutil_filtered(user=None, command=None):
  48. for process in process_iter():
  49. if user and process.username != user:
  50. continue
  51. if command and process.name != command:
  52. continue
  53. yield process
  54. def run_command(command, expected=None, sudo=False, **kwargs):
  55. if sudo:
  56. command = "sudo sh -c '%s'" % command
  57. # run the command
  58. subproc = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)
  59. retcode = subproc.wait()
  60. if retcode:
  61. args = (command, subproc.stderr.read(), retcode)
  62. raise CommandFailedError(*args, **kwargs)
  63. output = subproc.stdout.read()
  64. # check the output, given various values of 'expected'
  65. if expected is None:
  66. return output.splitlines()
  67. if isinstance(expected, RE_TYPE):
  68. match = expected.match(output)
  69. if not match:
  70. raise UnexpectedOutput(command, output)
  71. return match
  72. lines = output.splitlines()
  73. if isinstance(expected, int) and len(lines) != expected:
  74. raise UnexpectedOutput(command, output)
  75. expected = tuple(expected)
  76. if len(expected) == 2:
  77. if (len(lines) < expected[0] or len(lines) > expected[1]):
  78. raise UnexpectedOutput(command, output)
  79. return lines
  80. if len(expected) == 3:
  81. if expected[0] < len(lines) < expected[2]:
  82. raise UnexpectedOutput(command, output)
  83. return lines
  84. raise TypeError("unexpected value for 'expected': %s" % expected)