def plistcli(argv): """plistcli [-?D] <configfile>... Provides an interactive CLI for editing a property list file. Options: -? = This help text. -D = Debug on. """ import os from pycopia import getopt try: optlist, longopts, args = getopt.getopt(argv[1:], "?") except getopt.GetoptError: print (plistcli.__doc__) return for opt, val in optlist: if opt == "-?": print (plistcli.__doc__) return if opt == "-D": from pycopia import autodebug io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = RootCommands(ui) for fname in args: root = plistconfig.get_config(fname) cmd._setup(root, fname, "%%Yplistconfig%%N:%s> " % (fname,)) parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_plistconfig")) parser.interact()
def jsoncli(argv): """jsoncli [-?D] <configfile>... Provides an interactive CLI for editing a JSON format config file. Options: -? = This help text. -D = Debug on. """ import os from pycopia import getopt try: optlist, longopts, args = getopt.getopt(argv[1:], "?D") except getopt.GetoptError: print (jsoncli.__doc__) return for opt, val in optlist: if opt == "-?": print (jsoncli.__doc__) return elif opt == "-D": from pycopia import autodebug io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = RootCommands(ui) for fname in args: root = jsonconfig.get_config(fname) cmd._setup(root, fname, "%%Yjsonconfig%%N:%s> " % (fname,)) parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_jsonconfig")) parser.interact()
def __call__(self, argv): cf = self._config optlist, extraopts, args = getopt.getopt(argv[1:], "hdvc:f:n:N") for opt, optarg in optlist: if opt == "-h": print __doc__ sys.exit(2) if opt == "-d": cf.flags.DEBUG += 1 if opt == "-v": cf.flags.VERBOSE += 1 if opt == "-c" or opt == "-f": cf.mergefile(optarg) if opt == "-n": cf.NOTE = optarg if opt == "-N": cf.flags.NONOTE = True cf.update(extraopts) cf.argv = args # test args cf.arguments = [os.path.basename(argv[0])] + argv[1:] # original command line self.initialize() if cf.argv: self.run_modules(cf.argv) else: from pycopia import cliutils testlist = self.get_test_list() try: test = cliutils.choose(testlist) except: return None else: self.run_module(test) self.finalize()
def __call__(self, argv): cf = self.reporter.config cf.flags.DEBUG = 0 cf.flags.VERBOSE = 0 optlist, extraopts, args = getopt.getopt(argv[1:], "h?gdDvc:f:") for opt, optarg in optlist: if opt in ("-h", "-?"): print(TestReporterInterfaceDoc % (os.path.basename(argv[0]), )) return elif opt == "-g": self.reporter.report_global() elif opt == "-d": cf.flags.DEBUG += 1 elif opt == "-D": from pycopia import autodebug # top-level debug for framework bugs elif opt == "-v": cf.flags.VERBOSE += 1 elif opt == "-c" or opt == "-f": cf.mergefile(optarg) cf.evalupdate(extraopts) if not args: args = choose_tests() if not args: return objects, errors = module.get_objects(args) if errors: self.reporter.report_errors(errors) if objects: self.reporter.report_objects(objects)
def doccli(argv): """doccli [-h?] [-D] [<filename>] Create and interactively edit an XHTML document. """ filename = None try: optlist, longopts, args = getopt.getopt(argv[1:], "?hD") except getopt.GetoptError: print doccli.__doc__ return for opt, optarg in optlist: if opt in ("-?", "-h"): print doccli.__doc__ return elif opt == "-D": from pycopia import autodebug if args: filename = args[0] io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = TopLevel(ui) cmd._environ["filename"] = filename if filename: doc = XHTML.get_document(filename) else: doc = XHTML.new_document() cmd._setup(doc, "doc> ") parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_doccli")) parser.interact()
def __call__(self, argv): cf = self.reporter.config cf.flags.DEBUG = 0 cf.flags.VERBOSE = 0 optlist, extraopts, args = getopt.getopt(argv[1:], "h?gdDvc:f:") for opt, optarg in optlist: if opt in ("-h", "-?"): print (TestReporterInterfaceDoc % (os.path.basename(argv[0]),)) return elif opt == "-g": self.reporter.report_global() elif opt == "-d": cf.flags.DEBUG += 1 elif opt == "-D": from pycopia import autodebug # top-level debug for framework bugs elif opt == "-v": cf.flags.VERBOSE += 1 elif opt == "-c" or opt == "-f": cf.mergefile(optarg) cf.evalupdate(extraopts) if not args: args = choose_tests() if not args: return objects, errors = module.get_objects(args) if errors: self.reporter.report_errors(errors) if objects: self.reporter.report_objects(objects)
def adbsh(argv): """adbsh [-?hD] Provides an interactive session for ADB. Options: -? = This help text. -D = Enable debugging. """ try: optlist, longopts, args = getopt.getopt(argv[1:], "?hD") except getopt.GetoptError: print adbsh.__doc__ return for opt, optarg in optlist: if opt in ("-?", "-h"): print adbsh.__doc__ return elif opt == "-D": from pycopia import autodebug client = adb.AdbClient() io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = AdbClientCommands(ui) cmd._setup(client, "ADB> ") parser = CLI.CommandParser( cmd, historyfile=os.path.expandvars("$HOME/.hist_androidsh")) parser.interact()
def newpass(argv): """Change a users' password. newpass [--password=<newpass>] <username> """ try: opts, longopts, args = getopt.getopt(argv[1:], "h?") except getopt.GetoptError: print(newpass.__doc__) return for opt, optarg in opts: if opt in ("-?", "-h"): print(newpass.__doc__) return try: username = args[0] except IndexError: username = cliutils.get_input("Account name? ") password = longopts.get("password") if not password: password = ask_password() if not password: print("Passwords do not match, exiting.", file=sys.stderr) return user = models.query(models.User, username=username).one() user.password = password models.commit() update_shadow(username, password)
def dbconfig(argv): """dbconfig [-?D] Options: -? = This help text. -D = Debug on. """ global _session from pycopia import getopt try: optlist, longopts, args = getopt.getopt(argv[1:], "?") except getopt.GetoptError: print (dbconfig.__doc__) return for opt, val in optlist: if opt == "-?": print (dbconfig.__doc__) return if opt == "-D": from pycopia import autodebug io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = ConfigCommands(ui) _session = models.get_session() root = get_root(_session) cmd._setup(root, "%%Ydbconfig%%N:%s> " % (root.name,)) cmd._environ["session"] = _session parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_dbconfig")) parser.interact()
def smtpcli(argv): """smtpcli [-h] [-l <logfilename>] [-s <portname>] [host] [port] Provides an interactive session at a protocol level to an SMTP server. """ bindto = None port = 25 sourcefile = None paged = False logname = None try: optlist, longopts, args = getopt.getopt(argv[1:], "b:hp:s:l:g") except getopt.GetoptError: print(smtpcli.__doc__) return for opt, val in optlist: if opt == "-b": bindto = val if opt == "-l": logname = val elif opt == "-s": sourcefile = val elif opt == "-g": paged = True elif opt == "-h": print(smtpcli.__doc__) return elif opt == "-p": try: port = int(val) except ValueError: print(smtpcli.__doc__) return theme = UI.DefaultTheme(PROMPT) parser = CLI.get_cli(EmailClientCLI, paged=paged, theme=theme) if len(args) > 0: if len(args) > 1: port = int(args[1]) else: port = 25 host = args[0] else: host = "" if logname: parser.commands.logfile(["logfile", logname]) if host: parser.commands.connect(["connect"] + IF(bindto, ["-s", bindto], []) + [host, port]) else: parser.commands._print( "Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def __call__(self, argv): """Run the test runner. Invoke the test runner by calling it. """ cf = self.runner.config cf.flags.REPORT = False cf.flags.INTERACTIVE = False cf.flags.DEBUG = 0 cf.flags.VERBOSE = 0 optlist, extraopts, args = getopt.getopt(argv[1:], "h?dDviIrc:f:n:") for opt, optarg in optlist: if opt in ("-h", "-?"): print (TestRunnerInterfaceDoc % (os.path.basename(argv[0]),)) return elif opt == "-d": cf.flags.DEBUG += 1 elif opt == "-D": from pycopia import autodebug # top-level debug for framework bugs elif opt == "-v": cf.flags.VERBOSE += 1 elif opt == "-i": cf.flags.INTERACTIVE = True elif opt == "-I": cf.flags.INTERACTIVE = False elif opt == "-c" or opt == "-f": cf.mergefile(optarg) elif opt == "-n": cf.comment = optarg elif opt == "-r": cf.flags.REPORT = True cf.evalupdate(extraopts) # original command line arguments saved for the report cf.arguments = [os.path.basename(argv[0])] + argv[1:] # Save extra options for overriding configuration after a mergefile # because command line options should have highest precedence. self.runner.set_options(extraopts) if not args: if cf.flags.REPORT: self.runner.report_global() return 0 else: args = choose_tests() if not args: return 2 objects, errors = module.get_objects(args) if errors: logging.warn("Errors found while loading test object:") for error in errors: logging.warn(error) if objects: cf.argv = args self.runner.initialize() rv = self.runner.run_objects(objects) self.runner.finalize() return not rv # inverted due to shell semantics (zero is good) being different from result code else: return int(bool(errors)) + 2
def __call__(self, argv): """Run the test runner. Invoke the test runner by calling it. """ cf = self.runner.config cf.flags.REPORT = False cf.flags.INTERACTIVE = False cf.flags.DEBUG = 0 cf.flags.VERBOSE = 0 optlist, extraopts, args = getopt.getopt(argv[1:], "h?dDviIrc:f:n:") for opt, optarg in optlist: if opt in ("-h", "-?"): print(TestRunnerInterfaceDoc % (os.path.basename(argv[0]), )) return elif opt == "-d": cf.flags.DEBUG += 1 elif opt == "-D": from pycopia import autodebug # top-level debug for framework bugs elif opt == "-v": cf.flags.VERBOSE += 1 elif opt == "-i": cf.flags.INTERACTIVE = True elif opt == "-I": cf.flags.INTERACTIVE = False elif opt == "-c" or opt == "-f": cf.mergefile(optarg) elif opt == "-n": cf.comment = optarg elif opt == "-r": cf.flags.REPORT = True cf.evalupdate(extraopts) # original command line arguments saved for the report cf.arguments = [os.path.basename(argv[0])] + argv[1:] # Save extra options for overriding configuration after a mergefile # because command line options should have highest precedence. self.runner.set_options(extraopts) if not args: if cf.flags.REPORT: self.runner.report_global() return 0 else: args = choose_tests() if not args: return 2 objects, errors = module.get_objects(args) if errors: logging.warn("Errors found while loading test object:") for error in errors: logging.warn(error) if objects: cf.argv = args self.runner.initialize() rv = self.runner.run_objects(objects) self.runner.finalize() return not rv # inverted due to shell semantics (zero is good) being different from result code else: return int(bool(errors)) + 2
def run(self, argv): """Run the test runner. Invoke the test runner by calling it. """ cf = self.runner.config cf.flags.INTERACTIVE = True cf.flags.DEBUG = 0 cf.flags.VERBOSE = 0 optlist, longopts, args = getopt.getopt(argv[1:], "h?dDvIc:f:m:e:r:") for opt, optarg in optlist: if opt in ("-h", "-?"): print(TestRunnerInterfaceDoc.format( name=os.path.basename(argv[0]))) return elif opt == "-d": cf.flags.DEBUG += 1 elif opt == "-D": from pycopia import autodebug # noqa elif opt == "-v": cf.flags.VERBOSE += 1 elif opt == "-I": cf.flags.INTERACTIVE = False elif opt == "-c" or opt == "-f": cf.mergefile(optarg) elif opt == "-m": cf.comment = optarg elif opt == "-r": cf.reportname = optarg elif opt == "-e": cf.environmentname = optarg cf.evalupdate(longopts) # original command line arguments saved for the report cf.arguments = [os.path.basename(argv[0])] + argv[1:] ui = UI.get_userinterface(themename="ANSITheme") if not args: from . import simplechooser args = simplechooser.choose_tests(ui) if not args: return 10 objects, errors = module.get_objects(args) if errors: logging.warn("Errors found while loading test object:") for error in errors: logging.warn(error) if objects: cf.argv = args rv = self.runner.run(objects, ui) if rv is None: return 11 else: try: return int(rv) except TypeError: return 12 else: return len(errors) + 20
def snmpcli(argv): """snmpcli [-h] [-p <port>] [-s <scriptname>] [-m <module>] host community Provides an interactive session to an SNMP agent. """ port = 161 sourcefile = None logfile = None modname = None try: optlist, longopts, args = getopt.getopt(argv[1:], "hl:p:s:m:") except getopt.GetoptError: print(snmpcli.__doc__) return for opt, val in optlist: if opt == "-s": sourcefile = val elif opt == "-l": logfile = val elif opt == "-h": print(snmpcli.__doc__) return elif opt == "-p": try: port = int(val) except ValueError: print(snmpcli.__doc__) return elif opt == "-m": modname = val if not args: print(snmpcli.__doc__) return host = args[0] if len(args) > 1: community = args[1] else: community = "public" if modname: module = __import__(modname, globals(), locals(), ["*"]) manager = module.get_manager(host, community) else: manager = Manager.get_manager(host, community, mibs=[SNMPv2_MIB, IF_MIB]) parser = CLI.get_generic_cli( manager, SNMPManagerCommands, logfile=logfile, historyfile=os.path.expandvars("$HOME/.hist_snmpcli") ) if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def smtpcli(argv): """smtpcli [-h] [-l <logfilename>] [-s <portname>] [host] [port] Provides an interactive session at a protocol level to an SMTP server. """ bindto = None port = 25 sourcefile = None paged = False logname = None try: optlist, longopts, args = getopt.getopt(argv[1:], "b:hp:s:l:g") except getopt.GetoptError: print (smtpcli.__doc__) return for opt, val in optlist: if opt == "-b": bindto = val if opt == "-l": logname = val elif opt == "-s": sourcefile = val elif opt == "-g": paged = True elif opt == "-h": print (smtpcli.__doc__) return elif opt == "-p": try: port = int(val) except ValueError: print (smtpcli.__doc__) return theme = UI.DefaultTheme(PROMPT) parser = CLI.get_cli(EmailClientCLI, paged=paged, theme=theme) if len(args) > 0: if len(args) > 1: port = int(args[1]) else: port = 25 host = args[0] else: host = "" if logname: parser.commands.logfile(["logfile", logname]) if host: parser.commands.connect(["connect"]+IF(bindto, ["-s", bindto], [])+[host, port]) else: parser.commands._print("Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def __call__(self, argv): """Run the test runner. Invoke the test runner by calling it. """ cf = self.runner.config # this getopt() is a lightweight getopt that only considers # traditional options as options (e.g. -x). Any long-option form (e.g. # --reportname=default) is converted into a dictionary and is used to # update the configuration. This allows the user or test runner to # provide or alter configuration parameters at run time without # needing a pre-defined list to getopt(). from pycopia import getopt optlist, extraopts, args = getopt.getopt(argv[1:], "h?dviIc:f:n:") for opt, optarg in optlist: if opt in ("-h", "-?"): print TestRunnerInterfaceDoc % (os.path.basename(argv[0]), ) return if opt == "-d": cf.flags.DEBUG += 1 if opt == "-v": cf.flags.VERBOSE += 1 if opt == "-i": cf.flags.INTERACTIVE = True if opt == "-I": cf.flags.INTERACTIVE = False if opt == "-c" or opt == "-f": cf.mergefile(optarg) if opt == "-n": cf.comment = optarg cf.update(extraopts) cf.argv = args # test args # original command line arguments saved for the report cf.arguments = [os.path.basename(argv[0])] + argv[1:] # Save extra options for overriding configuration after a mergefile # because command line options should have highest precedence. self.runner.SetOptions(extraopts) if not args: from pycopia import cliutils l = GetModuleList() l.insert(0, None) arg = cliutils.choose(l, prompt="Select test") if arg is None: return args = [arg] objects, errors = module.GetObjects(args) if errors: print >> sys.stderr, "Errors found while loading test object:" for error in errors: print >> sys.stderr, error if objects: self.runner.Initialize() self.runner.RunObjects(objects) self.runner.Finalize()
def storagecli(argv): """storagecli [-?rg] [<scriptfile>...] Provides an interactive session to the configuration server. This allows you to interactively view and change the persistent database. Options: -? = This help text. -g = used paged output (like 'more'). """ from pycopia import getopt paged = False try: optlist, longopts, args = getopt.getopt(argv[1:], "?g") except getopt.GetoptError: print storagecli.__doc__ return for opt, val in optlist: if opt == "-?": print storagecli.__doc__ return elif opt == "-g": paged = True if paged: from pycopia import tty io = tty.PagedIO() else: io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cf = Storage.get_config(initdict=longopts) cf.reportfile = __name__.replace(".", "_") cf.logbasename = "%s.log" % (__name__.replace(".", "_"), ) cf.arguments = argv cmd = RootContainerEditor(ui) cmd._setup(cf, "root") parser = CLI.CommandParser( cmd, historyfile=os.path.expandvars("$HOME/.hist_storagecli")) if args: for arg in args: try: parser.parse(arg) except KeyboardInterrupt: break else: parser.interact()
def storagecli(argv): """storagecli [-?rg] [<scriptfile>...] Provides an interactive session to the configuration server. This allows you to interactively view and change the persistent database. Options: -? = This help text. -g = used paged output (like 'more'). """ from pycopia import getopt paged = False try: optlist, longopts, args = getopt.getopt(argv[1:], "?g") except getopt.GetoptError: print storagecli.__doc__ return for opt, val in optlist: if opt == "-?": print storagecli.__doc__ return elif opt == "-g": paged = True if paged: from pycopia import tty io = tty.PagedIO() else: io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cf = Storage.get_config(initdict=longopts) cf.reportfile = __name__.replace(".", "_") cf.logbasename = "%s.log" % (__name__.replace(".", "_"),) cf.arguments = argv cmd = RootContainerEditor(ui) cmd._setup(cf, "root") parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_storagecli")) if args: for arg in args: try: parser.parse(arg) except KeyboardInterrupt: break else: parser.interact()
def androidsh(argv): """androidsh [-d <index>] [-s <serial_no>] [-?hD] [<scriptfilename>] Provides an interactive session to an Android device connected via adb. Options: -d = Device index to use (default 1). -r = Device revision: sooner: 0, dream v2: 2, dream v3: 3 -s = Device serial number. -? = This help text. -D = Enable debugging. """ serial_no = None device_id = 1 try: optlist, longopts, args = getopt.getopt(argv[1:], "?hDd:") except getopt.GetoptError: print androidsh.__doc__ return for opt, optarg in optlist: if opt in ("-?", "-h"): print androidsh.__doc__ return elif opt == "-s": serial_no = optarg elif opt == "-d": device_id = int(optarg) elif opt == "-D": from pycopia import autodebug if serial_no is not None: dev = devices.GetDevice(serial_no) else: dev = devices.GetDevice(device_id) io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = AndroidCommands(ui) cmd._setup(dev, "%s-%s> " % ( dev.build.product, device_id, )) parser = CLI.CommandParser( cmd, historyfile=os.path.expandvars("$HOME/.hist_androidsh")) if args: scriptfilename = args[0] text = open(scriptfilename).read() parser.feed(text) else: parser.interact()
def remotecli(argv): """remotecli [-h|-?] [-g] [-s <script>] Provides an interactive session to a remote Client server object. Most of the methods in the module remote.Server may be called this way. """ from pycopia import getopt from pycopia.storage import Storage paged = False script = None try: optlist, longopts, args = getopt.getopt(argv[1:], "s:?hg") except getopt.GetoptError: print remotecli.__doc__ return for opt, val in optlist: if opt == "-?" or opt == "-h": print remotecli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val # do runtime setup cf = Storage.get_config(initdict=longopts) #testrunner.connect_user(cf) #testrunner.runtime_config(cf) # fake test module attributes cf.reportfile = "remotecli" cf.logbasename = "remotecli.log" cf.arguments = argv theme = UI.DefaultTheme(PROMPT) history = os.path.expandvars("$HOME/.hist_clientcli") parser = CLI.get_cli(TopLevelCLI, env=cf, paged=paged, theme=theme, historyfile=history) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact()
def imapcli(argv): """imapcli [-h|--help] [-S] [host] [port] Provides an interactive session at a protocol level to an IMAP server. If the "-S" argument is provided, will connect using SSL. """ from pycopia import getopt port = imaplib.IMAP4_PORT sourcefile = None paged = False ssl = True try: optlist, longopts, args = getopt.getopt(argv[1:], "hp:s:gS") except getopt.GetoptError: print(imapcli.__doc__) return for opt, val in optlist: if opt == "-s": sourcefile = val elif opt == "-h": print(imapcli.__doc__) return elif opt == "-g": paged = True elif opt == "-S": ssl = True elif opt == "-p": try: port = int(val) except ValueError: print(imapcli.__doc__) return theme = UI.DefaultTheme(PROMPT) parser = CLI.get_cli(ImapCLI, paged=paged, theme=theme) if len(args) > 0: parser.commands.connect(["connect"] + ((ssl == True) and ["-S"] or []) + args) else: parser.commands._print( "Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def remotecli(argv): """remotecli [-h|-?] [-g] [-s <script>] Provides an interactive session to a remote Client server object. Most of the methods in the module remote.Server may be called this way. """ from pycopia import getopt from pycopia.storage import Storage paged = False script = None try: optlist, longopts, args = getopt.getopt(argv[1:], "s:?hg") except getopt.GetoptError: print remotecli.__doc__ return for opt, val in optlist: if opt == "-?" or opt == "-h": print remotecli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val # do runtime setup cf = Storage.get_config(initdict=longopts) #testrunner.connect_user(cf) #testrunner.runtime_config(cf) # fake test module attributes cf.reportfile = "remotecli" cf.logbasename = "remotecli.log" cf.arguments = argv theme = UI.DefaultTheme(PROMPT) history=os.path.expandvars("$HOME/.hist_clientcli") parser = CLI.get_cli(TopLevelCLI, env=cf, paged=paged, theme=theme, historyfile=history) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact()
def imapcli(argv): """imapcli [-h|--help] [-S] [host] [port] Provides an interactive session at a protocol level to an IMAP server. If the "-S" argument is provided, will connect using SSL. """ from pycopia import getopt port = imaplib.IMAP4_PORT sourcefile = None paged = False ssl = True try: optlist, longopts, args = getopt.getopt(argv[1:], "hp:s:gS") except getopt.GetoptError: print(imapcli.__doc__) return for opt, val in optlist: if opt == "-s": sourcefile = val elif opt == "-h": print(imapcli.__doc__) return elif opt == "-g": paged = True elif opt == "-S": ssl = True elif opt == "-p": try: port = int(val) except ValueError: print(imapcli.__doc__) return theme = UI.DefaultTheme(PROMPT) parser = CLI.get_cli(ImapCLI, paged=paged, theme=theme) if len(args) > 0: parser.commands.connect(["connect"] + ((ssl == True) and ["-S"] or []) + args) else: parser.commands._print("Be sure to run 'connect' before anything else.\n") if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def instrumentshell(argv): """pdish [-?rg] Provides an interactive session to the GPIB bus. Options: -?, -h = This help text. -g = used paged output (like 'more'). -d = Enable debugging. """ paged = False try: optlist, longopts, args = getopt.getopt(argv[1:], "?hgd") except getopt.GetoptError: print instrumentshell.__doc__ return for opt, val in optlist: if opt in ("-?", "-h"): print instrumentshell.__doc__ return elif opt == "-g": paged = True elif opt == "-d": from pycopia import autodebug if paged: from pycopia import tty io = tty.PagedIO() else: io = CLI.ConsoleIO() env = measurecore.MeasurementContext() env.evalupdate(longopts) ui = CLI.UserInterface(io, env) conf = core._GetConfig() cmd = TopLevel(ui) cmd._setup(conf, "pdish> ") parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_pdish")) parser.interact()
def __call__(self, argv): """Invoke the suite runner by calling it with argument list. """ cf = self.runner.config optlist, extraopts, args = getopt.getopt(argv[1:], "h?dDviIc:f:n:") for opt, optarg in optlist: if opt in ("-h", "-?"): print(SuiteRunnerInterfaceDoc % (os.path.basename(argv[0]), )) return if opt == "-d": cf.flags.DEBUG += 1 if opt == "-D": from pycopia import autodebug # top-level debug for framework bugs if opt == "-v": cf.flags.VERBOSE += 1 if opt == "-i": cf.flags.INTERACTIVE = True if opt == "-I": cf.flags.INTERACTIVE = False if opt == "-c" or opt == "-f": cf.mergefile(optarg) if opt == "-n": cf.comment = optarg cf.evalupdate(extraopts) cf.arguments = [os.path.basename(argv[0])] + argv[1:] cf.argv = args self.runner.set_options(extraopts) if not args: from pycopia import cliutils choices = [(row.id, str(row)) for row in models.TestSuite.get_suites(self.dbsession)] choices.insert(0, (0, "Skip it")) chosen_id = cliutils.choose_key(dict(choices), 0, prompt="Suite? ") if chosen_id == 0: return args = [chosen_id] for testsuite in self.get_test_suites(args): suite = self.get_suite(testsuite) self.runner.initialize() self.runner.run_object(suite) self.runner.finalize()
def main(argv): """qashell [-dD] Run the QA shell. """ from pycopia import getopt debug = 0 try: optlist, longopts, args = getopt.getopt(argv[1:], "?hdD") except getopt.GetoptError: print (main.__doc__) return for opt, val in optlist: if opt in ("-?", "-h"): print (main.__doc__) return elif opt == "-d": debug += 1 elif opt == "-D": from pycopia import autodebug if debug: from pycopia import logwindow widgets.DEBUG = logwindow.DebugLogWindow(do_stderr=True) app = TestRunnerShell() try: app.run() except: if debug: ex, val, tb = sys.exc_info() from pycopia import debugger if debug > 1: from pycopia import IOurxvt io = IOurxvt.UrxvtIO() else: io = None debugger.post_mortem(tb, ex, val, io) widgets.DEBUG.close() if debug > 1: io.close() else: raise
def __call__(self, argv): """Invoke the suite runner by calling it with argument list. """ cf = self.runner.config optlist, extraopts, args = getopt.getopt(argv[1:], "h?dDviIc:f:n:") for opt, optarg in optlist: if opt in ("-h", "-?"): print (SuiteRunnerInterfaceDoc % (os.path.basename(argv[0]),)) return if opt == "-d": cf.flags.DEBUG += 1 if opt == "-D": from pycopia import autodebug # top-level debug for framework bugs if opt == "-v": cf.flags.VERBOSE += 1 if opt == "-i": cf.flags.INTERACTIVE = True if opt == "-I": cf.flags.INTERACTIVE = False if opt == "-c" or opt == "-f": cf.mergefile(optarg) if opt == "-n": cf.comment = optarg cf.evalupdate(extraopts) cf.arguments = [os.path.basename(argv[0])] + argv[1:] cf.argv = args self.runner.set_options(extraopts) if not args: from pycopia import cliutils choices = [(row.id, str(row)) for row in models.TestSuite.get_suites(self.dbsession)] choices.insert(0, (0, "Skip it")) chosen_id = cliutils.choose_key(dict(choices), 0, prompt="Suite? ") if chosen_id == 0: return args = [chosen_id] for testsuite in self.get_test_suites(args): suite = self.get_suite(testsuite) self.runner.initialize() self.runner.run_object(suite) self.runner.finalize()
def main(argv): """qashell [-dD] Run the QA shell. """ from pycopia import getopt debug = 0 try: optlist, longopts, args = getopt.getopt(argv[1:], "?hdD") except getopt.GetoptError: print(main.__doc__) return for opt, val in optlist: if opt in ("-?", "-h"): print(main.__doc__) return elif opt == "-d": debug += 1 elif opt == "-D": from pycopia import autodebug if debug: from pycopia import logwindow widgets.DEBUG = logwindow.DebugLogWindow(do_stderr=True) app = TestRunnerShell() try: app.run() except: if debug: ex, val, tb = sys.exc_info() from pycopia import debugger if debug > 1: from pycopia import IOurxvt io = IOurxvt.UrxvtIO() else: io = None debugger.post_mortem(tb, ex, val, io) widgets.DEBUG.close() if debug > 1: io.close() else: raise
def nmslog(argv): """ Usage: nmslog [-p port] [-d] [<logfile> ...] Record external syslog events. An optional list of file names may be supplied on the command line. The received event will be written to each file given, including stdout. The user may also type in a message at anytime which will also be added to the log files. The -d flag enables debugging mode. The -p flag specifies a non-standard UDP port to listen to. """ from pycopia import getopt port = 514 debug = False try: opts, longopts, args = getopt.getopt(argv[1:], "p:dh?") except getopt.GetoptError: print __doc__ return for opt, arg in opts: if opt == "-p": port = int(arg) if opt == "-d": debug = True elif opt in ("-?", "-h"): print __doc__ return sl = Syslog(args) get_dispatcher(("", port), sl.dispatch) sl.addlog(sys.stdout) print "Logging started. Listening on UDP port %d. You may type manual entries at will." % ( port, ) sl.message("STARTING", ", ".join(map(lambda o: o.name, sl.logfiles))) sa = SyslogApp(sl) sa.mainloop(debug) sl.close()
def nmslog(argv): """ Usage: nmslog [-p port] [-d] [<logfile> ...] Record external syslog events. An optional list of file names may be supplied on the command line. The received event will be written to each file given, including stdout. The user may also type in a message at anytime which will also be added to the log files. The -d flag enables debugging mode. The -p flag specifies a non-standard UDP port to listen to. """ from pycopia import getopt port = 514 debug = False try: opts, longopts, args = getopt.getopt(argv[1:], "p:dh?") except getopt.GetoptError: print __doc__ return for opt, arg in opts: if opt == "-p": port = int(arg) if opt == "-d": debug = True elif opt in ("-?", "-h"): print __doc__ return sl = Syslog(args) get_dispatcher(("", port), sl.dispatch) sl.addlog(sys.stdout) print "Logging started. Listening on UDP port %d. You may type manual entries at will." % (port,) sl.message("STARTING", ", ".join(map(lambda o: o.name, sl.logfiles))) sa = SyslogApp(sl) sa.mainloop(debug) sl.close()
def __call__(self, argv): """Invoke the job runner by calling it with argument list. """ cf = self.runner.config optlist, extraopts, args = getopt.getopt(argv[1:], "h?") for opt, optarg in optlist: if opt in ("-h", "-?"): print((JobRunnerInterfaceDoc % (os.path.basename(argv[0]),))) return cf.evalupdate(extraopts) self.runner.set_options(extraopts) for testjob in get_test_jobs(args): if testjob is None: continue cf.environmentname = testjob.environment.name if self.is_job_running(testjob.id): continue self.create_job_lock(testjob.id) try: if testjob.parameters: params = _parse_parameters(testjob.parameters) cf.arguments = testjob.parameters.split() else: params = {} cf.argv = [testjob.suite.name] cf.comment = "Automated test job %s(%s)." % (testjob.name, testjob.id) cf.reportname = testjob.reportname cf.evalupdate(params) self.runner.set_options(params) suite = get_suite(testjob.suite, cf) self.runner.initialize() self.runner.run_object(suite) self.runner.finalize() finally: self.remove_job_lock(testjob.id)
def __call__(self, argv): """Invoke the job runner by calling it with argument list. """ cf = self.runner.config optlist, extraopts, args = getopt.getopt(argv[1:], "h?") for opt, optarg in optlist: if opt in ("-h", "-?"): print JobRunnerInterfaceDoc % (os.path.basename(argv[0]), ) return cf.evalupdate(extraopts) self.runner.set_options(extraopts) for testjob in get_test_jobs(args): if testjob is None: continue cf.environmentname = testjob.environment.name if self.is_job_running(testjob.id): continue self.create_job_lock(testjob.id) try: if testjob.parameters: params = _parse_parameters(testjob.parameters) cf.arguments = testjob.parameters.split() else: params = {} cf.argv = [testjob.suite.name] cf.comment = "Automated test job %s(%s)." % (testjob.name, testjob.id) cf.reportname = testjob.reportname cf.evalupdate(params) self.runner.set_options(params) suite = get_suite(testjob.suite, cf) self.runner.initialize() self.runner.run_object(suite) self.runner.finalize() finally: self.remove_job_lock(testjob.id)
def main(argv): """dbedit [-d] """ debug = 0 try: optlist, longopts, args = getopt.getopt(argv[1:], "?hdD") except getopt.GetoptError: print((main.__doc__)) return for opt, val in optlist: if opt in ("-?", "-h"): print((main.__doc__)) return elif opt == "-d": debug += 1 elif opt == "-D": from pycopia import autodebug sess = models.get_session() try: app = DBEditor(sess, debug) try: app.run() except: if debug: ex, val, tb = sys.exc_info() from pycopia import debugger if debug > 1: from pycopia import IOurxvt io = IOurxvt.UrxvtIO() else: io = None debugger.post_mortem(tb, ex, val, io) if debug > 1: io.close() else: raise finally: sess.close()
def main(argv): """dbedit [-d] """ debug = 0 try: optlist, longopts, args = getopt.getopt(argv[1:], "?hdD") except getopt.GetoptError: print (main.__doc__) return for opt, val in optlist: if opt in ("-?", "-h"): print (main.__doc__) return elif opt == "-d": debug += 1 elif opt == "-D": from pycopia import autodebug sess = models.get_session() try: app = DBEditor(sess, debug) try: app.run() except: if debug: ex, val, tb = sys.exc_info() from pycopia import debugger if debug > 1: from pycopia import IOurxvt io = IOurxvt.UrxvtIO() else: io = None debugger.post_mortem(tb, ex, val, io) if debug > 1: io.close() else: raise finally: sess.close()
def dbcli(argv): """dbcli [-?] Provides an interactive session to the database. Options: -? = This help text. """ global _session from pycopia import getopt try: optlist, longopts, args = getopt.getopt(argv[1:], "?") except getopt.GetoptError: print (dbcli.__doc__) return for opt, val in optlist: if opt == "-?": print (dbcli.__doc__) return io = CLI.ConsoleIO() ui = CLI.UserInterface(io) cmd = DBSessionCommands(ui) _session = models.get_session() cmd._setup(_session, "db> ") cmd._environ["session"] = _session parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_dbcli")) if args: for arg in args: try: parser.parse(arg) except KeyboardInterrupt: break else: parser.interact()
def deleteuser(argv): """Delete a user deleteuser <username> """ try: opts, longopts, args = getopt.getopt(argv[1:], "h?") except getopt.GetoptError: print(deleteuser.__doc__) return for opt, optarg in opts: if opt in ("-?", "-h"): print(deleteuser.__doc__) return try: username = args[0] except IndexError: username = cliutils.get_input("Account name? ") user = models.query(models.User, username=username).one() models.delete(user) models.close() delete_shadow(username) shutil.rmtree(user.home, ignore_errors=True)
def __call__(self, argv): global _DEBUG, _FORCE, _dbsession, debugger domodule = False opts, longopts, args = getopt.getopt(argv[1:], "h?dMf") for opt, arg in opts: if opt in ("-h", "-?"): print (_DOC) return elif opt == "-d": from pycopia import debugger _DEBUG = True elif opt == "-f": _FORCE = True elif opt == "-M": domodule = True if not args: print (_DOC) return # Look like a test runner. self.config = config.get_config() _dbsession = models.get_session() self.config.options_override = longopts self.config.arguments = [] self.config.username = os.environ["USER"] try: if domodule: for arg in args: self.import_module(arg) else: for arg in args: self.import_package(arg) finally: _dbsession.close() _dbsession = None
def run_server(argv): username = None do_daemon = True debug = False killserver = False try: optlist, longopts, args = getopt.getopt(argv[1:], "dnh?kl:f:p:s:") except getopt.GetoptError: print(run_server._doc.format(procname=argv[0])) return if len(args) > 0: servername = args[0] else: servername = os.path.basename(argv[0]) logfilename = "/var/log/{}.log".format(servername) cffilename = "/etc/pycopia/{}.conf".format(servername) pidfile = "/var/run/{}.pid".format(servername) socketpath = '/tmp/{}.sock'.format(servername) for opt, optarg in optlist: if opt == "-n": do_daemon = False elif opt == "-k": killserver = True elif opt == "-d": from pycopia import autodebug # noqa debug = True elif opt == "-u": username = optarg elif opt == "-l": logfilename = optarg elif opt == "-f": cffilename = optarg elif opt == "-p": pidfile = optarg elif opt == "-s": socketpath = optarg elif opt in ("-h", "-?"): print(run_server._doc.format(procname=argv[0])) return 2 try: config = basicconfig.get_config(cffilename, CONFIGFILE=cffilename, PIDFILE=pidfile, SOCKETPATH=socketpath, LOGFILENAME=logfilename, DEBUG=debug, SERVERNAME=servername) except: ex, val, tb = sys.exc_info() logging.warn("Could not get server config: {} ({})".format( ex.__name__, val)) return 1 config.update(longopts) if username: config.USERNAME = username if killserver: kill_server(config) return 0 if check4server(config): logging.warn("Server {!r} already running on socket {!r}.".format( servername, socketpath)) return 1 if do_daemon and not debug: from pycopia import daemonize from pycopia import logfile lf = logfile.ManagedStdio(logfilename) daemonize.daemonize(lf, pidfile=pidfile) else: # for controller with open(pidfile, "w") as fo: fo.write("{}\n".format(os.getpid())) server = get_server(config) return int(server.run())
def run_server(argv): username = None do_daemon = True debug = False killserver = False try: optlist, longopts, args = getopt.getopt(argv[1:], "dnh?kl:f:p:s:") except getopt.GetoptError: print(run_server._doc.format(procname=argv[0])) return if len(args) > 0: servername = args[0] else: servername = os.path.basename(argv[0]) logfilename = "/var/log/{}.log".format(servername) cffilename = "/etc/pycopia/{}.conf".format(servername) pidfile = "/var/run/{}.pid".format(servername) socketpath = '/tmp/{}.sock'.format(servername) for opt, optarg in optlist: if opt == "-n": do_daemon = False elif opt == "-k": killserver = True elif opt == "-d": from pycopia import autodebug # noqa debug = True elif opt == "-u": username = optarg elif opt == "-l": logfilename = optarg elif opt == "-f": cffilename = optarg elif opt == "-p": pidfile = optarg elif opt == "-s": socketpath = optarg elif opt in ("-h", "-?"): print(run_server._doc.format(procname=argv[0])) return 2 try: config = basicconfig.get_config(cffilename, CONFIGFILE=cffilename, PIDFILE=pidfile, SOCKETPATH=socketpath, LOGFILENAME=logfilename, DEBUG=debug, SERVERNAME=servername) except: ex, val, tb = sys.exc_info() logging.warn( "Could not get server config: {} ({})".format(ex.__name__, val)) return 1 config.update(longopts) if username: config.USERNAME = username if killserver: kill_server(config) return 0 if check4server(config): logging.warn( "Server {!r} already running on socket {!r}.".format(servername, socketpath)) return 1 if do_daemon and not debug: from pycopia import daemonize from pycopia import logfile lf = logfile.ManagedStdio(logfilename) daemonize.daemonize(lf, pidfile=pidfile) else: # for controller with open(pidfile, "w") as fo: fo.write("{}\n".format(os.getpid())) server = get_server(config) return int(server.run())
def snmpcli(argv): """snmpcli [-h] [-p <port>] [-s <scriptname>] [-m <module>] host community Provides an interactive session to an SNMP agent. """ port = 161 sourcefile = None logfile = None modname = None try: optlist, longopts, args = getopt.getopt(argv[1:], "hl:p:s:m:") except getopt.GetoptError: print(snmpcli.__doc__) return for opt, val in optlist: if opt == "-s": sourcefile = val elif opt == "-l": logfile = val elif opt == "-h": print(snmpcli.__doc__) return elif opt == "-p": try: port = int(val) except ValueError: print(snmpcli.__doc__) return elif opt == "-m": modname = val if not args: print(snmpcli.__doc__) return host = args[0] if len(args) > 1: community = args[1] else: community = "public" if modname: module = __import__(modname, globals(), locals(), ["*"]) manager = module.get_manager(host, community) else: manager = Manager.get_manager(host, community, mibs=[SNMPv2_MIB, IF_MIB]) parser = CLI.get_generic_cli( manager, SNMPManagerCommands, logfile=logfile, historyfile=os.path.expandvars("$HOME/.hist_snmpcli")) if sourcefile: try: parser.parse(sourcefile) except CLI.CommandQuit: pass else: parser.interact()
def getopt(self, argv, shortopts): return getopt.getopt(argv[1:], shortopts)
def configurator_cli(argv): """configurator_cli [-s <script>] [-g] <device> Interact with a DUT configurator. If no device is specified use the testbed DUT. Options: -g Use paged output (like 'more') -s <script> Run a CLI script from the given file instead of entering interactive mode. """ import os from pycopia.QA import configurator from pycopia import getopt from pycopia.storage import Storage paged = False script = None try: optlist, longopts, args = getopt.getopt(argv[1:], "s:?g") except GetoptError: print configurator_cli.__doc__ return for opt, val in optlist: if opt == "-?": print configurator_cli.__doc__ return elif opt == "-g": paged = True elif opt == "-s": script = val if not args: print configurator_cli.__doc__ return if paged: from pycopia import tty io = tty.PagedIO() else: io = IO.ConsoleIO() # do runtime setup cf = Storage.get_config(initdict=longopts) cf.reportfile = "configurator_cli" cf.logbasename = "configurator_cli.log" cf.arguments = argv dev = cf.devices[args[0]] ctor = configurator.get_configurator(dev, logfile=cf.logfile) # construct the CLI theme = ConfiguratorTheme("Configurator> ") ui = UI.UserInterface(io, cf, theme) cmd = CLI.get_generic_cmd(ctor, ui, ConfiguratorShellCLI) cmd.device = dev # stash actual device for future reference parser = CLI.CommandParser( cmd, historyfile=os.path.expandvars("$HOME/.hist_configurator")) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact() try: ctor.exit() except: pass
def controller_cli(argv): """controller_cli [-s <script>] [-g] <device> Interact with a DUT configurator. If no device is specified use the testbed DUT. Options: -g Use paged output (like 'more') -s <script> Run a CLI script from the given file instead of entering interactive mode. """ import os from pycopia import getopt from pycopia.QA import controller from pycopia.QA import config paged = False script = None try: optlist, longopts, args = getopt.getopt(argv[1:], "s:?g") except GetoptError: print((controller_cli.__doc__)) return for opt, val in optlist: if opt == "-?": print((controller_cli.__doc__)) return elif opt == "-g": paged = True elif opt == "-s": script = val if not args: print((controller_cli.__doc__)) return if paged: from pycopia import tty io = tty.PagedIO() else: io = IO.ConsoleIO() # do runtime setup cf = config.get_config(initdict=longopts) cf.reportfile = "controller_cli" cf.logbasename = "controller_cli.log" cf.arguments = argv dev = cf.devices[args[0]] cont = controller.get_configurator(dev, logfile=cf.logfile) # construct the CLI theme = ConfiguratorTheme("Controller> ") ui = UI.UserInterface(io, cf, theme) cmd = CLI.get_generic_cmd(cont, ui, ConfiguratorShellCLI) cmd.device = dev # stash actual device for future reference parser = CLI.CommandParser(cmd, historyfile=os.path.expandvars("$HOME/.hist_controller")) if script: try: parser.parse(script) except KeyboardInterrupt: pass else: parser.interact() try: cont.close() except: pass
def newuser(argv): """Create a new user newuser [-Mm] [<longopts>] <username> Options: -M Do NOT make home directory. -m Only make home directory for existing user with no home directory. Where long options are: --first_name=<firstname> --last_name=<lastname> --password=<newpass> --shell=<shell> --home=<home> You will be prompted for missing information. This function should be run as root user. """ makehome = True onlyhome = False try: opts, longopts, args = getopt.getopt(argv[1:], "h?Mm") except getopt.GetoptError: print(newuser.__doc__) return for opt, optarg in opts: if opt in ("-?", "-h"): print(newuser.__doc__) return elif opt == "-M": makehome = False elif opt == "-m": onlyhome = True try: username = args[0] except IndexError: username = cliutils.get_input("Account name? ") try: pwent = passwd.getpwnam(username) except KeyError: pass else: if onlyhome: make_homedir(pwent.home, pwent.uid, pwent.gid) return else: print("User already exists, exiting.", file=sys.stderr) return password = longopts.get("password") if not password: password = ask_password() if not password: print("Passwords do not match, exiting.", file=sys.stderr) return # Get maximum UID value from passwd and database, not including system ones. uidl = [pwe.uid for pwe in passwd.getpwall() if pwe.uid < 10000] dblist = [u.uid for u in models.dbsession.query(models.User).all()] uidl.extend(dblist) uid = max(uidl) + 1 first_name = longopts.get("first_name") if not first_name: first_name = cliutils.get_input("First Name? ") last_name = longopts.get("last_name") if not last_name: last_name = cliutils.get_input("Last Name? ") gecos = "{}, {}".format(last_name, first_name) shell = longopts.get("shell") if not shell: shell = cliutils.get_input("Shell? ", default="/bin/sh") home = longopts.get("home") if not home: home = cliutils.get_input("Homedir? ", default="/home/{}".format(username)) email = longopts.get("email") if not email: email = cliutils.get_input("Email? ") primary_grp = models.dbsession.query(models.Group).filter(models.Group.groupname == "users").one() glist = models.dbsession.query(models.Group).all() glist.remove(primary_grp) sup_groups = cliutils.choose_multiple(glist, prompt="Extra groups?") superuser = cliutils.yes_no("Is admin?") user = models.create( models.User, username=username, uid=uid, gid=primary_grp.gid, gecos=gecos, first_name=first_name, last_name=last_name, shell=shell, homedir=home, email=email, is_superuser=superuser, is_active=True, ) user.password = password models.dbsession.add(user) models.dbsession.commit() user.groups = sup_groups models.dbsession.commit() new_shadow(username, password) if makehome: make_homedir(home, user.uid, user.gid) return user