def get_show_int_stats(self): chunks = self.chunker(CLI(self.cmds['stats'][0], False).get_output(), r'^Eth\s+\d+|^Po\s+\d+', regex=True) for chunk in chunks: for line in chunk: line_list = line.split() id = '{} {}'.format(line.lower()[0], line_list[1]) if id in self.data.keys(): self.data[id]['Packets_RX'] = line_list[2] self.data[id]['Packets_TX'] = line_list[3] self.data[id]['Errors_RX'] = line_list[4] self.data[id]['Errors_TX'] = line_list[5] self.data[id]['Discards_RX'] = line_list[6] self.data[id]['Discards_TX'] = line_list[7] self.data[id]['CRC_RX'] = line_list[8] chunks = self.chunker(CLI(self.cmds['stats'][1], False).get_output(), r'^Interface', regex=True) for chunk in chunks: id = '{} {}'.format(chunk[0].split()[1].lower()[0], chunk[0].split()[2]) if id in self.data.keys(): self.data[id]['mbits/sec_rx'] = chunk[1].split()[1] self.data[id]['mbits/sec_tx'] = chunk[1].split()[2]
def challenge_factor(): """A function to take the multiple """ factor = CLI.mulfactor_input() min_donation = CLI.min_donation_input() max_donation = CLI.max_donation_input() donors.multiply_factor(factor, min_donation, max_donation, **donors.donors_collection_data)
def projections(): fullname = CLI.fullname_input() if fullname in donors.donors_collection_data.keys(): projected_donor = { fullname: donors.donors_collection_data[fullname] } factor = CLI.mulfactor_input() min_donation = CLI.min_donation_input() max_donation = CLI.max_donation_input() donors.multiply_factor(factor, min_donation, max_donation, **projected_donor)
def __get_log_message(self): """Returns the latest log message text for the msgid(s) in LOG_MSGID_LIST.""" self.logger.info('Executing show log raslog reverse.') log_output = CLI( 'show log raslog reverse | include ' + '|'.join(self.data['log_msgid_list']), False).get_output()[0] msgid = log_output.split(', ')[1][1:-1] message = ', '.join(log_output.split(', ')[6:]) self.data['log_message'][msgid] = message return
def main(): if len(sys.argv) > 1: command = sys.argv[1] chmpship_name = sys.argv[2] chmpship_races_count = sys.argv[3] interface = CLI(command, chmpship_name, chmpship_races_count) interface.begin() else: print(hello_message()) print(menu_message())
def main(): # resolving the '-' issue readline.set_completer_delims(readline.get_completer_delims().replace('-', '')) cli = CLI() if len(sys.argv) > 1: try: cli.onecmd(' '.join(sys.argv[1:])) except BadResponseError as e: print(str(e)) else: prompt_for_credentials() cli.cmdloop()
def __get_event_handler_policy(self): """Gets the event-handler activation config. Stores the parsed config in self.config""" event_activate_config = CLI( 'show running-config event-handler ' + 'activate ' + self.data['event_name'], False).get_output() self.config['event_handler_activate'] = {'status': False} self.config['action_timeout'] = {} self.config['delay'] = {} self.config['interval'] = {} self.config['iterations'] = {} self.config['trigger_mode'] = {} self.config['trigger_function'] = {} for line in event_activate_config: if line == '% No entries found.': return self.config['event_handler_activate']['status'] = True self.__find_event_handler_activate(line) self.__find_action_timeout(line) self.__find_delay(line) self.__find_interval(line) self.__find_iterations(line) self.__find_trigger_mode(line) self.__find_trigger_function(line) return
def thank_you(): """Send a thank you letter""" fullname = CLI.fullname_input() if fullname.isalpha(): if fullname == str("list"): donors.display_donors() elif fullname in donors.donors_collection_data.keys(): amount = CLI.amount_input() donor.update_data_print_thanks(amount, fullname) else: try: amount = CLI.amount_input() donor.add_data_print_thanks(amount, fullname) except ValueError: print("Enter the correct amount in integer") else: print("Enter the donor name correctly")
def main(): data = {} try: output = CLI('show version', do_print=False).get_output() data = output[2] except: pass return data
def main(): data = {} try: output = CLI('show system', do_print=False).get_output() data = output[5] except: pass return data
def __init__(self): view = CLI() args = self.parse_args() base_path = Path(args.path) data = tp.parse_torrent_file(args.torrent) for file in data["info"]["files"]: self.paths.append(Path(base_path, *file["path"])) not_in_path = self.check_dir(base_path) print("Files not in path: ", len(not_in_path)) if len(not_in_path) != 0: print("Files:") view.display_file_list(not_in_path) if not args.dry_run and view.ask_file_delete(): self.delete_files(not_in_path)
def main(): # if the user passes no arguements then run the gui if len(sys.argv) == 1: root = Tk() gui = GUI(root) root.mainloop() # else run the cli else: myargs = getopts(sys.argv) cli = CLI(myargs)
def do_unregistration(self): self.logger.info('removing the config for the event %s: ', self.data['event_name']) config = ['configure terminal'] config.append('no event-handler activate %s' % self.data['event_name']) config.append('no event-handler %s' % self.data['event_name']) config.append('end') config.append('copy run start') config.append('y') CLI('\n'.join(config), False) return
def get_show_media(self): chunks = self.chunker(CLI(self.cmds['media'], False).get_output(), r'Interface', regex=True) for chunk in chunks: id = '{} {}'.format(chunk[0].split()[1].lower()[0], chunk[0].split()[2]) if id in self.data.keys(): self.data[id]['QSFP'] = ' '.join( chunk[1].split()[3:]).strip('()') self.data[id]['RX_Power'] = chunk[2].split()[-2]
def __register_event_handler(self): """Creates or modifies the event handler.""" config = ['configure terminal'] config.append('event-handler %s' % self.data['event_name']) config = config + self.__build_triggers() config = config + self.__build_action() config = config + self.__build_description() config.append('end') config.append('copy run start') config.append('y') CLI('\n'.join(config), False) return
def parse_networks(self): containers = [] for net in self.networks: driver = net['Driver'] if (driver == dname): net_name = net['Name'] net_containers = net['Containers'] for cont_id, cont in net_containers.iteritems(): container = {} container['Id'] = cont_id if container['Id'].startswith('ep-'): continue container['Name'] = cont['Name'] container['IPv4Address'] = cont['IPv4Address'] container['MacAddress'] = cont['MacAddress'] container['Network'] = net_name container['EndpointId'] = cont['EndpointID'] cmap = self.container_map[cont['Name']] for item, cont_info in cmap.iteritems(): container['HostName'] = cont_info['IP'] fmt_mac = format_mac(cont['MacAddress']) showmac = CLI( "show mac-address-table address {}".format(fmt_mac)) found = 0 for item in showmac.get_ouput(): if "VlanId" in item: continue elif "Total" in item: continue else: found = 1 mac_split = item.split() ifname = mac_split[4] + " " + mac_split[5] container['SwitchInterface'] = ifname containers.append(container) self.parsed_containers = containers
def parse_networks(self): containers = [] for net in self.networks: driver = net['Driver'] if(driver==dname): net_name = net['Name'] net_containers = net['Containers'] for cont_id,cont in net_containers.iteritems(): container = {} container ['Id'] = cont_id if container['Id'].startswith('ep-'): continue container ['Name'] = cont['Name'] container ['IPv4Address'] = cont['IPv4Address'] container ['MacAddress'] = cont['MacAddress'] container ['Network'] = net_name container ['EndpointId'] = cont['EndpointID'] cmap = self.container_map[cont['Name']] for item, cont_info in cmap.iteritems(): container['HostName'] = cont_info['IP'] fmt_mac = format_mac(cont['MacAddress']) showmac = CLI("show mac-address-table address {}".format(fmt_mac)) found = 0 for item in showmac.get_ouput(): if "VlanId" in item: continue elif "Total" in item: continue else: found = 1 mac_split = item.split() ifname = mac_split[4] + " " + mac_split[5] container['SwitchInterface'] = ifname containers.append(container) self.parsed_containers = containers
def __activate_event_handler(self): """activates the event_handler.""" config = ['configure terminal'] config.append('event-handler activate %s' % self.data['event_name']) config.append(self.__build_action_timeout()) config.append(self.__build_delay()) config.append(self.__build_interval()) config.append(self.__build_iterations()) config.append(self.__build_trigger_mode()) config.append(self.__build_trigger_function()) config.append('end') config.append('copy run start') config.append('y') CLI('\n'.join(config), False) return
def get_show_int_status(self): chunks = self.chunker(CLI(self.cmds['status'], False).get_output(), r'^Eth\s+\d+|^Po\s+\d+', regex=True) for chunk in chunks: for line in chunk: line_list = line.split() id = '{} {}'.format(line.lower()[0], line_list[1]) self.init_interface(id) self.interface_order.append(id) self.data[id]['Link'] = line_list[2] name_index = 6 if self.data[id]['Link'] == 'connected': name_index = 7 if len(line_list) - 1 >= name_index: self.data[id]['Name'] = ' '.join(line_list[name_index:])
def __get_event_handler_config(self): """Gets the event-handler config. Stores the parsed config in self.config""" self.logger.info('Getting the running config for the event %s: ', self.data['event_name']) event_handler_config = CLI( 'show running-config event-handler %s' % self.data['event_name'], False).get_output() self.config['trigger'] = None self.config['event_handler_name'] = None self.config['action'] = None self.config['description'] = None if ('syntax error: element does not exist' not in event_handler_config and '% No entries found.' not in event_handler_config): for line in event_handler_config: self.__find_event_handler_name(line) self.__find_trigger(line) self.__find_action(line) self.__find_description(line) return
def main(): # resolving the '-' issue readline.set_completer_delims(readline.get_completer_delims().replace( '-', '')) cli = CLI() if len(sys.argv) > 1: try: cli.onecmd(' '.join(sys.argv[1:])) except BadResponseError as e: print(str(e)) else: prompt_for_credentials() cli.cmdloop()
if os.environ["key_server_site"] == "": while True: site_name = raw_input("Key Server Path: ") if site_name[-1] == "/": site_name = site_name[:-1] sn_conf = raw_input("Is this Correct? [y/n] ") if sn_conf.lower() == "y": os.environ["key_server_site"] = site_name with open("config.json", "w") as config_file: config_file.write(json.dumps({'site_name': site_name})) print("Config Saved\n\n") break print("Key Server Admin") user_name = raw_input("Username: "******"Password: "******"Login info is not correct.") while True: command = raw_input("%s > " % (CLI.current_app if CLI.current_app != "" else "~")) cli.command(command)
if __name__ == "__main__" : try : # Global parser parser = argparse.ArgumentParser(description="BunkerWeb Command Line Interface") subparsers = parser.add_subparsers(help="command", dest="command") # Unban subparser parser_unban = subparsers.add_parser("unban", help="remove a ban from the cache") parser_unban.add_argument("ip", type=str, help="IP address to unban") # Parse args args = parser.parse_args() # Instantiate CLI cli = CLI() # Execute command ret, err = False, "unknown command" if args.command == "unban" : ret, err = cli.unban(args.ip) if not ret : print("CLI command status : ❌ (fail)") print(err) os._exit(1) else : print("CLI command status : ✔️ (success)") print(err) os._exit(0)
#!/usr/bin/env python3 from Donor import Donor from DonorCollection import DonorCollection from CLI import CLI if __name__ == '__main__': donor = Donor() donors = DonorCollection() cli = CLI() def thank_you(): """Send a thank you letter""" fullname = CLI.fullname_input() if fullname.isalpha(): if fullname == str("list"): donors.display_donors() elif fullname in donors.donors_collection_data.keys(): amount = CLI.amount_input() donor.update_data_print_thanks(amount, fullname) else: try: amount = CLI.amount_input() donor.add_data_print_thanks(amount, fullname) except ValueError: print("Enter the correct amount in integer") else: print("Enter the donor name correctly") def challenge_factor():
else: print '\nDISABLED HOTSTART. All Keitlheys will be reset.\n' print 'You want to proceed? (yes/no)', hotstart = query(0) ####################################### # Spawn command line interface ####################################### # The CLI gets its own thread. Tkinter (display GUI) needs to be the # main thread. devices = DeviceReader.get_devices(config, hotstart) for k in devices: devices[k].start() myCLI = CLI() myCLI.set_keithleys(devices) myCLI.start() ####################################### # Signal handling ####################################### def signal_handler(signal, frame): print 'Received SIGINT' print 'You have to press ctrl + D to exit the interpreter' signal.signal(signal.SIGINT, signal_handler)
def main(): try: download_brocade_config() CLI('copy flash://rackhd_brocade_config running-config', do_print=False) except: pass
# -*- coding: utf-8 -*- ###################################################################### # Program for registrering av medlemmer # # Medlemmer lagres i en teksfil på formatet #N Full Name::user name # # Skrevet av Sindre Wetjen, orginal av Line Moseng # ###################################################################### import sys from CLI import CLI if __name__ == "__main__": print "Welcome to verdandes simple registration system" print "type 'help' for help" output = "default.db" if sys.argv.count('-o') != 0: oindx = 1 + sys.argv.index('-o') output = sys.argv[oindx] + ".db" if "--cli" in sys.argv or "-c" in sys.argv: cli = CLI(output) cli.start() else: try: import GUI GUI.start(output) except Exception as e: print "There was an error with the GUI, falling back to CLI" cli = CLI(output) cli.start()
def cmdProcessor(self): cli = CLI(self.family) cli.cmdloop() return
def main(): interface = CLI("cinema.db") interface.start()
def run_CLI(): check_root() from CLI import CLI CLI().cmdloop()
from CLI import CLI from Components import * temp = "A.jpg" a = ProgressBar(tot=20, title="RANDOM bar", preset='magic', info=lambda cur, tot: '%6.2f - %5s' % (cur / tot * 100.0, temp)) b = CLIComponent(align='center') CLI.init([[a], [b]], borderstyle=('magenta', None, ['bold'])) @RedirectWrapper(target_cli=CLI) def foo1(j): if (j % 2 == 0): print("Loss = MAGIC") if (j == 8): print("HAHAHAHAHA\nRandom output from random package\nHate them") if (j == 12): warnings.warn("A really annoying deprecated warning", DeprecationWarning) if (j == 15): warnings.warn("A not so annoying future warning", FutureWarning) for j in range(20): CLI.cnt = j
import os import logging from CLI import CLI from Web import WebServer logging.basicConfig(filename='log.log', level=logging.DEBUG) logging.getLogger().setLevel(logging.DEBUG) handler = logging.StreamHandler(sys.stdout) root = logging.getLogger() root.setLevel(logging.DEBUG) root.addHandler(handler) if __name__ == "__main__": try: Configuration.read_conf() ArgumentParser.handle_args() if Configuration.Config.START_WEB_SERVER: WebServer.start() else: CLI.start_cli_tool() except KeyboardInterrupt: print('\n') try: sys.exit(0) except SystemExit: os.exit(0)
def main(stdscr): """The Main Game!!!""" # init pygame #pygame.init(); pygame.display.init() pygame.joystick.init(); noPlayers = pygame.joystick.get_count(); # no controllers, no game. if noPlayers == 0: raise(Exception('no controllers detected')) return # init CLI cli = CLI(stdscr, noPlayers); sys.stdout = cli; Game.cli = cli; cli.setEventHandler(Game.inputHandler); # run through setup steps Game.setupState = 0; while Game.setupState < len(Game.setupStep): # still setting up cli.log('Setup step %i of %i' % (Game.setupState + 1, len(Game.setupStep))); cli.instructions = Game.setupStep[Game.setupState]["inst"]; cli.inputloop(); time.sleep(0.2); # throttle cli.instructions = '(S)tart, (L)ist Serial or (Q)uit'; # update timer thread def update(): cli.updateTime(Game.timer.getTime()); Game.cli.printGameScreen(); t = threading.Timer(0.1, update); t.daemon = True; t.start(); update(); # start # init each player for i in range(noPlayers): # joystick def playprint(str): cli.playerLog(i, str); try: Game.joystick[i] = InputDevice(playprint); except IndexError: Game.joystick.append(InputDevice(playprint)); Game.joystick[i].start(i); steeringAxis = Game.conf["controller"]["steeringAxis"]; accBtn = Game.conf["controller"]["accBtn"]; revBtn = Game.conf["controller"]["revBtn"]; powBtn = Game.conf["controller"]["powBtn"]; Game.joystick[i].configure(steeringAxis, accBtn, revBtn, powBtn); # player try: Game.player[i] = Player(); except IndexError: Game.player.append(Player()); # serial/Zumo try: port = Game.conf["zumoser"][i]; try: Game.ser[i] = serial.Serial(port, baudrate=9600); except IndexError: Game.ser.append(serial.Serial(port, baudrate=9600)); try: Game.zumo[i] = Zumo(Game.ser[i], 0.01); except IndexError: Game.zumo.append(Zumo(Game.ser[i], 0.01)); # 1 thread per zumo Game.zumo[i].beginControlThrustSteer( Game.joystick[i].getSpeed, Game.joystick[i].getDir, Game.player[i].getBoost) cli.playerTrackXY(i, Game.joystick[i].getDir, Game.joystick[i].getSpeed) playprint('Initialised on %s' % port) except OSError: playprint('Could not initialise.') InputDevice.startReadThread(0.01); # 1 thread for all joysticks while cli.running: cli.inputloop();
def main(): CLI.start()
from CLI import CLI if __name__ == '__main__': CLI()