Mercurial > hg > KCl
view kcl/run_cmd.py @ 0:0f44ee073173 default tip
fake salt, initial commit
author | Jeff Hammel <k0scist@gmail.com> |
---|---|
date | Mon, 06 Feb 2017 01:10:22 +0000 |
parents | |
children |
line wrap: on
line source
#!/usr/bin/env python # -*- coding: utf-8 -*- """ run a command on some things """ # imports import argparse import os import subprocess import sys import time # module globals __all__ = ['print_command', 'call', 'RunCmdParser'] string = (str, unicode) def print_command(command, **kwargs): if not isinstance(command, string): command = subprocess.list2cmdline(command) print (command) def call(command, **kwargs): process = subprocess.Popen(command, **kwargs) stdout, stderr = process.communicate() if process.returncode: cmdline = subprocess.list2cmdline(command) print cmdline raise subprocess.CalledProcessError(process.returncode, cmdline) def ssh_call(host, command, ssh='ssh'): call([ssh, host, command], stderr=subprocess.PIPE) class RunCmdParser(argparse.ArgumentParser): """CLI option parser""" def __init__(self, **kwargs): kwargs.setdefault('formatter_class', argparse.RawTextHelpFormatter) kwargs.setdefault('description', __doc__) argparse.ArgumentParser.__init__(self, **kwargs) self.add_argument('-H', '--host', dest='hosts', nargs='+', help="hosts to run on; or read from stdin if omitted") self.add_argument("command", help="command to run") self.options = None self._hosts = None def parse_args(self, *args, **kw): options = argparse.ArgumentParser.parse_args(self, *args, **kw) self.validate(options) self.options = options return options def validate(self, options): """validate options""" def hosts(self): if self._hosts is None: assert self.options is not None self._hosts = self.options.hosts or sys.stdin.read().strip().split() return self._hosts def command(self): return self.options.command def main(args=sys.argv[1:]): """CLI""" # parse command line options parser = RunCmdParser() options = parser.parse_args(args) # get command to run command = parser.command() # call the command on all hosts for host in parser.hosts(): ssh_call(host, command) if __name__ == '__main__': main()