Python colorama.Fore.RED Examples

The following are 30 code examples of colorama.Fore.RED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module colorama.Fore , or try the search function .
Example #1
Source File: Comments.py    From URS with MIT License 8 votes vote down vote up
def list_submissions(reddit, post_list, parser):
        print("\nChecking if post(s) exist...")
        posts, not_posts = Validation.Validation.existence(s_t[2], post_list, parser, reddit, s_t)
        
        if not_posts:
            print(Fore.YELLOW + Style.BRIGHT + 
                "\nThe following posts were not found and will be skipped:")
            print(Fore.YELLOW + Style.BRIGHT + "-" * 55)
            print(*not_posts, sep = "\n")

        if not posts:
            print(Fore.RED + Style.BRIGHT + "\nNo submissions to scrape!")
            print(Fore.RED + Style.BRIGHT + "\nExiting.\n")
            quit()

        return posts 
Example #2
Source File: login.py    From maubot with GNU Affero General Public License v3.0 7 votes vote down vote up
def login(server, username, password, alias) -> None:
    data = {
        "username": username,
        "password": password,
    }
    try:
        with urlopen(f"{server}/_matrix/maubot/v1/auth/login",
                     data=json.dumps(data).encode("utf-8")) as resp_data:
            resp = json.load(resp_data)
            config["servers"][server] = resp["token"]
            if not config["default_server"]:
                print(Fore.CYAN, "Setting", server, "as the default server")
                config["default_server"] = server
            if alias:
                config["aliases"][alias] = server
            save_config()
            print(Fore.GREEN + "Logged in successfully")
    except HTTPError as e:
        try:
            err = json.load(e)
        except json.JSONDecodeError:
            err = {}
        print(Fore.RED + err.get("error", str(e)) + Fore.RESET) 
Example #3
Source File: cb_tools.py    From Forager with MIT License 7 votes vote down vote up
def run_feed_server():
    #stands up the feed server, points to the CB/json_feeds dir
    chdir('data/json_feeds/')
    port = 8000
    handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("", port), handler)

    try:
        print((Fore.GREEN + '\n[+]' + Fore.RESET), end=' ')
        print(('Feed Server listening at http://%s:8000' % gethostname()))
        httpd.serve_forever()
    except:
        print((Fore.RED + '\n[-]' + Fore.RESET), end=' ')
        print("Server exited")

    return 
Example #4
Source File: rpsgame.py    From python-for-absolute-beginners-course with MIT License 6 votes vote down vote up
def get_roll(player_name, roll_names):
    try:
        print("Available rolls:")
        for index, r in enumerate(roll_names, start=1):
            print(f"{index}. {r}")

        text = input(f"{player_name}, what is your roll? ")
        if text is None or not text.strip():
            print("You must enter response")
            return None

        selected_index = int(text) - 1

        if selected_index < 0 or selected_index >= len(roll_names):
            print(f"Sorry {player_name}, {text} is out of bounds!")
            return None

        return roll_names[selected_index]
    except ValueError as ve:
        print(Fore.RED + f"Could not convert to integer: {ve}" + Fore.WHITE)
        return None 
Example #5
Source File: build.py    From maubot with GNU Affero General Public License v3.0 6 votes vote down vote up
def read_meta(path: str) -> Optional[PluginMeta]:
    try:
        with open(os.path.join(path, "maubot.yaml")) as meta_file:
            try:
                meta_dict = yaml.load(meta_file)
            except YAMLError as e:
                print(Fore.RED + "Failed to build plugin: Metadata file is not YAML")
                print(Fore.RED + str(e) + Fore.RESET)
                return None
    except FileNotFoundError:
        print(Fore.RED + "Failed to build plugin: Metadata file not found" + Fore.RESET)
        return None
    try:
        meta = PluginMeta.deserialize(meta_dict)
    except SerializerError as e:
        print(Fore.RED + "Failed to build plugin: Metadata file is not valid")
        print(Fore.RED + str(e) + Fore.RESET)
        return None
    return meta 
Example #6
Source File: tools.py    From Forager with MIT License 6 votes vote down vote up
def update_progress(progress):
    barLength = 20  # Modify this value to change the length of the progress bar
    status = ""
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
        status = "error: progress var must be float\r\n"
    if progress < 0:
        progress = 0
        status = Fore.RED + "Halt!\r\n"
    if progress >= .999:
        progress = 1
        status = Fore.GREEN + " Complete!\r\n"
    block = int(round(barLength*progress))
    text = "\r[*] Progress: [{0}] {1}% {2}".format("#"*block + "-"*(barLength-block), round(progress*100), status)
    sys.stdout.write(text)
    sys.stdout.flush() 
Example #7
Source File: cb_tools.py    From Forager with MIT License 6 votes vote down vote up
def create_json_feed(meta, json_path):
        #Creating JSON feed using scripts in cbfeeds/
        data = generate_feed.create_feed(meta)
        #print data

        #Saving the data to file in json_feeds/
        try:
            print((Fore.YELLOW + '[*]' + Fore.RESET), end=' ')
            print('Saving report to: %s' % json_path)
            dump_data = open(json_path, 'w+').write(data)
        except:
            print((Fore.RED + '[-]' + Fore.RESET), end=' ')
            print('Could not dump report to %s' % json_path)
            exit(0)

        return 
Example #8
Source File: binarly_query.py    From binarly-query with MIT License 6 votes vote down vote up
def main(options):
    if options.pretty_print and not HAS_TABULATE:
        print(Style.BRIGHT + Fore.RED + "Pretty printing requires tabulate python module. (pip install tabulate)")
        return

    init_api(options)
    cmd = options.commands

    switcher = {
        'search': process_search,
        'hunt': process_hunt,
        'sign': process_sign,
        'classify': process_classify,
        'metadata': process_metadata,
        'demo': process_demo
    }

    # Get the function from switcher dictionary
    process_fn = switcher.get(cmd)
    # Execute the function
    return process_fn(options) 
Example #9
Source File: ProxyTool.py    From ProxHTTPSProxyMII with MIT License 6 votes vote down vote up
def handle_one_request(self):
        """Catch more exceptions than default

        Intend to catch exceptions on local side
        Exceptions on remote side should be handled in do_*()
        """
        try:
            BaseHTTPRequestHandler.handle_one_request(self)
            return
        except (ConnectionError, FileNotFoundError) as e:
            logger.warning("%03d " % self.reqNum + Fore.RED + "%s %s", self.server_version, e)
        except (ssl.SSLEOFError, ssl.SSLError) as e:
            if hasattr(self, 'url'):
                # Happens after the tunnel is established
                logger.warning("%03d " % self.reqNum + Fore.YELLOW + '"%s" while operating on established local SSL tunnel for [%s]' % (e, self.url))
            else:
                logger.warning("%03d " % self.reqNum + Fore.YELLOW + '"%s" while trying to establish local SSL tunnel for [%s]' % (e, self.path))
        self.close_connection = 1 
Example #10
Source File: output.py    From drydock with GNU General Public License v2.0 6 votes vote down vote up
def print_results(self,results):
    try:
      if results['status'] == 'Pass':
        print ("Status: " + Fore.GREEN + 'Pass' + Fore.RESET)
      elif results['status'] == 'Fail':
        print ("Status: " + Fore.RED + 'Fail' + Fore.RESET)
    except KeyError:
      pass
    except TypeError:
      pass
    print "Description: " + results['descr']
    try:
      res = str(results['output'])
      print "Output: "
      print(Style.DIM + res + Style.RESET_ALL)
    except KeyError:
      pass
    print "\n" 
Example #11
Source File: automate_project.py    From project-automation with MIT License 6 votes vote down vote up
def CreateGitHubRepo():
    global repoName
    global private
    global username
    global password
    GetCredentials()
    try:
        user = Github(username, password).get_user()
        user.create_repo(repoName, private=private)
        return True
    except Exception as e:
        repoName = ""
        username = ""
        password = ""
        private = ""
        print(Fore.RED + str(e) + Fore.WHITE)
        return False 
Example #12
Source File: main.py    From network-programmability-stream with MIT License 6 votes vote down vote up
def main():
    start_time = time.time()
    nr = InitNornir("config.yaml", configure_logging=False)
    # result = nr.run(
    #     task=netmiko_send_command,
    #     command_string="show cdp neighbors detail",
    #     use_textfsm=True,
    # )
    nr.run(
        task=update_lldp_neighbors,
    )
    logger.info("LLDP details were successfully fetched using RESTCONF and OPENCONFIG")
    milestone = time.time()
    time_to_run = milestone - start_time
    print(
        f"{Fore.RED}It took {time_to_run:.2f} seconds to get and parse LLDP details"
        f"{Fore.RESET}"
    )
    graph, edge_labels = build_graph(nr.inventory.hosts.values())
    draw_and_save_topology(graph, edge_labels)
    time_to_run = time.time() - milestone
    print(
        f"{Fore.RED}It took additional {time_to_run:.2f} seconds "
        f"to draw and save the network topology{Fore.RESET}"
    ) 
Example #13
Source File: output.py    From h2t with MIT License 6 votes vote down vote up
def print_line(message, level=1, category = None, title = None, status=False):
    sts = get_status(category, status)

    if sts == 'applied':
        color = Fore.GREEN
        pre = '[+] '
    elif sts == 'touse':
        color = Fore.YELLOW
        pre = '[+] '
    elif sts == 'toremove':
        color = Fore.RED
        pre = '[-] '
    else:
        color = ''
        pre = ''

    if title:
        print(' '*4*level + Style.BRIGHT + title + ': ' + Style.RESET_ALL + message)
    else:
        print(' '*4*level + color + Style.BRIGHT + pre + Fore.RESET + message) 
Example #14
Source File: cloudfail.py    From CloudFail with MIT License 6 votes vote down vote up
def update():
    print_out(Fore.CYAN + "Just checking for updates, please wait...")
    print_out(Fore.CYAN + "Updating CloudFlare subnet...")
    if(args.tor == False):
        headers = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'}
        r = requests.get("https://www.cloudflare.com/ips-v4", headers=headers, cookies={'__cfduid': "d7c6a0ce9257406ea38be0156aa1ea7a21490639772"}, stream=True)
        with open('data/cf-subnet.txt', 'wb') as fd:
            for chunk in r.iter_content(4000):
                fd.write(chunk)
    else:
        print_out(Fore.RED + Style.BRIGHT+"Unable to fetch CloudFlare subnet while TOR is active")
    print_out(Fore.CYAN + "Updating Crimeflare database...")
    r = requests.get("http://crimeflare.net:83/domains/ipout.zip", stream=True)
    with open('data/ipout.zip', 'wb') as fd:
        for chunk in r.iter_content(4000):
            fd.write(chunk)
    zip_ref = zipfile.ZipFile("data/ipout.zip", 'r')
    zip_ref.extractall("data/")
    zip_ref.close()
    os.remove("data/ipout.zip")


# END FUNCTIONS 
Example #15
Source File: Logger.py    From URS with MIT License 6 votes vote down vote up
def master_timer(function):
        def wrapper(*args):
            logging.info("INITIALIZING URS.")
            logging.info("")

            start = time.time()
            
            try:
                function(*args)
            except KeyboardInterrupt:
                print(Style.BRIGHT + Fore.RED + "\n\nURS ABORTED BY USER.\n")
                logging.warning("")
                logging.warning("URS ABORTED BY USER.\n")
                quit()

            logging.info("URS COMPLETED SCRAPES IN %.2f SECONDS.\n" % \
                (time.time() - start))

        return wrapper 
Example #16
Source File: binarly_query.py    From binarly-query with MIT License 6 votes vote down vote up
def process_search(options):
    search_query = []
    search_query.extend([hex_pattern(val.replace(' ', '')) for val in options.hex])
    search_query.extend([ascii_pattern(val) for lst in options.a for val in lst])
    search_query.extend([wide_pattern(val) for lst in options.w for val in lst])

    result = BINOBJ.search(
        search_query, limit=options.limit, exact=options.exact, test=options.test)
    if 'error' in result:
        print(Style.BRIGHT + Fore.RED + result['error']['message'])
        return

    if 'stats' in result:
        show_stats_new(result['stats'], options.limit)

    if len(result['results']) == 0:
        return

#    if len(result['results']) >= options.limit:
#        print("Showing top {0} results:".format(options.limit))
#    else:
#        print("Results:")

    show_results(result['results'], pretty_print=options.pretty_print) 
Example #17
Source File: Redditor.py    From URS with MIT License 6 votes vote down vote up
def list_redditors(parser, reddit, user_list):
        print("\nChecking if Redditor(s) exist...")
        users, not_users = Validation.Validation.existence(s_t[1], user_list, parser, reddit, s_t)
        
        if not_users:
            print(Fore.YELLOW + Style.BRIGHT + 
                "\nThe following Redditors were not found and will be skipped:")
            print(Fore.YELLOW + Style.BRIGHT + "-" * 59)
            print(*not_users, sep = "\n")

        if not users:
            print(Fore.RED + Style.BRIGHT + "\nNo Redditors to scrape!")
            print(Fore.RED + Style.BRIGHT + "\nExiting.\n")
            quit()

        return users 
Example #18
Source File: Basic.py    From URS with MIT License 6 votes vote down vote up
def confirm_subreddits(subs, parser):
        while True:
            try:
                confirm = input("\nConfirm selection? [Y/N] ").strip().lower()
                if confirm == options[0]:
                    subs = [sub for sub in subs]
                    return subs
                elif confirm not in options:
                    raise ValueError
                else:
                    print(Fore.RED + Style.BRIGHT + "\nExiting.\n")
                    parser.exit()
            except ValueError:
                print("Not an option! Try again.")    

    ### Scrape again? 
Example #19
Source File: Basic.py    From URS with MIT License 6 votes vote down vote up
def print_subreddits(self, parser, reddit, search_for):
        print("\nChecking if Subreddit(s) exist...")
        subs, not_subs = self._find_subs(parser, reddit, search_for)

        if subs:
            print("\nThe following Subreddits were found and will be scraped:")
            print("-" * 56)
            print(*subs, sep = "\n")
        if not_subs:
            print("\nThe following Subreddits were not found and will be skipped:")
            print("-" * 60)
            print(*not_subs, sep = "\n")

        if not subs:
            print(Fore.RED + Style.BRIGHT + "\nNo Subreddits to scrape!")
            print(Fore.RED + Style.BRIGHT + "\nExiting.\n")
            quit()

        return subs 
Example #20
Source File: cli.py    From Bast with MIT License 6 votes vote down vote up
def controller_creatr(filename):
    """Name of the controller file to be created"""

    path = os.path.abspath('.') + '/controller'
    if not os.path.exists(path):
        os.makedirs(path)

    # if os.path.isfile(path + )

    file_name = str(filename + '.py')
    if os.path.isfile(path + "/" + file_name):
        click.echo(Fore.WHITE + Back.RED + "ERROR: Controller file exists")
        return
    controller_file = open(os.path.abspath('.') + '/controller/' + file_name, 'w+')
    compose = "from bast import Controller\n\nclass " + filename + "(Controller):\n    pass"
    controller_file.write(compose)
    controller_file.close()
    click.echo(Fore.GREEN + "Controller " + filename + " created successfully") 
Example #21
Source File: ginnoptimizer.py    From galera_innoptimizer with GNU General Public License v2.0 6 votes vote down vote up
def print_color(mtype, message=''):
    """@todo: Docstring for print_text.

    :mtype: set if message is 'ok', 'updated', '+', 'fail' or 'sub'
    :type mtype: str
    :message: the message to be shown to the user
    :type message: str

    """

    init(autoreset=False)
    if (mtype == 'ok'):
        print(Fore.GREEN + 'OK' + Fore.RESET + message)
    elif (mtype == '+'):
        print('[+] ' + message + '...'),
    elif (mtype == 'fail'):
        print(Fore.RED + "\n[!]" + message)
    elif (mtype == 'sub'):
        print(('  -> ' + message).ljust(65, '.')),
    elif (mtype == 'subsub'):
        print("\n    -> " + message + '...'),
    elif (mtype == 'up'):
        print(Fore.CYAN + 'UPDATED') 
Example #22
Source File: bitmask_cli.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def execute():
    cfg = Configuration(".bitmaskctl")
    print_json = '--json' in sys.argv

    cli = BitmaskCLI(cfg)
    cli.data = ['core', 'version']
    args = None if '--noverbose' in sys.argv else ['--verbose']

    if should_start(sys.argv):
        timeout_fun = cli.start
    else:
        def status_timeout(args):
            raise RuntimeError('bitmaskd is not running')
        timeout_fun = status_timeout

    try:
        yield cli._send(
            timeout=0.1, printer=_null_printer,
            errb=lambda: timeout_fun(args))
    except Exception, e:
        print(Fore.RED + "ERROR: " + Fore.RESET +
              "%s" % str(e))
        yield reactor.stop() 
Example #23
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def default_printer(result, key=None):
    if isinstance(result, (str, unicode)):
        if result in ('OFF', 'OFFLINE', 'ABORTED', 'False'):
            color = Fore.RED
        else:
            color = Fore.GREEN

        print_str = ""
        if key is not None:
            print_str = Fore.RESET + key.ljust(10)
        print_str += color + result + Fore.RESET
        print(print_str)

    elif isinstance(result, list):
        if result and isinstance(result[0], list):
            result = map(lambda l: ' '.join(l), result)
            for item in result:
                default_printer('\t' + item, key)
        else:
            result = ' '.join(result)
            default_printer(result, key)

    elif isinstance(result, dict):
        for key, value in result.items():
            default_printer(value, key)

    else:
        default_printer(str(result), key) 
Example #24
Source File: cloudfail.py    From CloudFail with MIT License 5 votes vote down vote up
def init(target):
    if args.target:
        print_out(Fore.CYAN + "Fetching initial information from: " + args.target + "...")
    else:
        print_out(Fore.RED + "No target set, exiting")
        sys.exit(1)

    if not os.path.isfile("data/ipout"):
            print_out(Fore.CYAN + "No ipout file found, fetching data")
            update()
            print_out(Fore.CYAN + "ipout file created")

    try:
        ip = socket.gethostbyname(args.target)
    except socket.gaierror:
        print_out(Fore.RED + "Domain is not valid, exiting")
        sys.exit(0)

    print_out(Fore.CYAN + "Server IP: " + ip)
    print_out(Fore.CYAN + "Testing if " + args.target + " is on the Cloudflare network...")

    try:
        ifIpIsWithin = inCloudFlare(ip)

        if ifIpIsWithin:
            print_out(Style.BRIGHT + Fore.GREEN + args.target + " is part of the Cloudflare network!")
        else:
            print_out(Fore.RED + args.target + " is not part of the Cloudflare network, quitting...")
            sys.exit(0)
    except ValueError:
        print_out(Fore.RED + "IP address does not appear to be within Cloudflare range, shutting down..")
        sys.exit(0) 
Example #25
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def print_status(status, depth=0):

    if status.get('vpn') == 'disabled':
        print('vpn       ' + Fore.RED + 'disabled' + Fore.RESET)
        return

    for name, v in [('status', status)] + status['childrenStatus'].items():
        line = Fore.RESET + name.ljust(12)
        if v['status'] in ('on', 'starting'):
            line += Fore.GREEN
        elif v['status'] == 'failed':
            line += Fore.RED
        line += v['status']
        if v.get('error'):
            line += Fore.RED + " (%s)" % v['error']
        line += Fore.RESET
        print(line)

    for k, v in status.items():
        if k in ('status', 'childrenStatus', 'error'):
            continue
        if k == 'up':
            k = '↑↑↑         '
        elif k == 'down':
            k = '↓↓↓         '
        print(Fore.RESET + k.ljust(12) + Fore.CYAN + str(v) + Fore.RESET) 
Example #26
Source File: logs.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def error(msg):
    print Fore.RED + msg + Fore.RESET 
Example #27
Source File: test_skelebot_main.py    From skelebot with MIT License 5 votes vote down vote up
def test_skelebot_runtime_error(self, mock_yaml, exit_mock, print_mock):
        mock_yaml.side_effect = RuntimeError("Environment Not Found")

        sb.main()

        print_mock.assert_called_once_with(Fore.RED + "ERROR" + Style.RESET_ALL + " | Environment Not Found")
        exit_mock.assert_called_once_with(1) 
Example #28
Source File: command.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def _error(self, msg):
        print Fore.RED + "[!] %s" % msg + Fore.RESET
        sys.exit(1) 
Example #29
Source File: core.py    From shellpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        if _is_colorama_enabled():
            return 'Command {red}\'{cmd}\'{end} failed with error code {code}, stderr output is {red}{stderr}{end}'\
                .format(red=Fore.RED, end=Style.RESET_ALL, cmd=self.cmd, code=self.result.returncode,
                        stderr=self.result.stderr)
        else:
            return 'Command \'{cmd}\' failed with error code {code}, stderr output is {stderr}'.format(
                    cmd=self.cmd, code=self.result.returncode, stderr=self.result.stderr) 
Example #30
Source File: core.py    From shellpy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, process, params):
        self._process = process
        self._params = params
        self.stdin = Stream(process.stdin, sys.stdin.encoding)

        print_stdout = _is_param_set(params, _PARAM_PRINT_STDOUT) or config.PRINT_STDOUT_ALWAYS
        self.stdout = Stream(process.stdout, sys.stdout.encoding, print_stdout)

        print_stderr = _is_param_set(params, _PARAM_PRINT_STDERR) or config.PRINT_STDERR_ALWAYS
        color = None if not _is_colorama_enabled() else Fore.RED
        self.stderr = Stream(process.stderr, sys.stderr.encoding, print_stderr, color)