class BasePlugin(Cmd): """ BasePlugin - the base class which all of our plugins should inherit from. It is meant to define all the necessary base functions for plugins. """ prompt = '>> ' ruler = '-' intro = banner() terminators = [] CATEGORY_SHELL = to_bold_cyan('Shell Based Operations') CATEGORY_GENERAL = to_bold_cyan('General Commands') def __init__(self): Cmd.__init__(self, startup_script=read_config().get('STARTUP_SCRIPT', ''), use_ipython=True) self.aliases.update({'exit': 'quit', 'help': 'help -v'}) self.hidden_commands.extend([ 'load', 'pyscript', 'set', 'shortcuts', 'alias', 'unalias', 'shell', 'macro' ]) self.t = Terminal() self.selected_client = None self.prompt = self.get_prompt() self.allow_cli_args = False # Alerts Thread self._stop_thread = False self._seen_clients = set(Client.unique_client_ids()) self._alert_thread = Thread() # Register the hook functions self.register_preloop_hook(self._alert_thread_preloop_hook) self.register_postloop_hook(self._alert_thread_postloop_hook) # Set the window title self.set_window_title('<< JSShell 2.0 >>') categorize([ BasePlugin.do_help, BasePlugin.do_quit, BasePlugin.do_py, BasePlugin.do_ipy, BasePlugin.do_history, BasePlugin.do_edit ], BasePlugin.CATEGORY_GENERAL) self.register_postparsing_hook( self._refresh_client_data_post_parse_hook) def _alert_thread_preloop_hook(self) -> None: """ Start the alerter thread """ self._stop_thread = False self._alert_thread = Thread(name='alerter', target=self._alert_function) self._alert_thread.start() def _alert_thread_postloop_hook(self) -> None: """ Stops the alerter thread """ self._stop_thread = True if self._alert_thread.is_alive(): self._alert_thread.join() def _alert_function(self) -> None: """ When the client list is larger than the one we know of alert the user that a new client has registered """ while not self._stop_thread: if self.terminal_lock.acquire(blocking=False): current_clients = set(Client.unique_client_ids()) delta = current_clients - self._seen_clients if len(delta) > 0: self.async_alert( self.t.bold_blue(' << new client registered >>'), self.prompt) self._seen_clients = current_clients self.terminal_lock.release() sleep(0.5) def print_error(self, text: str, end: str = '\n', start: str = '') -> None: """ Prints a formatted error message """ self.poutput(start + self.t.bold_red('[-]') + ' ' + self.t.red(text), end=end) def print_info(self, text: str, end: str = '\n', start: str = '') -> None: """ Prints a formatted informational message """ self.poutput(start + self.t.bold_yellow('[!]') + ' ' + self.t.yellow(text), end=end) def print_ok(self, text: str, end: str = '\n', start: str = '') -> None: """ Prints a formatted success message """ self.poutput(start + self.t.bold_green('[+]') + ' ' + self.t.green(text), end=end) def print_pairs(self, title: str, body: Dict[str, str], just_return: bool = False, colors: bool = True) -> Union[str, None]: """ Prints pairs of values with a certain title """ if colors: data = [self.t.bold_white_underline(title)] else: data = [title] for key, value in body.items(): k = key + ':' if colors: data.append(f' - {self.t.bold(k)} {value}') else: data.append(f' - {k} {value}') if just_return: return '\n'.join(data) self.ppaged('\n'.join(data)) def select_client(self, client: Client) -> None: """ Handles the operation of selecting a new client """ self.selected_client = client self.update_prompt() def _refresh_client_data_post_parse_hook( self, params: PostparsingData) -> PostparsingData: """ Refreshes the selected client data from the database. We do that because of `mongoengine`s behaviour, where if we set the current client, we do not track for modifications. This way, before every command is parsed we re-select the client """ if self.selected_client: cid = self.selected_client.cid self.select_client(Client.objects(cid=cid).first()) return params def get_prompt(self) -> str: """ Handles the operations of getting the prompt string """ prompt = self.t.bold_cyan('>> ') if self.selected_client: client_id = self.t.bold_red(self.selected_client.cid) prompt = self.t.cyan(f"[Client #{client_id}]") + ' ' + prompt return prompt def update_prompt(self) -> None: """ Handles what is needed when updating the prompt """ self.prompt = get_prompt(self)
# define data paths path = config.data_path # obtain the yaml skelton with open(config.yaml_skelton_path) as f: default_string = f.read() # for each sample that will be generated from search space space for i in xrange(20): timestamp = get_timestamp() print t.bold_red('ITERATION:'), t.bold_red(str(i)), "started at: ", timestamp samp = sample(spa) # generate sample (will give a description of a model) print t.bold_cyan('SAMP'), samp mod = build(samp) # based on description generated build an object that will fit into yaml_parser print t.bold_blue('MODEL'), mod # define weight decay parameters. They depend on the number of layers (there is one parameter fo each layer) weight_decay_coeffs = yp.parse_weight_decay(mod) # generate a filename to store the best model pkl_filename = join(config.path_for_storing, timestamp+"best_"+str(i)+'_'+".pkl") # create dictionary with hyper parameters hyper_params = {'model': yp.parse_to_yaml(mod), 'path': yp.parse_to_yaml(path), 'weight_decay_coeffs': weight_decay_coeffs, 'pkl_filename': pkl_filename} # fill the yaml skelton with hyperparameters
class Interface: def __init__(self, config_filename): self.config_filename = config_filename self.config = collections.OrderedDict() self.term = Terminal() self.hline = u'\u2500' self.left_up = u'\u250c' self.right_up = u'\u2510' self.left_down = u'\u2514' self.right_down = u'\u2518' self.left_middle = u'\u251c' self.right_middle = u'\u2524' self.vline = u'\u2502' self.TITLE = [ 'SDNProbe: A Lightweight Tool for Securing SDN Data Plane with Active Probing' .center(self.term.width - 2) ] self.MENU = [ 'Show the configure file', 'Generate test packets from topology file', 'Generate topology graph for the controller as input', 'Start probing', 'Exit (or press q)' ] self.menu_pos = 0 def show_menu(self): while True: os.system('clear') print self.left_up + self.hline * (self.term.width - 2) + self.right_up print self.vline + self.term.bold_cyan(self.TITLE[0]) + self.vline print self.left_middle + self.hline * (self.term.width - 2) + self.right_middle for i, menu in enumerate(self.MENU): if i == self.menu_pos: print self.vline + ' ' + self.term.yellow_reverse( '[' + str(i + 1) + '] ' + menu) + ' ' * ( self.term.width - len(menu) - 7) + self.vline else: print self.vline + ' ' + '[' + str( i + 1) + '] ' + menu + ' ' * ( self.term.width - len(menu) - 7) + self.vline print self.left_down + self.hline * (self.term.width - 2) + self.right_down print press = self.getch() if press == 'up': self.menu_pos = (self.menu_pos - 1) % (len(self.MENU)) elif press == 'down': self.menu_pos = (self.menu_pos + 1) % (len(self.MENU)) elif press == 'exit': return 5 elif press == 'enter': return self.menu_pos + 1 def read_config(self): try: with open(self.config_filename, 'r') as f: for line in f: var, val = line.strip().split('=') self.config[var] = val except IOError: self.print_IOError(self.config_filename) exit() except: print self.term.bold_red('[-] Error') exit() def show_config(self): max_var_len = len(max(self.config.keys(), key=len)) max_val_len = len(max(self.config.values(), key=len)) width = max_var_len + 3 + max_val_len + 1 print self.term.bold_green(' [+] Config file: ' + self.config_filename) print ' ' + self.left_up + self.hline * width + self.right_up for var, val in self.config.iteritems(): print ' ' + self.vline + ' ' + var.ljust( max_var_len) + ' = ' + val.ljust(max_val_len) + self.vline print ' ' + self.left_down + self.hline * width + self.right_down self.check_config() self.show_coninue() def generate_test_packets(self): print self.term.bold_green(' [+] Generating test packets from "' + self.config['TOPOLOGY_FILE'] + '"') if not self.check_config(): self.show_coninue() return False print p = Popen(['make', '-C', 'cmodule/'], stdout=PIPE) print self.term.bold_green(' [+] Make file') for line in iter(p.stdout.readline, b''): print self.term.bold_magenta(' ' * 5 + line.strip()) print p = Popen( ['cmodule/./generate_test_packets', self.config['TOPOLOGY_FILE']], stdout=PIPE) print self.term.bold_green(' [+] Start to generate test packets') for line in iter(p.stdout.readline, b''): if line.startswith(' '): print self.term.bold_magenta(' ' * 5 + line.strip()) elif line.strip() == '': pass else: print self.term.bold_green(' [+] ' + line.strip()) self.show_coninue() def generate_topology_graph(self): print self.term.bold_green(' [+] Generating topology graph from "' + self.config['TOPOLOGY_FILE'] + '" and "' + self.config['TOPOLOGY_FILE'] + '.testpackets"') if not self.check_config(): self.show_coninue() return False p = Popen([ 'pymodule/generate_topology_graph.py', '-i', self.config['TOPOLOGY_FILE'] ], stdout=PIPE) for line in iter(p.stdout.readline, b''): print self.term.bold_green(' [+] ' + line.rstrip()) self.show_coninue() def start_probing(self): p = Popen(['ryu-manager', 'pymodule/controller.py'], stdout=PIPE, stderr=PIPE) for line in iter(p.stderr.readline, b''): try: if line.startswith('---'): print self.term.bold_magenta(' [+] ' + line.strip()) elif line.startswith(' '): print self.term.bold_magenta(' ' * 5 + line.strip()) else: print self.term.bold_green(' [+] ' + line.strip()) except: pass print self.show_coninue() def show_exit(self): print self.term.bold_red(' [+] Exit...\n') def show_coninue(self): print print self.term.bold_green(' [+] Press any key to continue...') self.getch() def check_config(self): if not os.path.exists(self.config['TOPOLOGY_FILE']): self.print_IOError(self.config['TOPOLOGY_FILE']) return False return True def print_IOError(self, filename): print self.term.bold_red(' [-] IOError: No such file: ' + filename) def getch(self): def input_key(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) key = '' try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) if ord(ch) == 13: return 'enter' elif ord(ch) == 113 or ord(ch) == 81: return 'exit' elif ord(ch) != 27: return False ch = sys.stdin.read(1) if ord(ch) != 91: return False ch = sys.stdin.read(1) if ord(ch) == 65: return 'up' elif ord(ch) == 66: return 'down' #elif ord(ch) == 67: return 'right' #elif ord(ch) == 68: return 'left' else: return False finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) while True: press_key = input_key() if press_key != '': break return press_key