def display_tabled_gads(authors, rendered_gad_months, title, border, width=0): """Display a table of gads per author according to gads_render_func.""" if len(authors) <= 1: width = 1 elif width == 0: gad_width = max( [non_ansi_len(l) for l in rendered_gad_months[1].splitlines()]) author_width = max([non_ansi_len(a) for a in authors]) auto_width = (MAX_WIDTH - 1) / (max(gad_width, author_width) + 3) width = max(1, auto_width) table_data = list( chain.from_iterable( izip( [authors[i:i + width] for i in xrange(0, len(authors), width)], [ rendered_gad_months[i:i + width] for i in xrange(0, len(rendered_gad_months), width) ]))) if border == "ascii": display_table = AsciiTable(table_data) elif border == "single": display_table = SingleTable(table_data) elif border == "double": display_table = DoubleTable(table_data) else: exit(1) display_table.inner_row_border = True display_table.inner_column_border = True display_table.title = title sys.stdout.write(fg(DEFAULT_COLOR)) print display_table.table.encode('utf-8'), attr(0).encode('utf-8')
def test_attributes(): """Test with different attributes.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ] table = AsciiTable(table_data) assert 31 == max(len(r) for r in table.table.splitlines()) assert 31 == table.table_width table.outer_border = False assert 29 == max(len(r) for r in table.table.splitlines()) assert 29 == table.table_width table.inner_column_border = False assert 27 == max(len(r) for r in table.table.splitlines()) assert 27 == table.table_width table.padding_left = 0 assert 24 == max(len(r) for r in table.table.splitlines()) assert 24 == table.table_width table.padding_right = 0 assert 21 == max(len(r) for r in table.table.splitlines()) assert 21 == table.table_width
def option(self): """ Print the options required by the module Usage: options [-h] Options: -h, --help print this help menu """ table_data = [ ["Name", "Current Settings", "Required", "Description"] ] for name, options in self.options.items(): table_data.append([name, options["Current Settings"], options["Require"], options["Description"]]) table = AsciiTable(table_data) table.inner_column_border = False table.inner_footing_row_border = False table.inner_heading_row_border = True table.inner_row_border = False table.outer_border = False print (f'\nModule Options ({self.name}):\n\n{table.table}\n')
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print(''' This module is generate VBA macro loader payload with character substitution. The VBA macro reads real payload from spesific meta-data sections of file. Thus, a great advantage can be obtained against the security countermeasures in the target. Also payload will be triggered when user close the document. Working in this way is especially advantageous in analysis. Because run of macro code for when file opened is marked as malicious by the usage intensity. Using this module, the desired operating system commands can be executed on the target system.''') print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Parameter", "Required", "Value", "Description"], [ "CMD", "Yes", vbaCmdFile, "The file containing the payload command to run" ], [ "FTYPE", "Yes", vbaFileType, "File type of payload. Accepted: word, excel, powerpoint" ], [ "META", "Yes", vbaMetaName, "The metadata name to read payload. Accepted: Comments and Company (case sensetive)" ] ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print(''' This module can be used to generate .EXE loaders and it is coded with C#. It support Meterpreter Reverse HTTP, Reverse HTTPS staged payloads. The payloads generated by this module has two parts. The first part is the real loader code generated with character substitution. The second part is to compile and run the first part at runtime.''') print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Parameter", "Required", "Value", "Description"], [ "PROTO", "Yes", mpbProto, "Listener protocol. Accepted: http or https" ], [ "LHOST", "Yes", mpbLhost, "The local listener hostname or IP address" ], ["LPORT", "Yes", mpbLport, "The local listener port."], [ "ARCH", "Yes", mpbArch, "Architecture of target system. Accepted: x86 or x64" ], [ "SSIZE", "No", mpbSsize, "If you patched Metasploit insert your patch size" ] ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print(''' This module can be used to generate HTA downloader payload with character substitution, obfuscation and encoding. The module has HTML file output and generated HTML file do all things dynamically at the client-side. Thus, a great advantage can be obtained against the security countermeasures in the target. The logic of this module is derived from NCC Group's Demiguise project and added JavaScript encoder. Using this module, the desired operating system commands can be executed on the target system.''') print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Parameter", "Required", "Value", "Description"], [ "FNAME", "Yes", htaDownloadName, "The file name that will appear when the payload is triggered. Ex: SpookFlare" ], [ "CMD", "Yes", htaCmdFile, "The file containing the payload command to run" ] ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def test_attributes(): table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ] table = AsciiTable(table_data) assert 31 == max(len(r) for r in table.table.splitlines()) assert 31 == table.table_width table.outer_border = False assert 29 == max(len(r) for r in table.table.splitlines()) assert 29 == table.table_width table.inner_column_border = False assert 27 == max(len(r) for r in table.table.splitlines()) assert 27 == table.table_width table.padding_left = 0 assert 24 == max(len(r) for r in table.table.splitlines()) assert 24 == table.table_width table.padding_right = 0 assert 21 == max(len(r) for r in table.table.splitlines()) assert 21 == table.table_width
def cmd_assign(self, event, subreddit=None): if subreddit is None or subreddit not in self.config.channels: data = [ ["Subreddit", "Channel"], ] for channel in sorted(self.config.channels): if self.config.channels[channel] is not None: data.append( [channel, self.config.channels[channel]["name"]]) else: data.append([channel, "None"]) table_instance = AsciiTable(data) table_instance.justify_columns[3] = "right" table_instance.inner_column_border = False table_instance.outer_border = False event.msg.reply("```{}```".format(table_instance.table)) else: self.config.channels[subreddit] = { "id": event.channel.id, "name": event.channel.name, 'state': 0 } event.msg.reply( "Assigned /r/{} feed to this channel".format(subreddit)) self.save_settings()
def main_help(): commands = ['database', 'sniffing', 'exploit', 'modelling', 'exit'] description = [ 'Use database mode.', 'Use sniffing mode.', 'Use exploit mode.', 'Use modelling mode.', 'Quit this program' ] table_data = [['Commands', 'Description']] for i in range(len(commands) - 1): table_data.append([commands[i], description[i]]) table = AsciiTable(table_data) table.inner_column_border = False table.inner_footing_row_border = False table.inner_heading_row_border = True table.inner_row_border = False table.outer_border = False msg = f""" Core commands ============= {table.table}\n\n""" return msg
def order_summary(entry, exit, commission): data = [] if 'stop_price' in entry: data.append( ['%(action)s %(quantity)s %(ticker)s STOP $%(stop_price).2f LIMIT' % entry.as_dict(), pf(entry.price), Color('{cyan}%s{/cyan}' % pf(cost(entry, exit, commission)))] ) else: data.append( ['%(action)s %(quantity)s %(ticker)s LIMIT' % entry.as_dict(), pf(entry.price), Color('{cyan}%s{/cyan}' % pf(cost(entry, exit, commission)))] ) data.extend([ ['50% Target', pf(half_target_price(entry, exit)), '+%s' % pf(half_target_profit(entry, exit, commission))], ['Target', pf(exit.target_price), '+%s' % pf(target_profit(entry, exit, commission))], ['Profit', '', Color('{green}+%s{/green}' % pf(total_profit(entry, exit, commission)))], ['Stop loss', pf(exit.stop_price), Color('{hired}-%s{/red}' % pf(risk(entry, exit, commission)))], ['Risk/Reward', '', Color('{%(color)s}%(risk_reward).1f to 1{/%(color)s}' % { 'risk_reward': risk_reward(entry, exit, commission), 'color': 'green' if risk_reward(entry, exit, commission) >= 3 else 'hired' })], ]) table = AsciiTable(data) table.inner_column_border = False print(table.table)
def print(self): """ Print cart contents """ table_data = [] tables_headers = ['Item', ' ', 'Price'] border_row = ["----", "", "-----"] table_data.append(tables_headers) table_data.append(border_row) msg = "" for item in self.contents(): row = [item.product_code, "", "{0:.2f}".format(item.price)] table_data.append(row) if item.discount: discount_row = ["", item.coupon, f"-{item.discount}"] table_data.append(discount_row) total_row = ["", "", "{0:.2f}".format(self.total())] table_data.append(total_row) table = AsciiTable(table_data=table_data) table.inner_column_border = False table.outer_border = False table.inner_heading_row_border = False table.inner_footing_row_border = True table.justify_columns[1] = 'center' # Justify coupons center table.justify_columns[2] = 'right' # Justify prices right msg += table.table return msg
def block_header(cur): """ block portion of header """ block_data = [ [ "Total :", get(cur, "total_adlist_enabled") + "/" + get(cur, "total_adlist"), ], [ "Our Lists :", get(cur, "our_adlist_enabled") + "/" + get(cur, "our_adlist") ], [ "Others :", get(cur, "other_adlist_enabled") + "/" + get(cur, "other_adlist"), ], ] block_table = AsciiTable(block_data) block_table.inner_heading_row_border = False block_table.outer_border = False block_table.inner_row_border = False block_table.inner_column_border = False rows = adlist_top3_by_comment(cur) t3_block_data = [] for row in rows: t3_block_data.append([row[0], row[1]]) t3_block_table = AsciiTable(t3_block_data) t3_block_table.inner_heading_row_border = False t3_block_table.outer_border = False t3_block_table.inner_row_border = False t3_block_table.inner_column_border = False table_data = [ ["Ad/Blocklist Stats", "Top 3 by Comment"], [block_table.table, t3_block_table.table], [], ] table = SingleTable(table_data) table.padding_left = 2 table.outer_border = False utils.info(table.table)
def list(self): """ """ online_mode = self.cloudshell_config_reader.read().online_mode.lower() == "true" template_location = self.cloudshell_config_reader.read().template_location try: standards = self.standards.fetch() if online_mode: try: templates = self.template_retriever.get_templates(standards=standards) except SSLError: raise click.UsageError("Could not retrieve the templates list. Are you offline?") else: templates = self.template_retriever.get_templates(template_location=template_location, standards=standards) except FatalError as err: raise click.UsageError(str(err)) except FeatureUnavailable: if online_mode: templates = self.template_retriever.get_templates(alternative=ALTERNATIVE_TEMPLATES_PATH) else: templates = self.template_retriever.get_templates(template_location=template_location) if not templates: raise click.ClickException("No templates matched the view criteria(gen1/gen2) or " "available templates and standards are not compatible") template_rows = [["Template Name", "CloudShell Ver.", "Description"]] for template in list(templates.values()): template = template[0] cs_ver_txt = str(template.min_cs_ver) + " and up" template_rows.append( [template.name, cs_ver_txt, template.description]) # description is later wrapped based on the size of the console table = AsciiTable(template_rows) table.outer_border = False table.inner_column_border = False max_width = table.column_max_width(2) if max_width <= 0: # verify that the console window is not too small, and if so skip the wrapping logic click.echo(table.table) return row = 1 for template in list(templates.values()): template = template[0] wrapped_string = linesep.join(wrap(template.description, max_width)) table.table_data[row][2] = wrapped_string row += 1 output = table.table click.echo(output) if self.show_info_msg: click.echo(""" As of CloudShell 8.0, CloudShell uses 2nd generation shells, to view the list of 1st generation shells use: shellfoundry list --gen1. For more information, please visit our devguide: https://qualisystems.github.io/devguide/""")
def _create_table(data): """Creates a table from the given data.""" table = AsciiTable(data) table.inner_column_border = False table.inner_row_border = False table.outer_border = False table.inner_heading_row_border = False table.padding_right = 4 return str(table.table)
def do_list(self, line): optionsValues = [ ["ID", "Module", "Description"], ["1", "Linkedin Scraper to CSV", "Generate a CSV File which includes given company employees"], ["2", "Generate Emails", "Generate Email from given pattern"], ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = True print("\n" + optTable.table + "\n")
def print_table(data): table = AsciiTable(data) table.outer_border = False table.inner_column_border = False table.padding_left = 0 table.padding_right = 2 output = table.table print print print output print output.split('\n')[1]
def ps(gravitee_api, deploy_state): """APIs list""" resp = gravitee_api.get_apis() if not resp: click.echo("No Api(s) found ") else: data = [] if deploy_state: data.append(['id', 'Name', 'Synchronized', 'Status']) else: data.append(['id', 'Name', 'Status']) for api_item in resp.json(): if api_item['state'] == 'started': state_color = 'green' else: state_color = 'red' if 'workflow_state' in api_item: state = click.style(api_item['workflow_state'].upper(), fg='blue') + "-" + click.style( api_item['state'].upper(), fg=state_color) else: state = click.style(api_item['state'].upper(), fg=state_color) if deploy_state: response_state = gravitee_api.state_api(api_item['id']) synchronized = click.style("X", fg='yellow') if response_state.json()["is_synchronized"]: synchronized = click.style("V", fg='green') data.append( [api_item['id'], api_item['name'], synchronized, state]) else: if api_item['state'] == 'started': color = 'green' else: color = 'red' data.append([api_item['id'], api_item['name'], state]) table = AsciiTable(data) table.inner_footing_row_border = False table.inner_row_border = False table.inner_column_border = False table.outer_border = False if deploy_state: table.justify_columns[2] = 'center' click.echo(table.table)
def output(buf, dowrap=False): bbuf = [["Bot", "Pack#", "Size", "File"]] + buf t = AsciiTable(bbuf) t.inner_column_border = False t.outer_border = False if dowrap and sys.stdout.isatty(): mw = t.column_max_width(3) for e in bbuf: if len(e[3])>mw: e[3] = "\n".join(wrap(e[3], mw)) print(t.table) sys.stdout.flush()
def echo(self, data): table = AsciiTable(data) table.inner_footing_row_border = False table.inner_row_border = False table.inner_column_border = False table.outer_border = False # print("{}".format(justify_columns)) if not self.style is None: table.justify_columns = self.style click.echo(table.table)
def order_summary(entry, exit, commission): data = [] if 'stop_price' in entry: data.append([ '%(action)s %(quantity)s %(ticker)s STOP $%(stop_price).2f LIMIT' % entry.as_dict(), pf(entry.price), Color('{cyan}%s{/cyan}' % pf(cost(entry, exit, commission))) ]) else: data.append([ '%(action)s %(quantity)s %(ticker)s LIMIT' % entry.as_dict(), pf(entry.price), Color('{cyan}%s{/cyan}' % pf(cost(entry, exit, commission))) ]) data.extend([ [ '50% Target', pf(half_target_price(entry, exit)), '+%s' % pf(half_target_profit(entry, exit, commission)) ], [ 'Target', pf(exit.target_price), '+%s' % pf(target_profit(entry, exit, commission)) ], [ 'Profit', '', Color('{green}+%s{/green}' % pf(total_profit(entry, exit, commission))) ], [ 'Stop loss', pf(exit.stop_price), Color('{hired}-%s{/red}' % pf(risk(entry, exit, commission))) ], [ 'Risk/Reward', '', Color( '{%(color)s}%(risk_reward).1f to 1{/%(color)s}' % { 'risk_reward': risk_reward(entry, exit, commission), 'color': 'green' if risk_reward(entry, exit, commission) >= 3 else 'hired' }) ], ]) table = AsciiTable(data) table.inner_column_border = False print(table.table)
def print(self, data, **kwargs): table = AsciiTable(data) table.inner_footing_row_border = False table.inner_row_border = False table.inner_column_border = False table.outer_border = False if "inner_heading_row_border" in kwargs: table.inner_heading_row_border = kwargs["inner_heading_row_border"] if "style" in kwargs: table.justify_columns = kwargs["style"] click.echo(table.table)
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print("+ MODULE INFO") print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Modules", "Description"], ["Generate CSV File", "Linkedin Username/Email Required"], ["Generate Emails", "Linkedin Email generator"], ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print(''' This module can be used to generate Emails''') print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Set options", "Example"], ["Input", "Default: output.csv"], ["Output", "Default: Emails.txt"], ["Domain", "example.com"], ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def format_table(rows, *, header=None, border=True): """ >>> assert format_table([('a', 'b', 'c'), ('d', 'e', 'f')]) """ table_data = [] if header: table_data.append(list(header)) elif rows: table_data.append([f'#{i}' for i in range(len(rows[0]))]) table_data.extend(rows) table = AsciiTable(table_data) if not border: table.inner_column_border = False table.outer_border = False return table.table
async def _show_fantasy(self, ctx): league = self._find_league(ctx) if league: with open(f"{league}-details.json") as infile: league = json.load(infile) headers = [ "Pos", "Name", "Total", "Race", "Drivers", "Team", "Turbo", "Mega" ] data = [] index = 1 for _, entry in league.items(): try: drivers = ", ".join( [e["short_name"] for e in entry["drivers"]]) team = entry["team"]["short_name"] except KeyError: drivers = "" team = "" data.append([ p.ordinal(index), entry["name"], format_float(entry["score"]), format_float(entry["race_score"]), drivers, team, entry["turbo"] or "???", entry["mega"] or "???" ]) index += 1 for group in grouper(data, 10): table_data = [headers] for row in list(group): if row is not None: table_data.append(row) table_instance = AsciiTable(table_data) table_instance.inner_column_border = False table_instance.outer_border = False table_instance.justify_columns[2] = "center" table_instance.justify_columns[3] = "center" table_instance.justify_columns[6] = "center" content = "```{}```".format(table_instance.table) await ctx.send(content) else: await ctx.send(f"League {league} not found.")
def list(self): try: standards = self.standards.fetch() templates = self.template_retriever.get_templates( standards=standards) except (SSLError, FatalError): raise click.UsageError( 'Could not retrieve the templates list. Are you offline?') except FeatureUnavailable: templates = self.template_retriever.get_templates( alternative=ALTERNATIVE_TEMPLATES_PATH) if not templates: click.echo('No templates matched the criteria') return template_rows = [['Template Name', 'CloudShell Ver.', 'Description']] for template in templates.values(): cs_ver_txt = str(template.min_cs_ver) + " and up" template_rows.append([ template.name, cs_ver_txt, template.description ]) # description is later wrapped based on the size of the console table = AsciiTable(template_rows) table.outer_border = False table.inner_column_border = False max_width = table.column_max_width(2) if max_width <= 0: # verify that the console window is not too small, and if so skip the wrapping logic click.echo(table.table) return row = 1 for template in templates.values(): wrapped_string = linesep.join(wrap(template.description, max_width)) table.table_data[row][2] = wrapped_string row += 1 output = table.table click.echo(output) if self.show_info_msg: click.echo(''' As of CloudShell 8.0, CloudShell uses 2nd generation shells, to view the list of 1st generation shells use: shellfoundry list --gen1. For more information, please visit our devguide: https://qualisystems.github.io/devguide/''' )
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print(''' This module can be used to generate CSV file from given company.''') print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Set options", "Description"], ["Username", "Linkedin Username/Email Required"], ["Password", "Linkedin Passsword Required"], ["URL", "Linkedin Company Page Required, Example : https://www.linkedin.com/search/results/people/?facetCurrentCompany=%5B%22162479%22%5D"], ["Page", "How many pages you want to scrape? Max. 100"], ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def do_list(self, line): optionsValues = [["ID", "Module", "Description"], ["1", "Host Discovery", "test"], ["2", "SMB Share Unpriviliged", "test"], ["3", "SMB Share Privileged", "test"], ["4", "SMB Signing False", "test"], ["5", "SMB Vulnerabilities", "test"], ["6", "SMB Vulnerabilities", "test"], ["7", "SMB Vulnerabilities", "test"], ["8", "SMB Vulnerabilities", "test"], ["9", "SMB Vulnerabilities", "test"], ["10", "SMB Vulnerabilities", "test"]] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = True print("\n" + optTable.table + "\n")
def do_list(self, line): optionsValues = [ ["ID", "Pattern", "Description"], ["1", "(firstname).(surname)@company.com", "Generate Emails given pattern"], ["2", "(surname).(firstname)@company.com", "Generate Emails given pattern"], ["3", "(s).(firstname)@company.com", "(s) is first character of surname"], ["4", "(firstname).(s)@company.com", "(s) is first character of surname"], ["5", "(f).(surname)@company.com", "(f) is first character of firstname"], ["6", "(surname).(f)@company.com", "(f) is first character of firstname"], ["7", "(firstname)(surname)@company.com", "Generate Emails given pattern"], ["8", "(surname)(firstname)@company.com", "Generate Emails given pattern"], ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = True print("\n" + optTable.table + "\n")
def render(table_data): """ Render the given data as an ASCII table. Table data is provided as a list-of-lists. Column names are provided as a list of strings. Returns the string. """ table = AsciiTable(table_data) table.inner_column_border = False table.outer_border = False table.inner_heading_row_border = False table.padding_left = 0 table.padding_right = 2 output = table.table return "\n".join([line.strip() for line in output.split("\n")])
async def events(self, ctx, tag): """Show the point scoring events for a driver (most recent race)""" await ctx.send("Fetching events, please wait") if 'fantasy' not in self.credentials: msg = "Credentials missing." else: f1_cookie = generate_f1_cookie(self.config, self.credentials) if not f1_cookie: msg = "Events fetch failed." elif str(ctx.guild.id) not in self.config['fantasy']: msg = "This server was not found in fantasy settings." else: driver = self._find_driver(tag) if not driver: msg = f"Driver {tag} not found" else: headers = {'X-F1-COOKIE-DATA': f1_cookie} r = requests.get( self.config['urls']['events_url'].format(driver), headers=headers) if r.status_code in [200, 304]: headers = ["Event", "Freq", "Points"] data = [headers] content = json.loads(r.content.decode('utf-8')) events = content['game_periods_scores'][-1] for event in events['events']: data.append([ fix_title_weirdness( event['display_name'].title()), event['freq'], format_float(event['points']) ]) table_instance = AsciiTable(data) table_instance.inner_column_border = False table_instance.outer_border = False table_instance.justify_columns[1] = "center" table_instance.justify_columns[2] = "center" msg = "```{}```".format(table_instance.table) await ctx.send(msg)
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print( ''' This module can be used to host discovery. It uses "nmap" "-T5" option for scanning to target files up top 100 ports.''' ) print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["Parameter", "Required", "Value", "Description"], [ "RHOST", "Yes", m_rhost, "Setting for target(s). Accepted: CIDR formats or a txt file." ] ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def do_info(self, line): print("\n \033[1m\033[94m[*]\033[0m Module Info\033[0m\n") print("+ MODULE INFO") print("\n \033[1m\033[94m[*]\033[0m Module Options\033[0m") optionsValues = [ ["ID", "Pattern", "Description"], [ "1", "(firstname).(surname)@company.com", "Generate Emails given pattern" ], [ "2", "(surname).(firstname)@company.com", "Generate Emails given pattern" ], [ "3", "(s).(firstname)@company.com", "(s) is the first character of surname" ], [ "4", "(firstname).(s)@company.com", "(s) is the first character of surname" ], [ "5", "(f).(surname)@company.com", "(f) is the first character of firstname" ], [ "6", "(surname).(f)@company.com", "(f) is the first character of firstname" ], [ "7", "(firstname)(surname)@company.com", "Generate Emails given pattern" ], [ "8", "(surname)(firstname)@company.com", "Generate Emails given pattern" ], ] optTable = AsciiTable(optionsValues) optTable.outer_border = False optTable.inner_column_border = False optTable.justify_columns[1] = "center" print("\n" + optTable.table + "\n")
def info(self, options): """ Display service status information. Usage: info """ from terminaltables import AsciiTable rows = [] for key, value in self.project.info().iteritems(): rows.append([key + ':', value]) table = AsciiTable(rows) table.outer_border = False table.inner_column_border = False table.inner_heading_row_border = False table.title = 'Dork status information' print table.table
def test_attributes(): """Test table attributes.""" table_data = [ ['Name', 'Color', 'Type'], ['Avocado', 'green', 'nut'], ['Tomato', 'red', 'fruit'], ['Lettuce', 'green', 'vegetable'], ['Watermelon', 'green'] ] table = AsciiTable(table_data) table.justify_columns[0] = 'right' expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | +------------+-------+-----------+ | Avocado | green | nut | | Tomato | red | fruit | | Lettuce | green | vegetable | | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.justify_columns[2] = 'center' expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | +------------+-------+-----------+ | Avocado | green | nut | | Tomato | red | fruit | | Lettuce | green | vegetable | | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.inner_heading_row_border = False expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | | Avocado | green | nut | | Tomato | red | fruit | | Lettuce | green | vegetable | | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.title = 'Foods' table.inner_column_border = False expected = dedent("""\ +Foods-------------------------+ | Name Color Type | | Avocado green nut | | Tomato red fruit | | Lettuce green vegetable | | Watermelon green | +------------------------------+""") assert expected == table.table table.outer_border = False expected = ( ' Name Color Type \n' ' Avocado green nut \n' ' Tomato red fruit \n' ' Lettuce green vegetable \n' ' Watermelon green ' ) assert expected == table.table table.outer_border = True table.inner_row_border = True expected = dedent("""\ +Foods-------------------------+ | Name Color Type | +------------------------------+ | Avocado green nut | +------------------------------+ | Tomato red fruit | +------------------------------+ | Lettuce green vegetable | +------------------------------+ | Watermelon green | +------------------------------+""") assert expected == table.table table.title = False table.inner_column_border = True table.inner_heading_row_border = False # Ignored due to inner_row_border. table.inner_row_border = True expected = dedent("""\ +------------+-------+-----------+ | Name | Color | Type | +------------+-------+-----------+ | Avocado | green | nut | +------------+-------+-----------+ | Tomato | red | fruit | +------------+-------+-----------+ | Lettuce | green | vegetable | +------------+-------+-----------+ | Watermelon | green | | +------------+-------+-----------+""") assert expected == table.table table.outer_border = False expected = ( ' Name | Color | Type \n' '------------+-------+-----------\n' ' Avocado | green | nut \n' '------------+-------+-----------\n' ' Tomato | red | fruit \n' '------------+-------+-----------\n' ' Lettuce | green | vegetable \n' '------------+-------+-----------\n' ' Watermelon | green | ' ) assert expected == table.table
def execute_status(args): status = get_status() # First rows, showing daemon status if status['status'] == 'running': status['status'] = Color('{autogreen}' + '{}'.format(status['status']) + '{/autogreen}') elif status['status'] == 'paused': status['status'] = Color('{autoyellow}' + '{}'.format(status['status']) + '{/autoyellow}') if status['process'] == 'running' or status['process'] == 'paused': status['process'] = Color('{autogreen}' + '{}'.format(status['process']) + '{/autogreen}') print('Daemon: {}\nProcess status: {} \n'.format(status['status'], status['process'])) # Handle queue data data = status['data'] if isinstance(data, str): print(data) elif isinstance(data, dict): # Format incomming data to be compatible with Terminaltables formatted_data = [] formatted_data.append(['Index', 'Status', 'Code', 'Command', 'Path', 'Start', 'End']) for key, entry in sorted(data.items(), key=operator.itemgetter(0)): formatted_data.append( [ '#{}'.format(key), entry['status'], '{}'.format(entry['returncode']), entry['command'], entry['path'], entry['start'], entry['end'] ] ) # Create AsciiTable instance and define style table = AsciiTable(formatted_data) table.outer_border = False table.inner_column_border = False terminal_width = terminal_size() customWidth = table.column_widths # If the text is wider than the actual terminal size, we # compute a new size for the Command and Path column. if (reduce(lambda a, b: a+b, table.column_widths) + 10) > terminal_width[0]: # We have to subtract 14 because of table paddings left_space = math.floor((terminal_width[0] - customWidth[0] - customWidth[1] - customWidth[2] - customWidth[5] - customWidth[6] - 14)/2) if customWidth[3] < left_space: customWidth[4] = 2*left_space - customWidth[3] elif customWidth[4] < left_space: customWidth[3] = 2*left_space - customWidth[4] else: customWidth[3] = left_space customWidth[4] = left_space # Format long strings to match the console width for i, entry in enumerate(table.table_data): for j, string in enumerate(entry): max_width = customWidth[j] wrapped_string = '\n'.join(wrap(string, max_width)) if j == 1: if wrapped_string == 'done' or wrapped_string == 'running' or wrapped_string == 'paused': wrapped_string = Color('{autogreen}' + '{}'.format(wrapped_string) + '{/autogreen}') elif wrapped_string == 'queued': wrapped_string = Color('{autoyellow}' + '{}'.format(wrapped_string) + '{/autoyellow}') elif wrapped_string in ['errored', 'stopping', 'killing']: wrapped_string = Color('{autored}' + '{}'.format(wrapped_string) + '{/autored}') elif j == 2: if wrapped_string == '0' and wrapped_string != 'Code': wrapped_string = Color('{autogreen}' + '{}'.format(wrapped_string) + '{/autogreen}') elif wrapped_string != '0' and wrapped_string != 'Code': wrapped_string = Color('{autored}' + '{}'.format(wrapped_string) + '{/autored}') table.table_data[i][j] = wrapped_string print(table.table) print('')