Exemplo n.º 1
0
 def __setHeader(self):
     t = Terminal()
     h = "\n"
     h += t.bold_yellow("Initializing: ") + t.bold_white(self.name + "\n")
     h += t.bold_yellow("Author: ") + t.bold_white(self.author + "\n")
     h += t.bold_yellow("Version: ") + t.bold_white(self.version + "\n")
     h += t.bold_yellow("Info: ") + t.bold_white(self.info)
     print h
Exemplo n.º 2
0
class Program(object):
    def __init__(self):
        self.term = Terminal()
        self.scriptPath = os.path.dirname(os.path.realpath(__file__))
        self.banner()
        self.arguments = arghandle.ArgHandle()
        hostList = self.arguments.getHostList()
        par = self.arguments.getParDic()

        if hostList != None and len(hostList) > 0:
            contro = controller.Controller(self.term, self.scriptPath,
                                           hostList, par)
            contro.working()
        else:
            print "Parameter format is not correct !\nPlease look for help e.g. -h"

    def banner(self):
        from pyfiglet import Figlet
        f = Figlet(font="slant")
        print self.term.bold_yellow(f.renderText("NSA Check Tool"))
        print self.term.bold_yellow("[version]: beta 1.1")
Exemplo n.º 3
0
class Cli:
    def __init__(self):
        self.data = OrgData.load()
        self.total_points = 0
        self.personal_points = []
        self.terminal = Terminal()

    def run(self):
        self.list_names()
        self.print_prompt(
            "Please enter a person's name and their effort ratings, separated by spaces."
        )
        self.print_prompt(
            "Add a comma to the end of each line to continue to the next person."
        )
        ratings = self.get_ratings()
        self.calculate_points(ratings)
        self.calculate_shares()

    def list_names(self):
        text = 'People: '
        for (i, person) in enumerate(self.data.people):
            text += self.terminal.bold_yellow(person['name'])
            if i < len(self.data.people) - 1:
                text += ' | '
        print(text)

    def get_ratings(self):
        ratings = []
        while True:
            input_line = input('<- ')
            ratings.append(input_line.replace(',', ''))
            if not input_line.endswith(','):
                break
        return ratings

    def calculate_points(self, ratings):
        for rating in ratings:
            frags = rating.split(' ')
            name = frags[0]
            standing = list(
                filter(lambda p: p['name'] == name,
                       self.data.people))[0]['standing']
            multiplier = float(
                list(
                    filter(lambda m: m['name'] == standing,
                           self.data.standings))[0]['rate'])
            points = sum(list(map(int, frags[1:]))) * multiplier
            self.personal_points.append((name, points))
            self.total_points += points

    def calculate_shares(self):
        remainder = 0.0
        for person in self.personal_points:
            share = person[1] / self.total_points * 100
            truncated_share = math.trunc(share)
            remainder += share - truncated_share
            self.print_result(person[0], truncated_share)
        self.print_result('Remainder', remainder)

    def print_prompt(self, prompt):
        print(self.terminal.italic(prompt))

    def print_result(self, label, percentage):
        left = self.terminal.bold_yellow(f"{label}")
        right = self.terminal.bold_green(f"{percentage}%")
        print(left, '->', right)
Exemplo n.º 4
0
config.read('storage.conf')
accName = config.get('storage_account', 'accName')
accKey = config.get('storage_account', 'accKey')
queueName = config.get('storage_account', 'queueName')

# sudo pip install blessings
from azure.storage.queue import QueueService, QueueMessageFormat
from blessings import Terminal
import sys
import time

queue_service = QueueService(account_name=accName, account_key=accKey)
queue_service.decode_function = QueueMessageFormat.text_base64decode

t = Terminal()
print(t.green('Connected to Azure Storage Queue ' + queueName + '...'))
# Get approximate number of messages in queue
queue_metadata = queue_service.get_queue_metadata(queueName)
count = queue_metadata.approximate_message_count
print('Approximate number of messages in queue: ', count, '\n')

while True:
    messages = queue_service.get_messages(queueName)
    if messages:
        # Get the next message
        for message in messages:
            print(t.bold_yellow(message.content))
            queue_service.delete_message(queueName, message.id, message.pop_receipt)
            print(t.blue('-' * 40 + '\n'))
        time.sleep(4)
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
    opts, args = getopt.getopt(sys.argv[1:],"dh:t",["db=","help","table="])
except getopt.GetoptError as err:
    print(err)
    sys.exit(2)

for o, a in opts:
    if o in ("-d","--db"):
        db = a
        conn = sqlite3.connect(db)
        cursor = conn.cursor()
        if o in ("-t","--table"):
            table = a
            cursor.execute("SELECT * FROM "+table+";")
        else:
            clear()
            warning = t.bold_yellow('NO TABLE SPECIFIED.\nDEFAULTING TO default_hashes\n\nPRESS ENTER TO CONTINUE')
            raw_input(warning)
            cursor.execute("SELECT * FROM default_hashes;")
    elif o in ("-h","--help"):
        usage()
        sys.exit()
    else:
        assert False, "unhandled option"

row = cursor.fetchall()
for entry in row:
    v0 = str(entry[0])
    v1 = str(entry[1])
    v2 = str(entry[2])
    v3 = str(entry[3])
    
Exemplo n.º 7
0
class BaseMixin(Cmd):
    """The Mqtt-Pwn Base Command Line Interface Mixin"""

    prompt = '>> '
    ruler = '-'
    intro = banner()

    CMD_CAT_BROKER_OP = 'Broker Related Operations'
    CMD_CAT_VICTIM_OP = 'Victim Related Operations'
    CMD_CAT_GENERAL = 'General Commands'

    variables_choices = ['victim', 'scan']

    def __init__(self):
        """The class initializer"""

        Cmd.__init__(self, startup_script=config.STARTUP_SCRIPT)

        self.aliases.update({'exit': 'quit'})
        self.hidden_commands.extend(
            ['load', 'pyscript', 'set', 'shortcuts', 'alias', 'unalias', 'py'])

        self.current_victim = None
        self.mqtt_client = None
        self.current_scan = None

        self.t = Terminal()

        self.base_prompt = get_prompt(self)
        self.prompt = self.base_prompt

        categorize((
            BaseMixin.do_edit,
            BaseMixin.do_help,
            BaseMixin.do_history,
            BaseMixin.do_quit,
            BaseMixin.do_shell,
        ), BaseMixin.CMD_CAT_GENERAL)

    def print_error(self, text, end='\n', start=''):
        """Prints an error message with colors"""

        self.poutput(start + self.t.bold_red('[-]') + ' ' + self.t.red(text),
                     end=end)

    def print_info(self, text, end='\n', start=''):
        """Prints an information message with colors"""

        self.poutput(start + self.t.bold_yellow('[!]') + ' ' +
                     self.t.yellow(text),
                     end=end)

    def print_ok(self, text, end='\n', start=''):
        """Prints a successful message with colors"""

        self.poutput(start + self.t.bold_green('[+]') + ' ' +
                     self.t.green(text),
                     end=end)

    def print_pairs(self, title, body):
        """Prints a message that contains pairs for data"""

        self.poutput(self.t.bold_white_underline(title))

        for key, value in body.items():
            k = key + ':'
            self.poutput(f' - {self.t.bold(k)} {value}')

    def update_prompt(self):
        """Updates the command prompt"""

        self.prompt = get_prompt(self)