Example #1
0
 def run(self):
     self.console.root.interfaces
     data = [[
         "ESSID", "BSSID", "Channel", "Power", "Enc", "Cipher", "Auth",
         "Password", "Stations"
     ]]
     # parse targets from the state variable
     for essid, target in sorted(self.console.state['TARGETS'].items(),
                                 key=lambda x: x[0]):
         i = self.console.state['INTERFACES']
         c = any(x[1] == essid for x in i.values())
         rows = []
         # for each target, get the value from its associated dictionary
         for i, h in enumerate(data[0]):
             rows.append([""] * len(data[0]))
             v = target[h.lower()]
             if isinstance(v, (tuple, list)):
                 for j in range(len(v) - 1):
                     rows.append([""] * len(data[0]))
             else:
                 v = [v]
             for j, sv in enumerate(v):
                 sv = sv or ""
                 if c:
                     sv = colored(sv, attrs=['bold'])
                 rows[j][i] = sv
         for r in rows:
             if all(v == "" for v in r):
                 continue
             data.append(r)
     if len(data) > 1:
         t = BorderlessTable(data, "Available Targets")
         print_formatted_text(ANSI(t.table))
     else:
         self.logger.warning("No target available yet")
Example #2
0
 def run(self, key, value=None):
     if value is not None:
         obj = list(filter(lambda o: str(o) == value, get_objects()))[0]
     if key == "graph":
         from objgraph import show_refs
         if value is None:
             p = self.console.parent
             show_refs(self.console if p is None else p,
                       refcounts=True,
                       max_depth=3)
         else:
             show_refs(obj, refcounts=True, max_depth=3)
     elif key == "growth":
         from objgraph import get_leaking_objects, show_most_common_types
         show_most_common_types(objects=get_leaking_objects())
     elif key == "info":
         from psutil import Process
         p = Process(os.getpid())
         print_formatted_text(p.memory_info())
     elif key == "leaking":
         from objgraph import get_leaking_objects
         print_formatted_text(get_leaking_objects())
     elif key == "objects":
         data = [["Object", "#References"]]
         for o in get_objects():
             if isinstance(o, (Console, Module)):
                 data.append([str(o), str(getrefcount(o))])
         t = BorderlessTable(data, "Consoles/Modules")
         print_formatted_text(t.table)
     elif key == "refs":
         if value is not None:
             print_formatted_text(getrefcount(obj), ":")
             pprint(get_referrers(obj))
Example #3
0
 def get_help(cls, *levels, **kwargs):
     """ Display commands' help(s), using its metaclass' properties. """
     if len(levels) == 0:
         levels = Command._levels
     if len(levels) == 2 and "general" in levels:
         # process a new dictionary of commands, handling levels in order
         _ = {}
         for l in levels:
             for n, c in cls.commands.get(l, {}).items():
                 if c.level != "general" or all(l not in levels
                                                for l in c.except_levels):
                     _[n] = c
         # then rebuild the dictionary by levels from this dictionary
         levels = {"general": {}, "specific": {}}
         for n, c in _.items():
             levels[["specific", "general"][c.level == "general"]][n] = c
     else:
         _, levels = levels, {}
         for l in _:
             levels[l] = cls.commands[l]
     # now make the help with tables of command name-descriptions by level
     s, i = "", 0
     for l, cmds in sorted(levels.items(), key=lambda x: x[0]):
         if len(cmds) == 0 or l in kwargs.get('except_levels', []):
             continue
         d = [["Command", "Description"]]
         for n, c in sorted(cmds.items(), key=lambda x: x[0]):
             if not hasattr(c, "console") or not c.check():
                 continue
             d.append([n, getattr(c, "description", "")])
         if len(d) > 1:
             t = BorderlessTable(d, "{} commands".format(l.capitalize()))
             s += t.table + "\n"
             i += 1
     return "\n" + s.strip() + "\n" if i > 0 else ""
Example #4
0
 def run(self):
     d = [["Item", "Path", "Size"]]
     p = self.console.app_folder
     d.append(["APP_FOLDER", str(p), human_readable_size(p.size)])
     p = self.workspace
     d.append(["WORKSPACE", str(p), human_readable_size(p.size)])
     t = BorderlessTable(d, "Statistics")
     print_formatted_text(t.table)
Example #5
0
 def __str__(self):
     """ Custom string method. """
     data = [["Name", "Value", "Required", "Description"]]
     l = len(list(self.items(False)))
     for n, d, v, r in sorted(self.items(False), key=lambda x: x[0]):
         if v is None and l > 1:
             continue
         r = ["N", "Y"][r]
         if v == "":
             n, v, r = map(lambda s: colored(s, "red", attrs=['bold']),
                           [n, v, r])
         data.append([n, v, r, d])
     if len(data) == 2:
         return BorderlessTable(data).table
     elif len(data) > 3:
         return BorderlessTable(data,
                                "{} options".format(self.prefix)).table
     return ""
Example #6
0
 def get_info(cls, *fields, show_all=False):
     """ Display entity's metadata and other information.
     
     :param fields:   metadata fields to be output
     :param show_all: also include unselected fields, to be output behind the list of selected fields
     """
     t = ""
     if len(fields) == 0:
         fields = [("name", "description"),
                   ("author", "email", "version", "comments"),
                   ("options", )]
     # make a data table with the given fields and corresponding values
     data, __used = [], []
     _ = lambda s: s.capitalize() + ":"
     for field in fields:
         if not isinstance(field, (list, tuple)):
             field = (field, )
         add_blankline = False
         for f in field:
             try:
                 f, alias = f.split("|", 1)
             except:
                 alias = f
             __used.append(f)
             v = getattr(cls, f, "")
             if v is None or len(v) == 0:
                 continue
             elif isinstance(v, (list, tuple)):
                 data.append([_(alias), v[0]])
                 for i in v[1:]:
                     data.append(["", i])
             else:
                 data.append([_(alias), v])
             add_blankline = True
         if add_blankline:
             data.append(["", ""])
     t = BorderlessTable(data,
                         header=False).table + "\n" if len(data) > 0 else ""
     # add other metadata if relevant
     if show_all:
         unused = set(cls._metadata.keys()) - set(__used)
         if len(unused) > 0:
             t += cls.get_info(*sorted(list(unused)))
     return t.rstrip() + "\n"
Example #7
0
 def run(self, key, value=None):
     if key == "files":
         if value is None:
             data = [["Path", "Size"]]
             p = Path(self.config.option("WORKSPACE").value)
             for f in self.console._files.list:
                 data.append([f, human_readable_size(p.joinpath(f).size)])
             print_formatted_text(
                 BorderlessTable(data, "Files from the workspace"))
         elif self.config.option("TEXT_VIEWER").value:
             self.console._files.view(value)
     elif key == "issues":
         t = Entity.get_issues()
         if len(t) > 0:
             print_formatted_text(t)
     elif key == "modules":
         h = Module.get_help(value)
         if h.strip() != "":
             print_formatted_text(h)
         else:
             self.logger.warning("No module loaded")
     elif key == "options":
         if value is None:
             print_formatted_text(ANSI(str(self.config)))
         else:
             c = Config()
             c[self.config.option(value)] = self.config[value]
             print_formatted_text(ANSI(str(c)))
     elif key == "projects":
         if value is None:
             data = [["Name"]]
             for p in projects(self):
                 data.append([p])
             print_formatted_text(BorderlessTable(data,
                                                  "Existing projects"))
         else:
             print_formatted_text(value)
     elif key == "sessions":
         data = [["ID", "Description"]]
         for i, s in self.console._sessions:
             data.append([str(i), getattr(s, "description", "<undefined>")])
             print_formatted_text(BorderlessTable(data, "Open sessions"))
Example #8
0
 def run(self, text):
     keywords = shlex.split(text)
     data = [["Name", "Path", "Description"]]
     for m in Module.subclasses:
         for k in keywords:
             if m.search(k):
                 data.append([m.name, m.path, m.description])
     if len(data) == 1:
         self.logger.error("No match found")
     else:
         t = BorderlessTable(data, "Matching modules")
         print_formatted_text(t.table)
         n = len(data) - 2
         self.logger.info("{} match{} found".format(n, ["", "es"][n > 0]))
Example #9
0
 def get_help(cls, category=None):
     """ Display command's help, using its metaclass' properties. """
     uncat = {}
     for c, v in cls.modules.items():
         if not isinstance(v, dict):
             uncat[c] = v
     if category is None:
         categories = list(set(cls.modules.keys()) - set(uncat.keys()))
         if len(uncat) > 0:
             categories += ["uncategorized"]
     else:
         categories = [category]
     s, i = "", 0
     for c in categories:
         d = [["Name", "Path", "Enabled", "Description"]]
         for n, m in sorted((flatten_dict(cls.modules.get(c, {})) if c != "uncategorized" else uncat).items(),
                            key=lambda x: x[1].name):
             e = ["N", "Y"][m.enabled]
             d.append([m.name, m.subpath, e, m.description])
         t = BorderlessTable(d, "{} modules".format(c.capitalize()))
         s += t.table + "\n\n"
         i += 1
     return "\n" + s.strip() + "\n" if i > 0 else ""