Ejemplo n.º 1
0
    def setup(self, *,level='info', term=None):
        l = level.lower()
        if l == 'debug':
            self.logLevel = 4
        elif l == 'info':
            self.logLevel = 3
        elif l == 'warning':
            self.logLevel = 2
        elif l == 'error':
            self.logLevel = 1
        elif l == 'critical':
            self.logLevel = 0
        else:
            raise RuntimeError("Invalid log level")
        if term is not None:
            self.isTermE = term
            self.isTermO = term
        else:
            self.isTermE = sys.stderr.isatty()
            self.isTermO = sys.stdout.isatty()

        if self.isTermE:
            self.icos = [stylize("*", fg("white") + bg("red") + attr('bold')),
                         stylize("*", fg("red") + attr('bold')),
                         stylize("*", fg("yellow") + attr('bold')),
                         stylize("*", fg("cyan")),
                         stylize("*", fg("white") + attr('dim'))]
        else:
            self.icos = ["CRIT", "ERR ", "WARN", "INFO", "DBUG"]
Ejemplo n.º 2
0
def printRule(label='', *, ch='-', width=None, color=None):
    if not color:
        color=fg("white") +  attr('dim')
    if not width:
        width = max(1, shutil.get_terminal_size()[0]-4)
    if label:
        w = width - len(label) - 2
        lwidth = w//2 
        rwidth = w-lwidth
        lwidth, rwidth = max(0,lwidth), max(0,rwidth)
        print(stylize(ch*lwidth + " " + label + " " + ch*rwidth, color))
    else:
        print(stylize(ch*width, color))
Ejemplo n.º 3
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l', '--length', type=int)
    parser.add_argument('-c', '--color')
    parser.add_argument('text')
    args = parser.parse_args()

    if args.length is not None:
        length = args.length
    else:
        length = term_length()

    separator = (colored.stylize(DEFAULT_SEPARATOR, colored.fg(args.color))
                 if args.color is not None and colored is not None else
                 DEFAULT_SEPARATOR)
    sys.stdout.write(shorten_string(args.text, length, separator=separator))
Ejemplo n.º 4
0
def colorize(message, format, color=False):
    '''
    Returns the given message in a colorized format
    string with ANSI escape codes for colorized console outputs:
    - message:   the message to be formatted.
    - format:    triple containing format information:
                 (bg-color, fg-color, bf-boolean) supported colors are
                 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
    - color:     boolean determining whether or not the colorization
                 is to be actually performed.
    '''
    if color is False: return message
    (bg, fg, bold) = format
    params = []
    if bold:
        params.append(colored.attr('bold'))
    if bg:
        params.append(colored.bg(bg))
    if fg:
        params.append(colored.fg(fg))

    return colored.stylize(message, set(params))
Ejemplo n.º 5
0
import struct
import time
from datetime import datetime, timezone, timedelta
from uuid import getnode

import colored
from colored import stylize
from halo import Halo

from config import add_stdout
from demo_logging import logger

ok = stylize("✔️ ", colored.fg("green"))
nok = stylize("❌ ", colored.fg("red"))
step = stylize("▶ ", colored.fg("blue"))


def abort():
    logger.error(stylize("Aborting!", colored.fg("red")))
    exit(1)


def wait(t, reason="Waiting..."):
    if add_stdout:
        with Halo(reason, spinner="dots"):
            time.sleep(t)
        logger.info(ok + reason + " done!")
    else:
        logger.info(step + reason)
        time.sleep(t)
Ejemplo n.º 6
0
 def success(cls, message, extras=None):
     """Generate a formatted success message."""
     message = cls.format_message(message, extras)
     styling = colored.fg('green')
     return colored.stylize(MESSAGE_FORMAT.format('✓', message), styling)
Ejemplo n.º 7
0
def model_news_sa_price(ticker, from_date, pagenum):
    '''
    Analyzes the significance of the news headlines sentiments on the stock 
    price movement day over day, by using OLS model
    
    Display the OLS model summary and a plot about sentiment movement vs price 
    movement
    
    Parameters
    ----------
    ticker(string): a ticker symbol
    
    from_date(string): a string that means the start date for a stock's 
    price inquiry, with format like yyyy-mm-dd
    
    pagenum(int): number of pages of news headlines a user wants to extract
    '''
    # load the merged dataset between price and news sentiment
    df = merge_news_sa_price(ticker, from_date, pagenum)

    # if there is price data between the from_date to today, returns -1 and stop
    if type(df) != pd.DataFrame:
        return -1

    # stop if the data size is too little
    if len(df) <= 3:
        print(
            stylize('    Not enough price or news data to display. Try again.',
                    invalid_style))

        return -1

    #pick opening price, Compound score, Polarity scores as x variables
    X = df[['Open', 'Compound', 'Polarity']]

    #pick adj close price as outcome variable
    Y = df['Adj Close']

    X = sm.add_constant(X)  # adding a constant

    #assign OLS model
    model = sm.OLS(Y, X).fit()
    predictions = model.predict(X)

    #print model summary
    print_model = model.summary()
    print(print_model)

    # plot sentiment scores for all tickers
    mpl.rcParams.update(mpl.rcParamsDefault)  #set plot format back to default
    df.index = pd.to_datetime(
        df.index)  #convert index from string to date type
    fig, ax = plt.subplots(figsize=(6, 3))

    #plot actual stock price
    ax.plot(df.index, Y.values, '-', color='royalblue', label='Real Price')

    #plot model stock price
    ax.plot(df.index,
            predictions,
            '--*',
            color='darkorange',
            label='Model Price')
    # format labels and ticks
    ax.set_ylabel('Price').set_size(10)
    ax.set_xlabel('Date').set_size(10)
    ax.tick_params(axis="x", labelsize=8, rotation=0)
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
    ax.tick_params(axis="y", labelsize=8)
    ax.set_title(ticker + ': Real stock price vs OLS Model price').set_size(10)
    plt.legend(loc=2, prop={"size": 8})
    plt.tight_layout()
    plt.show()
Ejemplo n.º 8
0
def color_text(s, color):
    return colored.stylize(s, colored.fg(color))
Ejemplo n.º 9
0
def cprint(text, style, end="\n"):
    print(stylize(text, style), end=end)
Ejemplo n.º 10
0
from colored import fg, bg, attr
import colored
from colored import stylize

color = fg('#C0C0C0') + bg('#00005f')
res = attr('reset')
print(color + "Hello World !!!" + res)

print(color + "|\---/|" + res)
print(color + "| o_o |" + res)
print(color + " \_^_/" + res)

angry = colored.fg("red") + colored.attr("bold")
print(stylize("This is VERY angry text.", angry, colored.attr("underlined")))
        while hp > hl and t < tl:
            ts += inc
            t += inc
            hp = Trv.calc_hp(curr, ts)
        else:
            Trv.add_timestamp(ts)
            Trv.add_traveltime(tt)
    else:
        path = Trv.get_path()
        start = Trv.get_start()
        time = Trv.get_time()

    if i == trials - 1:
        ###########################################################
        print(
            stylize(hotels[start]['name'],
                    attr(1) + fg('#ff9933') + bg('black')))
        ###########################################################
        print(
            stylize(
                df(zip(map(lambda x: places[x]['name'], path),
                       map(lambda x: round(x, 2), time),
                       map(lambda x: round(x, 2), Trv.get_travel())),
                   index=range(1,
                               len(path) + 1),
                   columns=['Location', 'Time Spent', 'Travel Time']),
                attr(21) + bg('black')))
        ###########################################################
        print(
            stylize(f'{ttt:.2f} hrs of Travel Time',
                    fg('#dd7a09') + attr(21) + bg('black')))
map_path(start, path, time)
Ejemplo n.º 12
0
##########################-----------Parameters------------##############################
"""Set up the colors to be used on the display and also what the checpoint borders would look ilke
Also set up the directories. This needs to be changed in the future to makte it easy to set input and output paths"""
tacman_color = colored.fg(226) + colored.attr(1)

# set up some reference directory file locatios
CWD = os.getcwd()
OFD = CWD + "/output"

# If the path does not exists for the output directory, create it
if not os.path.exists(OFD):
    os.makedirs(OFD)

# Print the names of the directories for the user
print(stylize("TACMAN: The common working directory is: " + CWD, tacman_color))
print(stylize("TACMAN: The output directory is: " + OFD, tacman_color))

# Set up the various lists that will be used. The first list is the percentile cutoff that wille be used
percentiles = [1, 2, 4, 10, 20, 100]

#These are a bunch of lists that I will populate.
# the next list will hold the MOODS objects that are created
# the last list has the BIN files that will be created. these might be replaced by objects in later versions
percentile_len = len(percentiles)
percentile_counter = 1
MOODS_OBJ = []
BINS = []
percentile_folder = []
MOODS_len = len(args.moods_hits)
MOODS_counter = 1
Ejemplo n.º 13
0
#!/usr/local/bin/python3
# Made by @swisscoding on Instagram

from colored import stylize, fg
from PIL import Image
import os

# decoration
print(stylize("\n---- | Manipulate colors of a picture | ----\n", fg("red")))


# class
class Manipulate:
    def __init__(self, filename, processes, path):
        self.filename = filename
        self.processes = processes
        self.path = path

    # output magic method
    def __repr__(self):
        self.manipulate_color(self.filename, self.processes, self.path)
        return stylize("\nProcess done >>> manipulated_image.png created\n",
                       fg("red"))

    # methods
    def manipulate_color(self, filename, processes, path):
        for _ in range(processes):
            image = Image.open(filename)
            image = image.convert("RGB")
            pixel_data = image.load()
Ejemplo n.º 14
0
#!/usr/local/bin/python3
# Made by @swisscoding on Instagram

from colored import stylize, fg
import requests
from bs4 import BeautifulSoup

# decoration
print(stylize("\n---- | Get Bitcoin information | ----\n", fg("red")))

# class
class Scraper:
    def __init__(self):
        self.url = "https://www.coindesk.com/price/bitcoin"

    # output magic method
    def __repr__(self):
        data = self.scrape(self.url)
        current_price = stylize(data[0], fg("red"))
        change_in_perc = stylize(data[1], fg("red"))
        market_cap = stylize(data[2], fg("red"))
        ath = stylize(data[3], fg("red"))

        return f"Current Bitcoin price: {current_price}\
        \nChange in % (24H): {change_in_perc}\
        \nMarket capital: {market_cap}\nAll time high: {ath}\n"

    # methods
    def scrape(self, url):
        page = requests.get(url)
        soup = BeautifulSoup(page.content, 'html.parser')
Ejemplo n.º 15
0
 def __repr__(self):
     self.manipulate_color(self.filename, self.processes, self.path)
     return stylize("\nProcess done >>> manipulated_image.png created\n",
                    fg("red"))
Ejemplo n.º 16
0
    tasksIDPendingDelete = userInput.split()
    del tasksIDPendingDelete[0]  #Because the first element will be 'del'
    #tasksIDPendingDelete = list(map(int, tasksIDPendingDelete))
    for taskID in tasksIDPendingDelete:
        db.removeTask(taskID)
    syncSQLtoMemory()
    print(stylize("Task deleted.", colored.fg("green")))


if __name__ == "__main__":
    userInput = ""
    while userInput.lower() != "exit" and userInput.lower() != "quit":
        printMenu()
        printTasks()
        userInput = input(
            stylize("Enter your choice: ", colored.fg("light_yellow_3")))
        if userInput.lower() == "n" or userInput.lower() == "new":
            try:
                handleNewTask()
            except:
                print(
                    "Error 101. Please refer to the developer for immediate fix. Sorry for the inconvenience."
                )
        elif "check" in userInput.lower() or userInput.lower().split(
        )[0] == "c":
            try:
                handleCheckTask(userInput.lower())
            except:
                print(
                    "Error 102. Please refer to the developer for immediate fix. Sorry for the inconvenience."
                )
Ejemplo n.º 17
0
def print_test_header():
    test_group_name = inspect.stack()[0][3]
    print(stylize("\n\t\t\t-- Running {} --\n".format(test_group_name),
                  fg("white")),
          flush=True)
Ejemplo n.º 18
0
 def __str__(self):
     return "\n".join(
         (colored.stylize(" ", colored.bg(player.color.value)
                          ) if player else str(i)) + f": {domino}"
         for i, (player, domino) in enumerate(self.line))
# Load environment variables
load_dotenv()

# Set Orchestrator and Account Details from .env
orchestrator = str(os.getenv("ORCH_URL"))
account = os.getenv("ACCOUNT")
accountKey = os.getenv("ACCOUNT_KEY")

ec_ip_list = []

method = input(
    stylize(
        """Please choose method of MAC address assignments for the Edge Connect(s):

    1. Assign interfaces based on ascending order of MAC addresses
    2. Assign interfaces based on ascending order of Network Adapters in ESXi
    
    """,
        blue_text,
    ))

# Enter IP address of single Edge Connect
enter_more_ec = "y"
while enter_more_ec == "y":
    ec_ip = input(
        stylize("Please enter IP of Edge Connect (e.g. 10.1.30.100): ",
                blue_text))

    if not any(ec["ec_ip"] == ec_ip for ec in ec_ip_list):
        if valid_and_reachable(ec_ip) == True:
            tag = input(
Ejemplo n.º 20
0
                               'a')
            # trainlen = flags.batch_size * flags.evaluate_every
            # when debugging, summary info is needed for tensorboard
            # cur_trainlen = trainlen if model.best_test_acc < 0.530 \
            #     else flags.evaluate_every * flags.batch_size

            # train on trainset
            if flags.debug and summary is not None:
                train_metrics, step, train_summary, _ = \
                    run_set(sess, trainlen, metrics, (global_step, summary, train_op))
            else:
                train_metrics, step, _ = \
                    run_set(sess, trainlen, metrics, (global_step, train_op, ))
            info = model.output_metrics(train_metrics, trainlen)
            info = 'Trainset:' + info
            print((stylize(info, fg('yellow'))))
            print(info, file=output_file)

            if flags.debug:
                for i, s in zip(step, train_summary):
                    train_writer.add_summary(s, i)
                    train_writer.flush()

            # sess.run(traininit)
            # for i in range(100):
            #     input_x, input_mask, input_y, prediction, correct, probs, bert_output, logits =\
            #             sess.run((model.input_x, model.input_mask, model.input_y, model.prediction, model.correct, model.probs, model.bert_output, model.logits))
            #     print(input_x, input_mask, input_y, prediction, correct, bert_output, logits)

            # test on devset
            sess.run(devinit)
Ejemplo n.º 21
0
def pull(machine, from_path, to_path):
    """
    args: <machine> <from_path> <to_path>
    Argument @to_path is optional. If not provided, defaults to '.' (current dir).

    Pulls file(s) from machine

    """
    try:
        # retrieve the secret token from the config folder
        root = str(os.path.expanduser("~"))
        token = os.path.expanduser('~/.vectordash/token')

        if os.path.isfile(token):
            with open(token) as f:
                secret_token = f.readline()

            try:
                # API endpoint for machine information
                full_url = API_URL + str(secret_token)
                r = requests.get(full_url)

                # API connection is successful, retrieve the JSON object
                if r.status_code == 200:
                    data = r.json()

                    # machine provided is one this user has access to
                    if data.get(machine):
                        machine = (data.get(machine))

                        # Machine pem
                        pem = machine['pem']

                        # name for pem key file, formatted to be stored
                        machine_name = (machine['name'].lower()).replace(
                            " ", "")
                        key_file = root + "/.vectordash/" + machine_name + "-key.pem"

                        # create new file ~/.vectordash/<key_file>.pem to write into
                        with open(key_file, "w") as h:
                            h.write(pem)

                        # give key file permissions for scp
                        os.system("chmod 600 " + key_file)

                        # Port, IP address, and user information for pull command
                        port = str(machine['port'])
                        ip = str(machine['ip'])
                        user = str(machine['user'])

                        # execute pull command
                        pull_command = [
                            "scp", "-r", "-P", port, "-i", key_file,
                            user + "@" + ip + ":" + from_path, to_path
                        ]
                        print("Executing " +
                              stylize(" ".join(pull_command), fg("blue")))
                        subprocess.check_call(pull_command)

                    else:
                        print(
                            stylize(machine + " is not a valid machine id.",
                                    fg("red")))
                        print(
                            "Please make sure you are connecting to a valid machine"
                        )

                else:
                    print(
                        stylize(
                            "Could not connect to vectordash API with provided token",
                            fg("red")))

            except json.decoder.JSONDecodeError:
                print(stylize("Invalid token value", fg("red")))

        else:
            # If token is not stored, the command will not execute
            print(
                stylize(
                    "Unable to connect with stored token. Please make sure a valid token is stored.",
                    fg("red")))
            print("Run " + stylize("vectordash secret <token>", fg("blue")))
            print("Your token can be found at " +
                  stylize(str(TOKEN_URL), fg("blue")))

    except TypeError:
        type_err = "There was a problem with pull. Command is of the format "
        cmd_1 = stylize("vectordash pull <id> <from_path> <to_path>",
                        fg("blue"))
        cmd_2 = stylize("vectordash pull <id> <from_path>", fg("blue"))
        print(type_err + cmd_1 + " or " + cmd_2)
Ejemplo n.º 22
0
    def __str__(self):
        str = f"The {self.color.name} {self.rank}."

        return colored.stylize(f"{str}", colored.fg(self.color.name.lower()))
Ejemplo n.º 23
0
def show_yourHand():
    if not user_fullHand:
        print('\n')
        print(stylize('Your hand is empty!', colored.fg("red")))
    print('\n')
    print(*user_fullHand, sep="\n")
Ejemplo n.º 24
0
def launch():
    """
    args: None |
    Runs the client Daemon on the host's machine (IN PROD)

    """
    try:
        print(
            stylize("Launching the Vectordash client on this machine",
                    fg("green")))

        # TODO
        # This command should invoke the client Daemon

        var_folder = os.path.expanduser('/var/')
        var_vd_folder = os.path.expanduser(var_folder + 'vectordash/')
        if not os.path.isdir(var_folder):
            os.mkdir(var_folder)
            print(stylize("Created " + var_folder, fg("green")))

        if not os.path.isdir(var_vd_folder):
            os.mkdir(var_vd_folder)
            print(stylize("Created " + var_vd_folder, fg("green")))

        install_script = os.path.expanduser(var_vd_folder + 'install.sh')
        if not os.path.exists(install_script):
            print(
                stylize(
                    "Please go to vectordash.com to download install script and appropriate files.",
                    fg("red")))
            exit()

        client_py = os.path.expanduser(var_vd_folder + 'client.py')
        sshtunnel_py = os.path.expanduser(var_vd_folder + 'SSHtunnel.py')
        networkingprotocol_py = os.path.expanduser(var_vd_folder +
                                                   'NetworkingProtocol.py')
        specs_py = os.path.expanduser(var_vd_folder + 'specs.py')
        containercontroller_py = os.path.expanduser(var_vd_folder +
                                                    'ContainerController.py')
        if not os.path.exists(client_py) or not os.path.exists(sshtunnel_py) or not os.path.exists(specs_py) or \
                not os.path.exists(networkingprotocol_py) or not os.path.exists(containercontroller_py):
            print(
                stylize(
                    "It seems as though you have not downloaded one or more the following files:",
                    fg("red")))

            print(stylize(client_py, fg("blue")))
            print(stylize(sshtunnel_py, fg("blue")))
            print(stylize(networkingprotocol_py, fg("blue")))
            print(stylize(specs_py, fg("blue")))
            print(stylize(containercontroller_py, fg("blue")))

            print(
                stylize(
                    "Please go to vectordash.com to download them and make sure they are stored in the "
                    "appropriate directory: " + var_vd_folder, fg("red")))
            exit()
        else:
            subprocess.call("python3 " + client_py, shell=True)

    except ValueError as e:
        print(stylize("The following error was thrown: ", fg("red")) + str(e))
        print(
            stylize(
                "The Vectordash client could not be launched. Please make a github pull request with your error.",
                fg("red")))
Ejemplo n.º 25
0
def touch():
    print('\n')

    # Checks if the user has under 7 cards, if else force discards them
    cards_inHand = len(user_fullHand)
    if cards_inHand > 7:
        cardsTo_discard = cards_inHand - 7
        cardsTo_discard = str(cardsTo_discard)
        cards_inHand = str(cards_inHand)
        print(
            'You have ' + cards_inHand +
            ' cards in your hand, your must have 7 or lower at all times. Please discard '
            + cardsTo_discard + '.')
        for x in range(0, int(cardsTo_discard)):
            try:
                discard_card = input('Card: ')
                user_fullHand.remove(discard_card)
                print(stylize("[-1] " + discard_card, colored.fg("red")))
            except ValueError:

                touch()

    # Checks if the user has the needed amount of merges to win the game
    if 'Merge' and 'Merge' and 'Merge' in user_fullHand:
        print('Ye won mate!')
        exit()

    # Main input slot, for command usage and general printage
    touch_1 = input()

    # Check if the COM user has a mentioned suit
    if 'check' in touch_1:
        if 'spades' in touch_1:
            print('You: Do you have any Spades?')
            if 'Spades' in str(com_fullHand):
                print('Com: Yes')
                cards_inHand = len(user_fullHand)
                if cards_inHand >= 7:
                    print(
                        stylize(
                            'Your hand is full, would you like to discard a card? y/n',
                            colored.fg("red")))
                    yesno_ans = str(input())
                    if yesno_ans == 'y':
                        try:
                            discard_card = input('Card: ')
                            user_fullHand.remove(discard_card)
                            print(
                                stylize("[-1] " + discard_card,
                                        colored.fg("red")))
                        except ValueError:
                            print(
                                stylize("You don't own this card!",
                                        colored.fg("red")))
                            touch()
                        new_card = random.choice(nums) + ' of Spades'
                        user_fullHand.append(new_card)
                        print(stylize("[+1] " + new_card, colored.fg("green")))
                    elif yesno_ans == 'n':
                        touch()
                    else:
                        print(stylize('Invalid input!', colored.fg("red")))
                        touch()
                else:
                    new_card = random.choice(nums) + ' of Spades'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] " + new_card, colored.fg("green")))
            else:
                print('Com: No')
        if 'hearts' in touch_1:
            print('You: Do you have any Hearts?')
            if 'Hearts' in str(com_fullHand):
                print('Com: Yes')
                cards_inHand = len(user_fullHand)
                if cards_inHand >= 7:
                    print(
                        stylize(
                            'Your hand is full, would you like to discard a card? y/n',
                            colored.fg("red")))
                    yesno_ans = str(input())
                    if yesno_ans == 'y':
                        try:
                            discard_card = input('Card: ')
                            user_fullHand.remove(discard_card)
                            print(
                                stylize("[-1] " + discard_card,
                                        colored.fg("red")))
                        except ValueError:
                            print(
                                stylize("You don't own this card!",
                                        colored.fg("red")))
                            touch()
                        new_card = random.choice(nums) + ' of Spades'
                        user_fullHand.append(new_card)
                        print(stylize("[+1] " + new_card, colored.fg("green")))
                    elif yesno_ans == 'n':
                        touch()
                    else:
                        print(stylize('Invalid input!', colored.fg("red")))
                        touch()
                else:
                    new_card = random.choice(nums) + ' of Spades'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] " + new_card, colored.fg("green")))
            else:
                print('Com: No')
        if 'diamonds' in touch_1:
            print('You: Do you have any Diamonds?')
            if 'Diamonds' in str(com_fullHand):
                print('Com: Yes')
                cards_inHand = len(user_fullHand)
                if cards_inHand >= 7:
                    print(
                        stylize(
                            'Your hand is full, would you like to discard a card? y/n',
                            colored.fg("red")))
                    yesno_ans = str(input())
                    if yesno_ans == 'y':
                        try:
                            discard_card = input('Card: ')
                            user_fullHand.remove(discard_card)
                            print(
                                stylize("[-1] " + discard_card,
                                        colored.fg("red")))
                        except ValueError:
                            print(
                                stylize("You don't own this card!",
                                        colored.fg("red")))
                            touch()
                        new_card = random.choice(nums) + ' of Diamonds'
                        user_fullHand.append(new_card)
                        print(stylize("[+1] " + new_card, colored.fg("green")))
                    elif yesno_ans == 'n':
                        touch()
                    else:
                        print(stylize('Invalid input!', colored.fg("red")))
                        touch()
                else:
                    new_card = random.choice(nums) + ' of Spades'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] " + new_card, colored.fg("green")))
            else:
                print('Com: No')
        if 'clubs' in touch_1:
            print('You: Do you have any Clubs?')
            if 'Spades' in str(com_fullHand):
                print('Com: Yes')
                cards_inHand = len(user_fullHand)
                if cards_inHand >= 7:
                    print(
                        stylize(
                            'Your hand is full, would you like to discard a card? y/n',
                            colored.fg("red")))
                    yesno_ans = str(input())
                    if yesno_ans == 'y':
                        try:
                            discard_card = input('Card: ')
                            user_fullHand.remove(discard_card)
                            print(
                                stylize("[-1] " + discard_card,
                                        colored.fg("red")))
                        except ValueError:
                            print(
                                stylize("You don't own this card!",
                                        colored.fg("red")))
                            touch()
                        new_card = random.choice(nums) + ' of Spades'
                        user_fullHand.append(new_card)
                        print(stylize("[+1] " + new_card, colored.fg("green")))
                    elif yesno_ans == 'n':
                        touch()
                    else:
                        print(stylize('Invalid input!', colored.fg("red")))
                        touch()
                else:
                    new_card = random.choice(nums) + ' of Spades'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] " + new_card, colored.fg("green")))
            else:
                print(random.com_noResponses)

    # Displays the user's hand
    if 'hand' in touch_1:
        show_yourHand()

    # Discards inputted cards
    if 'discard' in touch_1:
        try:
            card1 = input('Card: ')
            user_fullHand.remove(str(card1))
            print(stylize("[-1] " + card1, colored.fg("red")))
        except ValueError:
            print(stylize("You don't own this card!", colored.fg("red")))

    # Merges two cards of a mentioned suit
    if 'merge' in touch_1:
        card1 = input('Card 1: ')
        try:
            user_fullHand.remove(str(card1))
        except ValueError:
            print(stylize("You don't own this card!", colored.fg("red")))
            touch()
        card2 = input('Card 2: ')
        try:
            user_fullHand.remove(str(card2))
        except ValueError:
            print(stylize("You don't own this card!", colored.fg("red")))
            touch()
        if 'Spades' in card1 and card2:
            if 'Merge' not in card1 and card2:
                print(stylize("[-2] Spades suit", colored.fg("red")))
                new_card = 'Spades Merge'
                user_fullHand.append(new_card)
                print(stylize("[+1] Spades Merge", colored.fg("green")))
        if 'Hearts' in card1 and card2:
            if 'Merge' not in card1 and card2:
                print(stylize("[-2] Hearts suit", colored.fg("red")))
                new_card = 'Hearts Merge'
                user_fullHand.append(new_card)
                print(stylize("[+1] Hearts Merge", colored.fg("green")))
        if 'Diamonds' in card1 and card2:
            if 'Merge' not in card1 and card2:
                print(stylize("[-2] Diamonds suit", colored.fg("red")))
                new_card = 'Diamonds Merge'
                user_fullHand.append(new_card)
                print(stylize("[+1] Diamonds Merge", colored.fg("green")))
        if 'Clubs' in card1 and card2:
            if 'Merge' not in card1 and card2:
                print(stylize("[-2] Clubs suit", colored.fg("red")))
                new_card = 'Clubs Merge'
                user_fullHand.append(new_card)
                print(stylize("[+1] Clubs Merge", colored.fg("green")))
        if 'Merge' in card1 and card2:
            if 'Merge x2' not in card1 and card2:
                if 'Spades' in card1 and card2:
                    print(stylize("[-2] Spades Merge", colored.fg("red")))
                    new_card = 'Spades Merge x2'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] Spades Merge x2", colored.fg("green")))
                if 'Hearts' in card1 and card2:
                    print(stylize("[-2] Hearts Merge", colored.fg("red")))
                    new_card = 'Hearts Merge x2'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] Hearts Merge x2", colored.fg("green")))
                if 'Diamonds' in card1 and card2:
                    print(stylize("[-2] Diamonds Merge", colored.fg("red")))
                    new_card = 'Diamonds Merge x2'
                    user_fullHand.append(new_card)
                    print(
                        stylize("[+1] Diamonds Merge x2", colored.fg("green")))
                if 'Clubs' in card1 and card2:
                    print(stylize("[-2] Clubs Merge", colored.fg("red")))
                    new_card = 'Clubs Merge x2'
                    user_fullHand.append(new_card)
                    print(stylize("[+1] Clubs Merge x2", colored.fg("green")))
        if 'Merge x2' in card1 and card2:
            if 'Spades' in card1 and card2:
                print(stylize("[-2] Spades Merge x2", colored.fg("red")))
                new_card = 'Quad Spades Merge '
                user_fullHand.append(new_card)
                print(stylize("[+1] Quad Spades Merge", colored.fg("green")))
            if 'Hearts' in card1 and card2:
                print(stylize("[-2] Hearts Merge x2", colored.fg("red")))
                new_card = 'Quad Hearts Merge'
                user_fullHand.append(new_card)
                print(stylize("[+1] Quad Hearts Merge", colored.fg("green")))
            if 'Diamonds' in card1 and card2:
                print(stylize("[-2] Diamonds Merge x2", colored.fg("red")))
                new_card = 'Quad Diamonds Merge '
                user_fullHand.append(new_card)
                print(stylize("[+1] Quad Diamonds Merge", colored.fg("green")))
            if 'Clubs' in card1 and card2:
                print(stylize("[-2] Clubs Merge x2", colored.fg("red")))
                new_card = 'Quad Clubs Merge '
                user_fullHand.append(new_card)
                print(stylize("[+1] Quad Clubs Merge", colored.fg("green")))

    # Restarts program after action
    touch()
Ejemplo n.º 26
0
def install():
    """
    Installs the Vectordash hosting client.
    """

    # the prompt we display before installation
    prompt = "This command will begin the Vectordash host installation process.\nPlease note that this will download 15GB+ of " \
             "data and can take upwards of an hour to complete.\nIf prompted with any selections, please press ENTER " \
             "to pick the default values.""\n\nWould you like to begin the host installation process now? " + \
             '%s%s[yes/no]%s ' % (fg('orchid'), attr('bold'), attr('reset'))

    # the JSON file where login credentials are stored
    login_file = '/var/vectordash/login.json'

    try:

        # ensuring the login file exists
        if not os.path.isfile(login_file):
            print("You are not logged in. Please run " +
                  stylize("vdhost login", fg("blue")) + ' to continue.')
            return

        # opening the login file
        with open(login_file, 'r') as f:
            data = json.load(f)

            # grabbing the email and machine secret
            email = data["email"]
            machine_key = data["machine_key"]

        # getting the package
        r = requests.post(VECTORDASH_URL + "machines/getpackage/",
                          data={
                              'email': email,
                              'machine_key': machine_key
                          })

        # if the credentials are invalid, we display an error
        if r.status_code != 200:
            print("Invalid authentication information . Please run " +
                  stylize("vdhost login", fg("blue")) + ' to continue.')
            return

        # writing out the tarball
        open('vectordash-host.tar.gz', 'wb').write(r.content)

        # unzipping the tarball
        command = [
            'sudo', 'tar', '-C', '/var/vectordash/client/', '-xvf',
            'vectordash-host.tar.gz', '--strip-components=1'
        ]

        # calling the unzip command
        subprocess.call(command, stdout=subprocess.PIPE)

        # delete the tarball once the unzip has been completed
        os.remove('vectordash-host.tar.gz')

        # displaying the prompt and asking the user if they want to continue with the installation process
        response = input(prompt)

        if "y" not in response:
            return

        # Running the installation script
        args = ['bash', '/var/vectordash/client/install.sh']
        subprocess.check_call(args)

    except OSError:
        print('Please run this command with sudo:' +
              stylize("sudo vdhost install", fg("blue")))

    except Exception as e:
        print("An unexpected error has occurred: " + stylize(e, fg("red")) +
              str(e))
Ejemplo n.º 27
0
    def misconfigured_containers(self, pods_data, namespacelist):
        print(
            stylize(
                "\n[+] Scanning for Misonfigured containers ......................................\n",
                fg("green_1")))
        print(
            "\nScanning for Misonfigured containers ......................................",
            file=self.file_obj)
        pod_deploy_data_list = [pods_data]  # , deployments_data]
        for pvl_validate_data in pod_deploy_data_list:
            if pvl_validate_data:
                pvl_containers = []
                cpu = []
                memory = []
                livenessprobe = []
                readnessprobe = []
                priorityclassname_in = []
                service_account_in = []
                mounted_in = []
                docker_sock_containers = []
                if pvl_validate_data.get('core') is not None:
                    pvl_validate_data = pvl_validate_data['core']
                elif pvl_validate_data.get('apps') is not None:
                    pvl_validate_data = pvl_validate_data['apps']
                else:
                    pvl_validate_data = {}
                if len(pvl_validate_data) != 0:
                    for pod_data in pvl_validate_data['items']:
                        containers_list, match_signs = PvlContainers(
                        ).containers_check(pod_data)
                        pvl_containers.append({
                            'match_signs': match_signs,
                            'pvl_container': containers_list
                        })
                        # print('privileged containers', str(containers_list))
                        PvlContainers().container_metrics(
                            pod_data, cpu, memory, livenessprobe,
                            readnessprobe, priorityclassname_in,
                            service_account_in, mounted_in,
                            docker_sock_containers)
                else:
                    for namespace in namespacelist:
                        if namespace in pods_data:
                            pods_data = pods_data[namespace]
                            for pod_data in pods_data['items']:
                                containers_list, match_signs = PvlContainers(
                                ).containers_check(pod_data)
                                pvl_containers.append({
                                    'match_signs':
                                    match_signs,
                                    'pvl_container':
                                    containers_list
                                })
                                # print('privileged containers', str(containers_list))
                                PvlContainers().container_metrics(
                                    pod_data, cpu, memory, livenessprobe,
                                    readnessprobe, priorityclassname_in,
                                    service_account_in, mounted_in,
                                    docker_sock_containers)
                scan_status(
                    "       [+] Scanning for Privileged Containers ................................."
                )
                scan_status(
                    "       [+] Scanning for livenessProbe ........................................."
                )
                scan_status(
                    "       [+] Scanning for readinessProbe ........................................"
                )
                scan_status(
                    "       [+] Scanning for CPU Limit ............................................."
                )
                scan_status(
                    "       [+] Scanning for Memory Limit .........................................."
                )
                scan_status(
                    "       [+] Scanning for Priorityclassname ....................................."
                )
                scan_status(
                    "       [+] Scanning for ServiceAccount Mount .................................."
                )
                scan_status(
                    "       [+] Scanning for Secrets Mounted ......................................."
                )
                scan_status(
                    "       [+] Scanning for docker Socket Mount ..................................."
                )
                print(
                    "       [+] Scanning for Privileged Containers .................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for livenessProbe .........................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for readinessProbe ........................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for CPU Limit .............................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for Memory Limit ..........................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for Priorityclassname .....................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for ServiceAccount Mount ..................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for Secrets Mounted .......................................",
                    file=self.file_obj)
                print(
                    "       [+] Scanning for docker Socket Mount .................................\n",
                    file=self.file_obj)

                print_msg_box('######## Privileged containers ########',
                              file_obj=self.file_obj)
                pvlc_list = []
                for pvlc_data in pvl_containers:
                    pvl_container = pvlc_data.get('pvl_container')
                    if pvl_container:
                        match_sighns = pvlc_data.get('match_signs')
                        for pvlc in pvl_container:
                            if not pvlc in pvlc_list:
                                print(
                                    "{pvlc} is configured with {match_sighns}".
                                    format(pvlc=pvlc,
                                           match_sighns=str(match_sighns)),
                                    file=self.file_obj)
                                pvlc_list.append(pvlc)

                print_msg_box(
                    '######## livenessprobe not set in below containers ########',
                    file_obj=self.file_obj)
                for liveness_container in list(set(livenessprobe)):
                    print(liveness_container, file=self.file_obj)

                print_msg_box(
                    '######## readinessprobe not set in below containers ########',
                    file_obj=self.file_obj)
                for readiness_container in list(set(readnessprobe)):
                    print(readiness_container, file=self.file_obj)

                print_msg_box(
                    '######## CPU Limit not set below containers ########',
                    file_obj=self.file_obj)
                for cpu_container in list(set(cpu)):
                    print(cpu_container, file=self.file_obj)

                print_msg_box(
                    '######## Memory Limit not set in below containers ########',
                    file_obj=self.file_obj)
                for memory_container in list(set(memory)):
                    print(memory_container, file=self.file_obj)

                print_msg_box(
                    '######## Priorityclassname not set in below containers ########',
                    file_obj=self.file_obj)
                for pcl_container in list(set(priorityclassname_in)):
                    print(pcl_container, file=self.file_obj)

                print_msg_box(
                    '######## Service account mounted in below containers ########',
                    file_obj=self.file_obj)
                for sac_container in list(set(service_account_in)):
                    print(sac_container, file=self.file_obj)

                print_msg_box(
                    '######## Secret mounted in below containers ########',
                    file_obj=self.file_obj)
                for mounted in list(set(mounted_in)):
                    print(mounted, file=self.file_obj)

                print_msg_box(
                    '######## Docker Socket mounted in below containers ########',
                    file_obj=self.file_obj)
                for docker_socket in list(set(docker_sock_containers)):
                    print(docker_socket, file=self.file_obj)

                print(
                    stylize(
                        "\n[+] Identified Misonfigured containers ........................................\n",
                        fg("green_1")))
                print(
                    "[+] Identified Misonfigured containers ........................................",
                    file=self.file_obj)
                if pvl_containers:
                    resource_available("Containers with High Privileges",
                                       self.file_obj)
                if livenessprobe:
                    resource_available(
                        "Containers with missing liveness Probe",
                        self.file_obj)
                if readnessprobe:
                    resource_available(
                        "Containers with missing readiness Probe",
                        self.file_obj)
                if cpu:
                    resource_available("Containers with missing CPU Limit",
                                       self.file_obj)
                if memory:
                    resource_available("Containers with missing Memory Limit",
                                       self.file_obj)
                if priorityclassname_in:
                    resource_available(
                        "Containers with missing Priorityclassname",
                        self.file_obj)
                if service_account_in:
                    resource_available(
                        "Containers with ServiceAccount Mounted",
                        self.file_obj)
                if mounted_in:
                    resource_available("Conatiners with Secrets Mounted",
                                       self.file_obj)
                if docker_sock_containers:
                    resource_available("Containers with Docker socket Mount",
                                       self.file_obj)
            else:
                print("\nPod or deployment data not available",
                      file=self.file_obj)
Ejemplo n.º 28
0
def plot_news_sa_price(ticker, from_date, pagenum):
    '''
    Plots a stock's news headlines' sentiment movement vs price movement
    
    Parameters
    ----------
    ticker(string): a ticker symbol
    
    from_date(string): a string that means the start date for a stock's 
    price inquiry, with format like yyyy-mm-dd
    
    pagenum(int): number of pages of news headlines a user wants to extract
    '''
    # get df with merged news sentiment and price history
    df_price_news = merge_news_sa_price(ticker, from_date, pagenum)

    #if there is no data between from_date and today, return -1 and stop.
    if type(df_price_news) != pd.DataFrame:
        return -1

    # returns -1 if data size is too small
    if len(df_price_news) <= 3:
        print(
            stylize('    Not enough price or news data to display. Try again.',
                    invalid_style))
        return -1

    # convert index from text to date type
    df_price_news.index = pd.to_datetime(df_price_news.index)

    # plot price change in % vs Polarity score
    x_date = df_price_news.index
    y_price = df_price_news['PriceChg']
    y_score = df_price_news['Polarity']

    # create graph
    mpl.rcParams.update(mpl.rcParamsDefault)
    fig = plt.figure(figsize=(6, 3))
    ax = fig.add_subplot(111)

    # plot price change percentage over time
    ax.set_xlabel('Date').set_size(10)
    ax.set_ylabel('Price Chg %', color='brown')
    lns1 = ax.plot(x_date, y_price, color='brown', label='Price Chg %')

    # plot polarity score over time on a secondary y-axis
    ax2 = ax.twinx()
    lns2 = ax2.plot(x_date, y_score, color='royalblue', label='Polarity Score')
    ax2.set_ylabel('Polarity Score', color='royalblue')

    # set axis limit
    ax.set_ylim(min(y_price) * 1.1, max(y_price) * 1.1)
    ax2.set_ylim(min(y_score) * 1.1, max(y_score) * 1.1)
    ax.set_xlim(min(x_date), max(x_date))

    # format labels and ticks
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
    ax.set_title('Price Change% vs News Sentiment Score').set_size(10)
    ax.tick_params(axis="x", labelsize=8)
    ax.tick_params(axis="y", labelsize=8)
    ax2.tick_params(axis="y", labelsize=8)

    # merge legends
    lns = lns1 + lns2
    labs = [l.get_label() for l in lns]
    ax.legend(lns, labs, loc=2, prop={'size': 8})
    fig.tight_layout()
    plt.show()
Ejemplo n.º 29
0
def colorit(msg, style):
    """ color the text given to the specified style """
    return stylize(msg, style)
Ejemplo n.º 30
0
def main():
    banner = '''
   ________              __      ____
  / ____/ /_  ___  _____/ /__   / __ \___  ____
 / /   / __ \/ _ \/ ___/ //_/  / /_/ / _ \/ __ \ 
/ /___/ / / /  __/ /__/ ,<    / _, _/  __/ /_/ /
\____/_/ /_/\___/\___/_/|_|  /_/ |_|\___/ .___/
                                       /_/
'''

    print(Fore.CYAN + banner + Style.RESET_ALL)
    print("Check IP and Domain Reputation")

    parser = argparse.ArgumentParser(
        description='Check IP or Domain Reputation',
        formatter_class=argparse.RawTextHelpFormatter,
        epilog='''
    Options
    --------------------
    freegeoip [freegeoip.live]  - free/opensource geolocation service     
    virustotal [virustotal.com] - online multi-antivirus scan engine            
    
    * NOTE: 
    Use of the VirusTotal option requires an API key.  
    The service is "free" to use, however you must register 
    for an account to receive an API key.''')

    optional = parser._action_groups.pop()
    required = parser.add_argument_group('required arguments')
    required.add_argument('query', help='query ip address or domain')
    optional.add_argument('--log',
                          action='store_true',
                          help='log results to file')
    optional.add_argument('--vt', action='store_true', help='check virustotal')

    group = optional.add_mutually_exclusive_group()
    group.add_argument('--fg',
                       action='store_true',
                       help='use freegeoip for geolocation')  # nopep8
    group.add_argument(
        '--mx',
        nargs='+',
        metavar='FILE',
        help='geolocate multiple ip addresses or domains')  # nopep8

    parser._action_groups.append(optional)
    args = parser.parse_args()
    QRY = args.query

    if len(sys.argv[1:]) == 0:
        parser.print_help()
        parser.exit()

    # Initialize utilities
    workers = Workers(QRY)

    print("\n" + Fore.GREEN + "[+] Running checks..." + Style.RESET_ALL)

    if args.log:
        if not os.path.exists('logfile'):
            os.mkdir('logfile')
        dt_stamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
        file_log = logging.FileHandler(f"logfile/logfile_{dt_stamp}.txt")
        file_log.setFormatter(
            logging.Formatter("[%(asctime)s %(levelname)s] %(message)s",
                              datefmt="%m/%d/%Y %I:%M:%S"))  # nopep8
        logger.addHandler(file_log)

    if args.fg:
        map_free_geo(QRY)

    if args.mx:
        print(
            colored.stylize("\n--[ Processing Geolocation Map ]--",
                            colored.attr("bold")))  # nopep8
        multi_map(input_file=args.mx[0])
        print(colored.stylize("\n--[ GeoIP Map File ]--",
                              colored.attr("bold")))  # nopep8
        try:
            multi_map_file = Path('multi_map.html').resolve(strict=True)
        except FileNotFoundError:
            logger.info(
                "[-] Geolocation map file was not created or does not exist."
            )  # nopep8
        else:
            logger.info(f"[>] Geolocation map file saved to: {multi_map_file}")
        sys.exit(1)

    if args.vt:
        print(
            colored.stylize("\n--[ VirusTotal Detections ]--",
                            colored.attr("bold")))  # nopep8
        if not config['VIRUS-TOTAL']['api_key']:
            logger.warning(
                "Please add VirusTotal API key to the 'settings.yml' file, or add it below"
            )  # nopep8
            user_vt_key = input("Enter key: ")
            config['VIRUS-TOTAL']['api_key'] = user_vt_key

            with open('settings.yml', 'w') as output:
                yaml.dump(config, output)

        api_key = config['VIRUS-TOTAL']['api_key']
        virustotal = VirusTotalChk(api_key)
        if DOMAIN.findall(QRY):
            virustotal.vt_run('domains', QRY)
        elif IP.findall(QRY):
            virustotal.vt_run('ip_addresses', QRY)
        elif URL.findall(QRY):
            virustotal.vt_run('urls', QRY)
        else:
            virustotal.vt_run('files', QRY)
            print(
                colored.stylize("\n--[ Team Cymru Detection ]--",
                                colored.attr("bold")))  # nopep8
            workers.tc_query(qry=QRY)
            sys.exit("\n")

    if DOMAIN.findall(QRY) and not EMAIL.findall(QRY):
        print(
            colored.stylize("\n--[ Querying Domain Blacklists ]--",
                            colored.attr("bold")))  # nopep8
        workers.spamhaus_dbl_worker()
        workers.blacklist_dbl_worker()
        print(
            colored.stylize(f"\n--[ WHOIS for {QRY} ]--",
                            colored.attr("bold")))  # nopep8
        workers.whois_query(QRY)

    elif IP.findall(QRY):
        # Check if cloudflare ip
        print(
            colored.stylize("\n--[ Using Cloudflare? ]--",
                            colored.attr("bold")))  # nopep8
        if workers.cflare_results(QRY):
            logger.info("Cloudflare IP: Yes")
        else:
            logger.info("Cloudflare IP: No")

        print(
            colored.stylize("\n--[ Querying DNSBL Lists ]--",
                            colored.attr("bold")))  # nopep8
        workers.dnsbl_mapper()
        workers.spamhaus_ipbl_worker()
        print(
            colored.stylize("\n--[ Querying IP Blacklists ]--",
                            colored.attr("bold")))  # nopep8
        workers.blacklist_ipbl_worker()

    elif NET.findall(QRY):
        print(
            colored.stylize("\n--[ Querying NetBlock Blacklists ]--",
                            colored.attr("bold")))  # nopep8
        workers.blacklist_netblock_worker()

    else:
        print(Fore.YELLOW +
              "[!] Please enter a valid query -- Domain or IP address" +
              Style.RESET_ALL)  # nopep8
        print("=" * 60, "\n")
        parser.print_help()
        parser.exit()

    # ---[ Results output ]-------------------------------
    print(colored.stylize("\n--[ Results ]--", colored.attr("bold")))
    TOTALS = workers.DNSBL_MATCHES + workers.BL_MATCHES
    BL_TOTALS = workers.BL_MATCHES
    if TOTALS == 0:
        logger.info(f"[-] {QRY} is not listed in any Blacklists\n")
    else:
        _QRY = Fore.YELLOW + QRY + Style.BRIGHT + Style.RESET_ALL
        _DNSBL_MATCHES = Fore.WHITE + Back.RED + str(
            workers.DNSBL_MATCHES) + Style.BRIGHT + Style.RESET_ALL  # nopep8
        _BL_TOTALS = Fore.WHITE + Back.RED + str(
            BL_TOTALS) + Style.BRIGHT + Style.RESET_ALL  # nopep8
        logger.info(
            f"[>] {_QRY} is listed in {_DNSBL_MATCHES} DNSBL lists and {_BL_TOTALS} Blacklists\n"
        )  # nopep8

    # ---[ Geo Map output ]-------------------------------
    if args.fg or args.mx:
        print(colored.stylize("--[ GeoIP Map File ]--",
                              colored.attr("bold")))  # nopep8
        time_format = "%d %B %Y %H:%M:%S"
        try:
            ip_map_file = prog_root.joinpath('geomap/ip_map.html').resolve(
                strict=True)  # nopep8
        except FileNotFoundError:
            logger.warning(
                "[-] Geolocation map file was not created/does not exist.\n"
            )  # nopep8
        else:
            ip_map_timestamp = datetime.fromtimestamp(
                os.path.getctime(ip_map_file))  # nopep8
            logger.info(
                f"[>] Geolocation map file created: {ip_map_file} [{ip_map_timestamp.strftime(time_format)}]\n"
            )  # nopep8
Ejemplo n.º 31
0
#!/usr/local/bin/python3
# Made by @swisscoding on Instagram
# Follow now and share!

from colored import stylize, fg

# decoration
print(stylize("\n---- | Convert time units | ----\n", fg("red")))

# options
print(stylize("Options:", fg("green")))
print(
    "> 'd' for days\n> 'h' for hours\n> 'm' for minutes\n> 's' for seconds\n")

# user interaction
user_input = float(input("Enter your value: "))
input_unit = input("What unit is your input?\n").lower()
output_unit = input("What unit do you want for output?\n").lower()

print(stylize("\n------------------------------------", fg("red")))

if input_unit == "d":
    if output_unit == "h":
        print(f"\n{user_input} day/s in hours: {round(user_input*24, 2)}\n")
    if output_unit == "m":
        print(
            f"\n{user_input} day/s in minutes: {round(user_input*24*60, 2)}\n")
    if output_unit == "s":
        print(
            f"\n{user_input} day/s in seconds: {round(user_input*24*60*60, 2)}\n"
        )
Ejemplo n.º 32
0
 def failure(cls, message, extras=None):
     """Generate a formatted failure message."""
     message = cls.format_message(message, extras)
     styling = colored.fg('red') + colored.attr('bold')
     return colored.stylize(MESSAGE_FORMAT.format('✘', message), styling)
Ejemplo n.º 33
0
 def get_red_message(message):
     return colored.stylize(message,
                            colored.fg("red") + colored.attr("bold"))
Ejemplo n.º 34
0
    def pod_security_polocies(self, psp_data, roles_data, roles_bindings_data,
                              clusterroles_data, clusterrolebindings_data,
                              namespacelist):
        psp_privilized = None
        print(
            "\n[+] Validating Pod Security Policies..................................",
            file=self.file_obj)
        psp = PspRole()
        if psp_data.get('policy') is not None:
            psp_privilized, psp_restricted = psp.validate_psp_rule(
                psp_data.get('policy'))
            if (roles_data.get('rbac') and roles_bindings_data.get('rbac')
                    and clusterroles_data.get('rbac')
                    and clusterrolebindings_data.get('rbac')) is not None:
                psp_roles_data = psp.validate_psp_role(
                    roles_data['rbac'], roles_bindings_data['rbac'],
                    clusterroles_data['rbac'],
                    clusterrolebindings_data['rbac'])
                psp.psp_update_data(psp_privilized, psp_restricted,
                                    psp_roles_data)
            print(
                stylize(
                    "\n[+] Identified Misconfigured Pod Security Policies ...........................\n",
                    fg("green_1")))
            if psp_privilized:
                resource_available("Privilized Pod Security Policies",
                                   self.file_obj)
            if psp_restricted:
                resource_available("Restricted Pod Security Policies",
                                   self.file_obj)
        else:
            for namespace in namespacelist:
                psp_privilized, psp_restricted = psp.validate_psp_rule(
                    psp_data.get(namespace))
                if (roles_data.get(namespace)
                        and roles_bindings_data.get(namespace)
                        and clusterroles_data.get(namespace) and
                        clusterrolebindings_data.get(namespace)) is not None:
                    psp_roles_data = psp.validate_psp_role(
                        roles_data[namespace], roles_bindings_data[namespace],
                        clusterroles_data[namespace],
                        clusterrolebindings_data[namespace])
                    psp.psp_update_data(psp_privilized, psp_restricted,
                                        psp_roles_data)
                print(
                    stylize(
                        "\n[+] Identified Misconfigured Pod Security Policies ...........................\n",
                        fg("green_1")))
                print(
                    "\n[+] Identified Misconfigured Pod Security Policies ...........................\n",
                    file=self.file_obj)
                if psp_privilized:
                    resource_available(
                        namespace + " Privilized Pod Security Policies",
                        self.file_obj)
                if psp_restricted:
                    resource_available(
                        namespace + " Restricted Pod Security Policies",
                        self.file_obj)
        print_msg_box('######## Privilized PSPs ########',
                      file_obj=self.file_obj)
        if psp_privilized:
            psp_container_list = []
            for psp_container, psp_data in psp_privilized.items():
                match_signs = psp_data.get('matched_signs')
                ser_acn_details = psp_data.get('service_acount')
                if ser_acn_details is None:
                    if not psp_container in psp_container_list:
                        print(
                            "{psp_container} has privilized rules {match_signs}"
                            .format(psp_container=psp_container,
                                    match_signs=str(match_signs)),
                            file=self.file_obj)
                        psp_container_list.append(psp_container)
            print(file=self.file_obj)
            psp_container_list = []
            for psp_container, psp_data in psp_privilized.items():
                match_signs = psp_data.get('matched_signs')
                ser_acn_details = psp_data.get('service_acount')
                if ser_acn_details:
                    kind = ser_acn_details.get('kind')
                    name = ser_acn_details.get('name')

                    if not psp_container in psp_container_list:
                        print(
                            "{psp_container} lets {kind} {name} use {match_signs}"
                            .format(psp_container=psp_container,
                                    kind=kind,
                                    name=name,
                                    match_signs=str(match_signs)),
                            file=self.file_obj)
                        psp_container_list.append(psp_container)
Ejemplo n.º 35
0
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import sys
import re
from argparse import ArgumentParser
import requests
import base64, xml.etree.ElementTree
import urllib
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning

Indra = pyfiglet.figlet_format("Paramter Finder", font='poison')
print("\n")
Xnuvers = pyfiglet.figlet_format("By Xnuvers007", font='3-d')

print(stylize(Indra, colored.fg("sky_blue_2")))
print(stylize(Xnuvers, colored.fg("sky_blue_1")))

parser = ArgumentParser()
parser.add_argument("-H", "--host", dest="host", metavar="HOST", required=True)
parser.add_argument("-t", "--threads", dest="threads", metavar="THREADS")
parser.add_argument("-c","--cookies", nargs='+', dest="cookies", metavar="COOKIES")
parser.add_argument("-v","--verbose", dest="verbose", action='store_true')
parser.add_argument("-p","--payload", dest="payload")
parser.add_argument("-b", "--burp",dest="burp",help="provide a burp file", action="store")

args = parser.parse_args()

validateHost_regex="^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$"
validateHostIpWithPort_regex="^https?:\/\/(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])?:?[0-9]+$"
Ejemplo n.º 36
0
def main():

    now = date.today()

    cli = argparse.ArgumentParser()

    cli.add_argument(
        '-i',
        '--InputFolder',
        help=
        "Folder containing paired fq, fq.gz, fastq, and fastq.gz files. Program will recursively find paired reads",
        required=True)
    cli.add_argument('-r',
                     '--Reference',
                     help="Host Reference fasta or fasta.gz file",
                     required=True)
    cli.add_argument(
        '-o',
        '--OutputFolder',
        help=f"Output Folder. Default is ~/dehost_output/dehost_{now}",
        required=False,
        default=f"~/dehost_output/dehost_{now}")
    cli.add_argument(
        '--LargeReference',
        help=
        "Use this option if your reference file is greater than 4 Gigabases",
        required=False,
        action='store_true')
    cli.add_argument(
        '-t',
        '--threads',
        help="Number of threads. More is faster if your computer supports it",
        type=int,
        required=False,
        default=4)

    args = cli.parse_args()

    for_files = sorted([
        f for f in glob.glob(args.InputFolder + "/**", recursive=True)
        if re.search(r'(.*)_(R|)1(.*)\.((fastq|fq)(|\.gz))$', f)
    ])
    rev_files = sorted([
        f for f in glob.glob(args.InputFolder + "/**", recursive=True)
        if re.search(r'(.*)_(R|)2(.*)\.((fastq|fq)(|\.gz))$', f)
    ])
    OutputFolder = os.path.expanduser(args.OutputFolder)
    os.system(f"mkdir -p {OutputFolder}")
    f = open(f"{OutputFolder}/cmd.log", 'w+')

    if (len(for_files) != len(rev_files)):
        print(
            stylize(f"You have unequal numbers of forward and reverse files!",
                    fg("red") + attr("bold")))
        raise Exception(
            stylize(
                f"You have {len(for_files)} forward files and {len(rev_files)} reverse files!",
                fg("red") + attr("bold")))

    for i in range(0, len(for_files)):

        #print(for_files[i])
        #print(rev_files[i])

        base = os.path.splitext(os.path.basename(for_files[i]))[0]
        base = os.path.splitext(base)[0]
        #print(base)
        os.system(f"mkdir -p {OutputFolder}")
        if args.LargeReference:
            minimap2_cmd = f"minimap2 -ax sr {args.Reference} {for_files[i]} {rev_files[i]} -t {args.threads} --split-prefix index_name > {OutputFolder}/{base}.sam"
        else:
            minimap2_cmd = f"minimap2 -ax sr {args.Reference} {for_files[i]} {rev_files[i]} -t {args.threads} > {OutputFolder}/{base}.sam"

        f.write(minimap2_cmd + '\n')
        os.system(minimap2_cmd)
        samtools_cmd1 = f"samtools view -u -f 4 {OutputFolder}/{base}.sam > {OutputFolder}/{base}_filtered.sam"
        f.write(samtools_cmd1 + '\n')
        os.system(samtools_cmd1)
        samtools_cmd2 = f"samtools bam2fq {OutputFolder}/{base}_filtered.sam > {OutputFolder}/{base}_filtered.fastq"
        f.write(samtools_cmd2 + '\n')
        os.system(samtools_cmd2)

        split1_cmd = f"cat {OutputFolder}/{base}_filtered.fastq | grep '^@.*/1$' -A 3 --no-group-separator >{OutputFolder}/{base}_filtered_r1.fastq"
        split2_cmd = f"cat {OutputFolder}/{base}_filtered.fastq | grep '^@.*/2$' -A 3 --no-group-separator >{OutputFolder}/{base}_filtered_r2.fastq"

        os.system(split1_cmd)
        f.write(split1_cmd + '\n')
        os.system(split2_cmd)
        f.write(split2_cmd + '\n')

        delete_cmd1 = f"rm {OutputFolder}/{base}.sam"
        os.system(delete_cmd1)
        f.write(delete_cmd1 + '\n')
        delete_cmd2 = f"rm {OutputFolder}/{base}_filtered.sam"
        f.write(delete_cmd2 + '\n')
        os.system(delete_cmd2)
        delete_cmd3 = f"rm {OutputFolder}/{base}_filtered.fastq"
        os.system(delete_cmd3)
        f.write(delete_cmd3 + '\n')

        print("progress: {}/{}".format(i + 1, len(for_files)))

    f.close()
Ejemplo n.º 37
0
                f = open('data.json', 'w+')
                f.write(c)
                f.close()
                with open('data.json', 'r+') as lst:
                    serialnumber = json.load(lst)
                    a = [serialnumber['SerialNumber'][12], serialnumber['SerialNumber'][13],
                         serialnumber['SerialNumber'][14],
                         serialnumber['SerialNumber'][15], serialnumber['SerialNumber'][16],
                         serialnumber['SerialNumber'][17],
                         serialnumber['SerialNumber'][18], serialnumber['SerialNumber'][19]]
                    b, c, d, e, f, g, h, i = a
                    password = (b + c + d + e + f + g + h + i)
                    print(stylize(f"[+] {ip} (DG8045):", colored.fg('green')))
                    print(stylize(f"Username: admin \nPassword: {password}", colored.fg('green')))
                    print("-------------------------------------")
            else:
                print(stylize(f"[-] {ip} is not DG8045 OR HG633 ", colored.fg('red')))
                print("-------------------------------------")
        except ConnectionError:
            print(stylize(f'[-] {ip} Maybe is Down',colored.fg('red')))
            print("-------------------------------------")


print(stylize(logo,colored.fg('green')))

try:
    Huawei(sys.argv[1])
except IndexError:
    print(stylize("""[-] Please specify target list
ex: python3 Huwawei_thief.py target.txt""", colored.fg('blue')))