Example #1
0
def get_hash_state():
    print colored.magenta("[?] Paste in the MD5, SHA-1 or SHA256 hash:")
    hashvalue = raw_input().strip(" ")
    if len(hashvalue) == 32:
        print colored.yellow("[*] MD5 Detected.")
        hashtype = "md5"
    if len(hashvalue) == 40:
        print colored.yellow("[*] SHA-1 Detected.")
        hashtype = "sha1"
    if len(hashvalue) == 64:
        print colored.yellow("[*] SHA-256 Detected.")
        hashtype = "sha256"

    print colored.yellow("[*] Checking " + str(hashvalue))
    hashstate = bit9.check_hash(hashtype, hashvalue)

    if len(hashstate) == 0:
        print colored.yellow("[-] Hash does not exist in our envirnment")
        print colored.magenta("[?] Would you like to ban this Hash?")
        userinput = get_user_input()
        if userinput == True:
            bit9.ban_hash(hashvalue, "Pre-emptive Hash Ban")
        if userinput == False:
            print colored.yellow("[*] Okay, not banning the Hash.")
    else:
        bit9.eval_hash_state(hashstate)
        print colored.green("[+] Hash checking complete.")
Example #2
0
def list_existing_drives():
    puts(colored.green('List registered Drives for editing / deleting...\n'))

    with indent(4, quote=' >'):
        puts('To edit a Drive, type the index of the Drive in the table.')
        puts(
            'To delete a Drive, type a minus sign followed by the index of the Drive.'
        )
        puts('To abort and return to main menu, hit [Ctrl+C].')
        puts(
            'For example, type "1" to edit the Drive indexed 1, and type "-1" to delete it.'
        )
    puts()

    account_store.get_all_accounts()
    drive_list = []
    for key, drive in drive_store.get_all_drives().items():
        drive_id, account_id, account_type = key
        with indent(4):
            puts(
                columns([(colored.green('Index')), 8],
                        [(colored.magenta('Drive ID')), 17],
                        [(colored.magenta('Drive Type')), 12],
                        [(colored.cyan('Account')), 20],
                        [(colored.yellow('Local Root')), None]))
            profile = drive.root.account.profile
            puts(
                columns([str(len(drive_list)), 8], [drive_id, 17],
                        [drive.type, 12],
                        ["{} ({})".format(account_id, profile.name), 20],
                        [drive.config.local_root, None]))
        drive_list.append(drive)
    prompt_edit_drive(drive_list)
Example #3
0
 def Run(graph, timetable, report):
     print colored.yellow(
         "[*] Adding Modules Loaded Threat Intel From Bit9.")
     for item in report['process']['modload_complete']:
         #print item
         if item.split("|")[1] != '':
             hashvalue = item.split('|')[1]
             intelresult = CheckHash.Run(hashvalue)
             #print intelresult
             #print type(intelresult[0]['threat'])
             if len(intelresult) >= 1 and intelresult[0]['threat'] == 100:
                 print colored.magenta("[+] Bit9 Threat Intel Hit! " +
                                       str(hashvalue))
                 threatlabel = intelresult[0]['fileName'] + str(
                     "-Threat=") + str(intelresult[0]['threat'])
                 time = item.split("|")[0][:-4]
                 modload_name = item.split("|")[2]
                 time_node = GetNode.Run(graph, time, "time", float(1.0))
                 threat_node = GetNode.Run(graph, threatlabel, "threat",
                                           float(5.0))
                 modload_node = GetNode.Run(graph, modload_name, "modload",
                                            float(1.0))
                 ConnectNodes.Run(graph, time_node, modload_node)
                 ConnectNodes.Run(graph, modload_node, threat_node)
             else:
                 print colored.cyan("[?] Hash not a threat, " +
                                    str(hashvalue))
                 pass
     print colored.green("[+] Completed.\n")
Example #4
0
def call_api_with_results(url):
    print colored.cyan("Making request: %s" % (url))
    r = requests.get(url, stream=True, timeout=5)

    if r.headers.get('content-length'):
        total_length = int(r.headers.get('content-length'))
        content = ''
        for chunk in progress.bar(r.iter_content(chunk_size=1024),
                                                 expected_size=(total_length/1024) + 1,
                                                 label=colored.green("  KB received: ")):
            content += chunk
    else:
        content = r.content

    if (r.status_code >= 200 and r.status_code < 300):
        print 'Status Code: %s' % colored.green(str(r.status_code))
    else:
        print 'Status Code: %s' % colored.red(str(r.status_code))

    print colored.cyan('Headers:')
    pretty_dict(r.headers)

    parsed_content = json.loads(content)
    print colored.magenta('Content:')
    print json.dumps(parsed_content, indent=2, sort_keys=True)
Example #5
0
def release(jshare_db, args):
    print(colored.magenta("Grabbing open notebooks..."))
    time.sleep(2)

    raw_notebooks = get_notebooks(jshare_db)
    notebooks = {}

    for port in raw_notebooks:
        if not is_in_db(jshare_db, port):
            notebooks[port] = raw_notebooks[port]

    if len(notebooks) == 0:
        print(colored.green('NO NOTEBOOKS OPEN'))
        sys.exit(0)

    print(colored.green('\nWhich notebook are you referring to?'))

    for i, key in enumerate(notebooks):
        try:
            jshare_db[key]

        except Exception as e:
            print('     {} {}'.format(colored.cyan('| {} |'.format(key)),
                                      notebooks[key][0]))

    while (1):
        if (sys.version_info > (3, 0)):
            port_chosen = input(colored.cyan('NOTEBOOK PORT: '))
        else:
            port_chosen = raw_input(colored.cyan('NOTEBOOK PORT: '))
        if port_chosen == 'q' or port_chosen == 'quit' or port_chosen == ':q':
            sys.exit(0)
        if port_chosen in notebooks:
            break
        else:
            print(colored.red('ERROR: MUST ENTER A VALID NOTEBOOK PORT'))
            continue

    os.system('ngrok http {} > ngrok.log &'.format(port_chosen))

    print(
        colored.magenta(
            "Opening notebook on port {} up...".format(port_chosen)))
    time.sleep(10)

    r = requests.get('http://127.0.0.1:4040/api/tunnels')
    r.raise_for_status()
    ngrok_url = r.json()['tunnels'][0]['public_url']

    notebook_url = ngrok_url + '/' + '?token=' + notebooks[port_chosen][1]

    jshare_db[port_chosen] = [notebooks[port_chosen][0], notebook_url]

    print(
        colored.green(
            "Opened! To see a list of open notebooks try running jupyshare show"
        ))
    print(colored.green("Your notebook is found on {}".format(notebook_url)))

    webbrowser.get(args.browser).open_new_tab(notebook_url)
Example #6
0
def list_existing_drives():
    puts(colored.green('List registered Drives for editing / deleting...\n'))

    with indent(4, quote=' >'):
        puts('To edit a Drive, type the index of the Drive in the table.')
        puts('To delete a Drive, type a minus sign followed by the index of the Drive.')
        puts('To abort and return to main menu, hit [Ctrl+C].')
        puts('For example, type "1" to edit the Drive indexed 1, and type "-1" to delete it.')
    puts()

    account_store.get_all_accounts()
    drive_list = []
    for key, drive in drive_store.get_all_drives().items():
        drive_id, account_id, account_type = key
        with indent(4):
            puts(columns(
                [(colored.green('Index')), 8],
                [(colored.magenta('Drive ID')), 17],
                [(colored.magenta('Drive Type')), 12],
                [(colored.cyan('Account')), 20],
                [(colored.yellow('Local Root')), None]))
            profile = drive.root.account.profile
            puts(columns(
                [str(len(drive_list)), 8],
                [drive_id, 17],
                [drive.type, 12],
                ["{} ({})".format(account_id, profile.name), 20],
                [drive.config.local_root, None]))
        drive_list.append(drive)
    prompt_edit_drive(drive_list)
Example #7
0
def get_hash_state():
    print colored.magenta("[?] Paste in the MD5, SHA-1 or SHA256 hash:")
    hashvalue=raw_input().strip(" ")
    if len(hashvalue)==32:
        print colored.yellow("[*] MD5 Detected.")
        hashtype="md5"
    if len(hashvalue)==40:
        print colored.yellow("[*] SHA-1 Detected.")
        hashtype="sha1"
    if len(hashvalue)==64:
        print colored.yellow("[*] SHA-256 Detected.")
        hashtype="sha256"
    
    print colored.yellow("[*] Checking "+str(hashvalue))
    hashstate=bit9.check_hash(hashtype, hashvalue)

    if len(hashstate)==0:
        print colored.yellow("[-] Hash does not exist in our envirnment")
        print colored.magenta("[?] Would you like to ban this Hash?")
        userinput=get_user_input()
        if userinput==True:
            bit9.ban_hash(hashvalue,"Pre-emptive Hash Ban")
        if userinput==False:
            print colored.yellow("[*] Okay, not banning the Hash.")
    else:
        bit9.eval_hash_state(hashstate)
        print colored.green("[+] Hash checking complete.")
Example #8
0
def show_doc() :
    doc = """
A very simple python script to check what your friend are doing on coding sites.
You can see you friends Last visit, Last question solved, Last contest given.

- Simple to use : Built with love so it's easy to use. Problem ? see the doc.
- Infinite options : There are many so i'll list all of them
- Add any number of usernames.
- single command will stalk every username.
- you can stalk any user anonymous.
- Secure : Belive me it's secure, till you take care of data file (no playing).
- Text Highlighting is cross platform - Supports Linux, MAC, Windows for the terminal based highlighting.
"""
    puts(colored.cyan(doc))
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if(x == 1) :
        flag = 0
        call_defined_function(menu(flag))
    elif(x == 0) :
        clear()
    else :
        flag = 1
        call_defined_function(menu(flag))
Example #9
0
def show_all_data() :
    """showing all entries present in the data file"""
    loop = 1
    cwd = os.getcwd()
    file_path = cwd+"\DATA"
    file_content = open(file_path)
    users_list = file_content.read().split()
    puts(colored.green("List of entries present in data file."))
    space()
    for user in users_list :
        puts(colored.yellow(str(loop)+". "+user))
        loop = loop + 1
    if loop == 1 :
        puts(colored.cyan("message : No entries found!"))
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if(x == 1) :
        flag = 0
        call_defined_function(menu(flag))
    elif(x == 0) :
        clear()
    else :
        flag = 1
        call_defined_function(menu(flag))
 def print_shell(self, *args):
     try:
         for arg in args:
             arg = str(arg)
             if isinstance(type(args), types.NoneType):
                 continue
             if self.color == 'true':
                 if str(arg).count(self.ruler) == len(str(arg)):
                     print colored.green(arg),
                 elif 'Error' in arg:
                     print colored.red(arg),
                 elif ":\n=" in arg:
                     print colored.red(arg),
                 elif ':' in arg:
                     print colored.blue(arg),
                 elif 'type' in arg:
                     print colored.green(arg),
                 elif 'state' in arg or 'count' in arg:
                     print colored.magenta(arg),
                 elif 'id =' in arg:
                     print colored.yellow(arg),
                 elif 'name =' in arg:
                     print colored.cyan(arg),
                 else:
                     print arg,
             else:
                 print arg,
         print
     except Exception, e:
         print colored.red("Error: "), e
Example #11
0
def greeting_text_and_guide():
    f = Figlet(font='slant')
    puts(colored.green(f.renderText('MangaDLer')))
    puts(colored.green("The mangareader.net Downloader\n"))

    with indent(2, quote=' | '):
        puts(colored.cyan("How to Use MangaDLer\n"))
        puts(
            colored.cyan("""
    Go to a mangareader.net link, for example: \n
    https://www.mangareader.net/naruto/11

    You see the url says 'naruto' for the manga name?
    Copy/paste the manga name 'naruto' into the manga prompt. (case insensitive)\n
        """))
    puts(colored.magenta("Example:"))
    puts(colored.green("Manga Name?: naruto\n"))
    with indent(2, quote=' | '):
        puts(
            colored.cyan("""
    Then when asked what chapters, you can respond one of three ways:
    *) Give a number like 374 for the 374th chapter of naruto.\n
    *) Give a range like 374-390 for the chapters 374, 375, .. 390\n
    *) Write 'all' to download all chapters.\n
        """))

    puts(colored.magenta("Examples:"))
    puts(colored.green("Which chapters?: 2"))
    puts(colored.green("Which chapters?: 2-10"))
    puts(colored.green("Which chapters?: all\n"))
Example #12
0
def show_doc():
    doc = """
A very simple python script to check what your friend are doing on coding sites.
You can see you friends Last visit, Last question solved, Last contest given.

- Simple to use : Built with love so it's easy to use. Problem ? see the doc.
- Infinite options : There are many so i'll list all of them
- Add any number of usernames.
- single command will stalk every username.
- you can stalk any user anonymous.
- Secure : Belive me it's secure, till you take care of data file (no playing).
- Text Highlighting is cross platform - Supports Linux, MAC, Windows for the terminal based highlighting.
"""
    puts(colored.cyan(doc))
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if (x == 1):
        flag = 0
        call_defined_function(menu(flag))
    elif (x == 0):
        clear()
    else:
        flag = 1
        call_defined_function(menu(flag))
Example #13
0
def show_all_data():
    """showing all entries present in the data file"""
    loop = 1
    cwd = os.getcwd()
    file_path = cwd + "/DATA"
    file_content = open(file_path)
    users_list = file_content.read().split()
    puts(colored.green("List of entries present in data file."))
    space()
    for user in users_list:
        puts(colored.yellow(str(loop) + ". " + user))
        loop = loop + 1
    if loop == 1:
        puts(colored.cyan("message : No entries found!"))
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if (x == 1):
        flag = 0
        call_defined_function(menu(flag))
    elif (x == 0):
        clear()
    else:
        flag = 1
        call_defined_function(menu(flag))
 def print_shell(self, *args):
     try:
         for arg in args:
             arg = str(arg)
             if isinstance(type(args), types.NoneType):
                 continue
             if self.color == 'true':
                 if str(arg).count(self.ruler) == len(str(arg)):
                     print colored.green(arg),
                 elif ":\n=" in arg:
                     print colored.red(arg),
                 elif ':' in arg:
                     print colored.blue(arg),
                 elif 'type' in arg:
                     print colored.green(arg),
                 elif 'state' in arg or 'count' in arg:
                     print colored.yellow(arg),
                 elif 'id =' in arg:
                     print colored.cyan(arg),
                 elif 'name =' in arg:
                     print colored.magenta(arg),
                 elif 'Error' in arg:
                     print colored.red(arg),
                 else:
                     print arg,
             else:
                 print arg,
         print
     except Exception, e:
         print colored.red("Error: "), e
Example #15
0
def loadUser():
    headers = {'User-Agent': config.tvtime["auth"]['user-agent']}
    request = requests.get(config.tvtime["urls"]['user'] + "?access_token=" +
                           access_token,
                           headers=headers)
    request_json = request.json()
    if (request_json["result"] == "OK"):
        global username
        username = request_json["user"]["name"]
        puts(
            colored.yellow('[Plex-TvTime-Agent]') +
            colored.magenta('[General]') +
            "###############################################################################"
        )
        puts(
            colored.yellow('[Plex-TvTime-Agent]') +
            colored.magenta('[General]') + " Welcome " + username)
        puts(
            colored.yellow('[Plex-TvTime-Agent]') +
            colored.magenta('[General]') +
            "###############################################################################"
        )
        puts(
            colored.yellow('[Plex-TvTime-Agent]') + colored.cyan('[Phase 1]') +
            " Loading Tv Time Data ")
        loadTvTimeShows()
    else:
        puts(
            colored.yellow('[Plex-TvTime-Agent]') + colored.cyan('[Phase 1]') +
            colored.red('[Error]') + " Token Expired, reauthenticate!")
        authenticate()
 def print_shell(self, *args):
     try:
         for arg in args:
             arg = str(arg)
             if isinstance(type(args), types.NoneType):
                 continue
             if self.color == "true":
                 if str(arg).count(self.ruler) == len(str(arg)):
                     print colored.green(arg),
                 elif "Error" in arg:
                     print colored.red(arg),
                 elif ":\n=" in arg:
                     print colored.red(arg),
                 elif ":" in arg:
                     print colored.blue(arg),
                 elif "type" in arg:
                     print colored.green(arg),
                 elif "state" in arg or "count" in arg:
                     print colored.magenta(arg),
                 elif "id =" in arg:
                     print colored.yellow(arg),
                 elif "name =" in arg:
                     print colored.cyan(arg),
                 else:
                     print arg,
             else:
                 print arg,
         print
     except Exception, e:
         print colored.red("Error: "), e
Example #17
0
def send_ena_action(ena_acc, action, test=False, date=None, samples=False):
    file_path = create_xml(ena_acc, action, date, samples)
    url = settings.ENA_SRA_URL
    if test:
        url = settings.ENA_SRA_DEV_URL
        print colored.magenta('This submission is going to ENA Dev Server')
    content = '<html>'
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    while '<html>' in content:
        files = {'SUBMISSION': open(file_path, 'rb')}
        r = requests.post(url, files=files, verify=False, timeout=1000)
        content = r.content
        if '<html>' not in content:
            break
        else:
            time.sleep(20)
    print content
    server = 'production'
    if test:
        server = 'test'
    if 'success="true' not in content:
        print colored.cyan('FAILURE: Failed submission to ENA. with the following errors ')
        errors = content.split('<ERROR>')
        for e in errors[1:]:
            print colored.red(e.split('</ERROR>')[0])
        return False, [i.split('</ERROR>')[0] for i in errors]


    else:
        print colored.green("%s was applied successfully on %s in the %s server" % (action, ena_acc, server))
        return True, []
Example #18
0
def respF(response):
    if response == True:
        print(colored.yellow("[*] Intercepted a file. Downloading..."))
        msg = requests.get(f'http://{server}:{port}/getPayload',
                           data={
                               'username': username
                           }).text
        file_data, filename = msg.split("FILEBREAK")
        file_bytes = base64.b64decode(file_data.encode())
        filename = filename.split(".enc")[0]
        with open(filename, 'wb') as f:
            f.write(file_bytes)
        # os.system(f"openssl rsautl -decrypt -inkey $HOME/.winds/private.pem -in {filename} -out $HOME/Downloads/{filename}")
        print(
            colored.magenta(
                "\nLook or ask for DECRYPTION_PHRASE key in secure chat"))
        print(
            colored.red(
                ">> Press ENTER/ RETURN and then Enter decryption password in next line: "
            ))
        os.system(
            f"openssl aes-256-cbc -d -salt -pbkdf2 -in {filename} -out $HOME/Downloads/{filename}"
        )
        os.system(f"rm {filename}")
        print(colored.magenta("[+] File saved in downloads folder."))
Example #19
0
def kill(jshare_db):
    ngrok_processes, ngrok_dict = get_live_processes()
    notebooks = get_notebooks(jshare_db)

    if len(ngrok_processes) == 0:
        print(colored.green('NO NOTEBOOKS ARE IN THE CLOUD'))
        sys.exit(0)

    print(
        colored.green(
            "\nWhich tunnel do you want to kill? Type 'all' if you want to shut everything down"
        ))

    for i, key in enumerate(ngrok_dict):
        if is_in_db(jshare_db, key):
            if key not in notebooks:
                os.system('kill {}'.format(ngrok_dict[key]))
                print(
                    colored.magenta(
                        "Didn't find any notebooks on port {}. Killing ngrok connection."
                        .format(key)))
                del jshare_db[key]
            else:
                print('     {} {}'.format(colored.cyan('| {} |'.format(key)),
                                          jshare_db[key][0]))
                print('              {}'.format(
                    colored.magenta(jshare_db[key][1])))
        else:
            jshare_db[key] = ["Location unknown", "Url unknown"]
            print('     {} {}'.format(colored.cyan('| {} |'.format(key)),
                                      jshare_db[key][0]))
            print('              {}'.format(colored.magenta(
                jshare_db[key][1])))

    while (1):
        port_chosen = raw_input(colored.cyan('NOTEBOOK PORT: '))

        if port_chosen in ('q', 'quit', ':q'):
            sys.exit(0)
        if port_chosen == 'all':
            for key in ngrok_dict:
                os.system('kill {}'.format(ngrok_dict[key]))
                print(
                    colored.green(
                        "Killed notebook listening on port {}".format(key)))
            jshare_db.clear()
            sys.exit(0)
        if port_chosen in ngrok_dict:
            break
        else:
            print(colored.red('ERROR: MUST ENTER A VALID NOTEBOOK PORT'))
            continue

    os.system('kill {}'.format(ngrok_dict[port_chosen]))
    del jshare_db[port_chosen]
    print(
        colored.green(
            "Killed notebook listening on port {}".format(port_chosen)))
    sys.exit(0)
Example #20
0
def disgenet( ):
	print( colored.yellow( "\n########################################### DISGENET -- DISGENET -- DISGENET -- ###########################################\n" ) )

	__DEBUG__ = 0
	# # connect to db
	host, user, password, db = connection_details( )
	conn = pymysql.connect( host, user, password )
	if conn != -1 :
		print( colored.green( 'database connection established' ) )
	else:
		print( colored.red ('Houston we have a problem' ) )
		sys.exit( 255 )

	conn.begin( )
	cursor = conn.cursor( )
	# select our database
	cursor.execute( "use " + db )
	conn.commit( )

	## disgenet
	###########################################
	disgenetDataFile = 'disgenet/disgenet_data.tsv'
	disgenetFieldNames = [ 'c1.diseaseId', 'c1.OMIM', 'c2.symbol', 'c2.geneId', 'c2.uniprotId', 'c2.description', 'c2.pantherName', 'c0.score', 'c0.Npmids', 'c0.Nsnps', 'c3.Ndiseases' ]
	restkey    = 'unknownkey';
	restval    = 'uknownvalue';
	dialect    = 'excel-tab';

	# read payload
	###########################################
	disgenetCsvfile = open( disgenetDataFile )
	disgenetReader = csv.DictReader( disgenetCsvfile, disgenetFieldNames, restkey, restval, dialect );

	kot = 0
	counter = 1
	disgenetReaderLength = len( list ( disgenetReader ) ) - 1 # -1 for the header

	disgenetCsvfile     = open( disgenetDataFile )
	disgenetReader      = csv.DictReader( disgenetCsvfile, disgenetFieldNames, restkey, restval, dialect );
	insertgenedataQuery = [ ]

	for row in disgenetReader:
		if kot == 0 : # magic to skip the first header row
			kot = 1
			continue
		insertgenedataQuery.append( "INSERT INTO gene( geneId, geneName, disgenetScore, noPubMedIDs ) VALUES ( '" + row['c2.geneId'] + "', '" + row['c2.symbol'] + "', " + row['c0.score'] + ", " + row['c0.Npmids'] +" );" )

	for query in insertgenedataQuery:
		try:
			cursor.execute( query )
		except pymysql.err.IntegrityError:
			print( colored.magenta( " ( " + str ( counter ) + " of " + str( disgenetReaderLength ) + " ) " ) + colored.red( "FAILED: " + query ) )
		else:
			print( colored.magenta( " ( " + str ( counter ) + " of " + str( disgenetReaderLength ) + " )\t" ) + colored.cyan( query ) )
		counter += 1
	conn.commit( )
	cursor.close( )

	if __DEBUG__:
		sys.exit( 0 )
Example #21
0
 def do_6(self, args):
     #Check if computers from list have Bit9 and/or CB installed
     print colored.magenta("[+] Enter palth of text file: ")
     usercomputerfile=raw_input()
     if os.path.isfile(os.path.abspath(usercomputerfile)) == False:
         print colored.red("[-] "+usercomputerfile+" does not exist")
     else:  
         ComputerLookup(usercomputerfile)
     Launch.show_logo2()
Example #22
0
    def do_3(self, args):
    # """Go through your environments Fire Eye '[-] File INFO was identified by FireEye as malicious.' Alerts.  
    # Check if the hash is banned, check if it was seen in Carbon Black,
    # prompt user to ban hash and/or certificate"""

        print colored.magenta("[?] How many most recent alerts would you like to view?")
        limit=raw_input("10/20/30/40/etc. ")
        FireEyeEvents(limit)
        Launch.show_logo2()
Example #23
0
    def do_2(self, args):
    # """Go through your environments 'SRS Potential Risk File' Alerts.  
    # Check if the hash is banned, check if it was seen in Carbon Black,
    # prompt user to ban hash and/or certificate"""

        print colored.magenta("[?] How many most recent alerts would you like to view?")
        limit=raw_input("10/20/30/40/etc. ")
        PotentialRiskFileEvents(limit)
        Launch.show_logo2()
Example #24
0
def options_proxy():
    my_string = ""
    print(colored.magenta(my_string.center(50,"▬")))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [1]  - [*] ProxyScrape Website [ + Socks5 ] """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [2]  - [*] Proxy-List Website  [ + Socks5 ] """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [3]  - [*] ProxyScrape Website [ + Socks4 ] """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [4]  - [*] Proxy-List Website  [ + Socks4 ] """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [99] - [*] Exit """))
    print(colored.magenta(my_string.center(50,"▬")))
Example #25
0
 def load_cb_config(self,configile):
         print colored.yellow("[*] Loading config file.")
         cfile= open(configile, "r").readlines()
         cbserverurl=str(cfile[0].rstrip())
         cbapitoken=str(cfile[1].rstrip())
         b9serverurl=str(cfile[2].rstrip())
         b9apitoken=str(cfile[3].rstrip())
         print colored.magenta("Carbon Black Server = "+cbserverurl)
         print colored.magenta("Bit9 Server = "+b9serverurl+"\n")
         return (cbserverurl,cbapitoken,b9serverurl,b9apitoken)
Example #26
0
def release(jshare_db, args):
    print(colored.magenta("Grabbing open notebooks..."))
    time.sleep(2)

    raw_notebooks = get_notebooks(jshare_db)
    notebooks = {}

    for port in raw_notebooks:
        if not is_in_db(jshare_db, port):
            notebooks[port] = raw_notebooks[port]

    if len(notebooks) == 0:
        print(colored.green('NO NOTEBOOKS OPEN'))
        sys.exit(0)

    print(colored.green('\nWhich notebook are you referring to?'))

    for i, key in enumerate(notebooks):
        try:
            jshare_db[key]

        except Exception as e:
            print('     {} {}'.format(colored.cyan('| {} |'.format(key)), notebooks[key][0]))

    while(1):
        if (sys.version_info > (3, 0)):
            port_chosen = input(colored.cyan('NOTEBOOK PORT: '))
        else:
            port_chosen = raw_input(colored.cyan('NOTEBOOK PORT: '))
        if port_chosen == 'q' or port_chosen == 'quit' or port_chosen == ':q':
            sys.exit(0)
        if port_chosen in notebooks:
            break
        else:
            print(colored.red('ERROR: MUST ENTER A VALID NOTEBOOK PORT'))
            continue

    os.system('ngrok http {} > ngrok.log &'.format(port_chosen))

    print(colored.magenta("Opening notebook on port {} up...".format(port_chosen)))
    time.sleep(10)

    r = requests.get('http://127.0.0.1:4040/api/tunnels')
    r.raise_for_status()
    ngrok_url = r.json()['tunnels'][0]['public_url']

    notebook_url = ngrok_url + '/' + '?token=' + notebooks[port_chosen][1]

    jshare_db[port_chosen] = [notebooks[port_chosen][0], notebook_url]

    print(colored.green("Opened! To see a list of open notebooks try running jupyshare show"))
    print(colored.green("Your notebook is found on {}".format(notebook_url)))

    webbrowser.get(args.browser).open_new_tab(notebook_url)
Example #27
0
def options_nmap():
    my_string = ""
    print(colored.magenta(my_string.center(50,"▬")))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [1]  - [*] DNS BRUTE   """))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [2]  - [*] TCP SCANNER """))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [3]  - [*] UDP SCANNER """))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [4]  - [*] PING        """))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [5]  - [*] SUBNET SCANNER        """))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [6]  - [*] FAKE IP SCANNER        """))
    print(colored.yellow("""\t▬▬▬▬▬▬▬▬ [99] - [*] Exit        """))
    print(colored.magenta(my_string.center(50,"▬")))
Example #28
0
def srs_potential_risk_events():
    print colored.magenta("[?] How many most recent alerts would you like to view?")
    limit=raw_input("10/20/30/40/etc. ")
    events=bit9.event("subtype", str(1200), limit)
    print colored.green("[+] Checking Potential Risk Alerts.")
    for event in events:
        if event['description'].endswith(" was identified by Bit9 Software Reputation Service as a potential risk."):
            print colored.red("[-] "+event['description'])
            match = re.match(r"^.*\[(.*)\].*$",event['description'])
            sha256=match.group(1)
            hashstate=bit9.check_hash("sha256", sha256)
            bit9.eval_hash_state(hashstate)
    print colored.green("[+] Our work here is done, check again soon.")
Example #29
0
def insertintoGeneOntology( results ):


	# # connect to db
	host, user, password, db = connection_details( )
	conn = pymysql.connect( host, user, password )
	if conn != -1 :
		print( colored.green( 'database connection established' ) )
	else:
		print( colored.red ('Houston we have a problem' ) )
		sys.exit( 255 )

	conn.begin( )
	cursor = conn.cursor( )
	# select our database
	cursor.execute( "use " + db )
	conn.commit( )

	ignoredOntologiesQuery = [ ]
	totalCounter = 1; # incremented at the end of the loop
	for protein in results:
		parsedJson = { }
		parsedJson = json.loads( results[protein] )
		counter = 1
		for item in parsedJson:
			bar = re.sub( '_', ' ', item['function_namespace'] )
			insertGoQuery = "INSERT INTO geneOntology( ontologyId, ontologyName, ontologyFunction, biological_process, proteinId ) values ( " + str(item['function_id']) + ', ' + str(item['go_term']) + ', \'' + str(item['function_name']) + '\', \'' +  str(bar) + '\', \'' + str( protein ) + '\' );' 
			try:
				cursor.execute( insertGoQuery )
			except:
				print( colored.magenta( " ( " + str ( counter ) + " of " + str( len( parsedJson ) ) + " ) " ) + colored.red( insertGoQuery ) )
				ignoredOntologiesQuery.append( insertGoQuery )
			else:
				print( colored.magenta( " ( " + str ( counter ) + " of " + str( len( parsedJson ) ) + " )" + "/" + str( totalCounter ) ) + " " + colored.cyan( insertGoQuery ) )
			counter += 1
			totalCounter += 1

	conn.commit( ) #moving the commit out of the loop allows for a somewhat faster execution time, at the price of doing a bulk commit at the end.
	cursor.close( )

	# write failed ongologies entries to disk
	if ignoredOntologiesQuery: 
		ignoredOntologiesFile = "ignoredOntologies.txt"
		print( colored.yellow( "##############################################################################"))
		print( "The following ontologies were ignored. They where written to disk ('" + ignoredOntologiesFile + "'') for follow up: " )
		for item in ignoredOntologiesQuery:
			print( colored.yellow( item ) )
		print( colored.yellow( "##############################################################################"))
		with open( ignoredOntologiesFile, 'w' ) as file:
			for ontology in ignoredOntologiesQuery:
				file.write( ontology )
Example #30
0
def build():
    start = time.time()
    error_occurred = False

    with indent(4):

        if not exists(build_dir):
            puts(colored.yellow('Build directory missing.'))
            puts(colored.yellow('Creating a new directory at %s' % build_dir))
            makedirs(build_dir)

        puts(colored.cyan('Build List:'))
        with indent(4):
            for js_file_path in build_list:
                puts(colored.magenta(js_file_path))

        puts(colored.cyan('Concatenating...'))
        with open(raw_target, mode="w") as raw_target_file:
            for js_file_path in build_list:
                raw_target_file.write('// *****************************************\n')
                raw_target_file.write('// %s\n' % js_file_path)
                raw_target_file.write('// *****************************************\n')
                with open(join(project_dir, js_file_path), mode='r') as js_file:
                    raw_target_file.write(js_file.read())
                    raw_target_file.write('\n\n')
        with indent(4):
            puts(colored.magenta('Done.'))

        puts(colored.cyan('Minifying...'))
        with indent(4):
            closure_bin = join(vendor_dir, 'closure/compiler.jar')
            r = envoy.run('java -jar %s --js=%s  --js_output_file=%s' % (
                closure_bin,
                raw_target,
                min_target,
            ))

            if r.status_code == 0:
                puts(colored.magenta('Done.'))
            else:
                error_occurred = True
                puts(colored.red('There was an error running the closure compiler'))
                puts(r.std_out)
                puts(r.std_err)

    run_time = time.time() - start
    if not error_occurred:
        puts(colored.green('Build successfully completed in %g seconds.' % run_time))
    else:
        puts(colored.red('An error occurred :('))
Example #31
0
def full_play() :
    """hacking into your system..lolz wait means stalking all data"""
    loop = 1
    cwd = os.getcwd()
    file_path = cwd+"\DATA"
    file_content = open(file_path)
    users_list = file_content.read().split()
    puts(colored.cyan("[ Getting data from internet.. ]"))
    puts(colored.green("[ Started stalking user accounts.. ]"))
    space()



    print "Sno. \t username \t Last Visit"
    for user in users_list :
        url = "http://codeforces.com/profile/" + user
        response = urllib.urlopen(url)
        if response == None :
            print "Check your Internet conneciton! Not working."
        else :
            scrapper = BeautifulSoup(response , 'html.parser')
            matches = scrapper.prettify()
            matches = scrapper.find('div',{'id':'pageContent'})
            match = matches.find('div',{'class':'roundbox'})
            match = match.find('ul')
            mylist = []
            for li in match.find_all('li') :
                catch = li.get_text()
                if "Last visit" in catch :
                    catch = catch.strip()
                    catch = re.sub(r"\s", "", catch)
                    print " "+ str(loop+1) + "\t " + user +"\t "+ catch[10:]
                    loop += 1
    if loop == 1 :
        puts(colored.cyan("message : No entries found!"))
    # else : 
    #     print_full_table(mylist)
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if(x == 1) :
        flag = 0
        call_defined_function(menu(flag))
    elif(x == 0) :
        clear()
    else :
        flag = 1
        call_defined_function(menu(flag))
Example #32
0
    def run_command(cls, *args):
        requested_keys = { k: True for k in args[0]}.keys()
        all_supported_keys = [x for x in requested_keys if x in supported_commands]

        if len(all_supported_keys):
            # command(s) specified, print help for specified command
            valid_help_keys = all_supported_keys

            print colored.magenta('Parameters can be specified in order they should appear')
            print colored.magenta('Arguments can be specified with "=" between key and value')
            print colored.magenta('\te.g.\tevents 12 venue.state=NY')
            print colored.magenta('\t[PARAMS]: 12 \t [ARGS]: { "venue.state": "NY" }')

            for key in valid_help_keys:
                if key == "help":
                    print colored.cyan('  [%s] takes any of the following arguments' % key)
                    all_args = [x for x in supported_commands.keys() if x != "help"]
                    pprint(all_args, indent=8)

                elif supported_commands[key]:
                    supported_commands[key].get_help_text(name=key)
        else:
            # print supported commands
            valid_help_keys = supported_commands.keys()

            print colored.blue('  Type `help [command1] [command2] ...` to get more information.\n  The following commands are supported:')
            for key in valid_help_keys:
                print colored.cyan('  [%s] - %s' % (key, supported_commands[key].get_info_text()))
Example #33
0
def options():
    my_string = ""
    print(colored.magenta(my_string.center(50,"▬")))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [01] - [*] Whois Lookup """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [02] - [*] NameServer Lookup """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [03] - [*] Traceroute Lookup """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [04] - [*] Fake Nmap İp & Mac Address Scanner Website """))
    print(colored.red("""\t▬▬▬▬▬▬▬▬ [05] - [*] Proxy Download """))
    print(colored.blue("""\t▬▬▬▬▬▬▬▬ [06] - [*] Layer 7 Attack """))
    print(colored.blue("""\t▬▬▬▬▬▬▬▬ [07] - [*] SubDomain Finder """))
    print(colored.blue("""\t▬▬▬▬▬▬▬▬ [08] - [*] WAF Checker """))
    print(colored.blue("""\t▬▬▬▬▬▬▬▬ [09] - [*] Social Media Finder """))
    print(colored.blue("""\t▬▬▬▬▬▬▬▬ [99] - [*] Exit """))
    print(colored.magenta(my_string.center(50,"▬")))
Example #34
0
def kill(jshare_db):
    ngrok_processes, ngrok_dict = get_live_processes()
    notebooks = get_notebooks(jshare_db)

    if len(ngrok_processes) == 0:
        print(colored.green('NO NOTEBOOKS ARE IN THE CLOUD'))
        sys.exit(0)

    print(colored.green("\nWhich tunnel do you want to kill? Type 'all' if you want to shut everything down"))

    for i, key in enumerate(ngrok_dict):
        if is_in_db(jshare_db, key):
            if key not in notebooks:
                os.system('kill {}'.format(ngrok_dict[key]))
                print(colored.magenta("Didn't find any notebooks on port {}. Killing ngrok connection.".format(key)))
                del jshare_db[key]
            else:
                print('     {} {}'.format(colored.cyan('| {} |'.format(key)), jshare_db[key][0]))
                print('              {}'.format(colored.magenta(jshare_db[key][1])))
        else:
            jshare_db[key] = ["Location unknown", "Url unknown"]
            print('     {} {}'.format(colored.cyan('| {} |'.format(key)), jshare_db[key][0]))
            print('              {}'.format(colored.magenta(jshare_db[key][1])))


    while(1):
        if (sys.version_info > (3, 0)):
            port_chosen = input(colored.cyan('NOTEBOOK PORT: '))
        else:
            port_chosen = raw_input(colored.cyan('NOTEBOOK PORT: '))

        if port_chosen in ('q' , 'quit' , ':q'):
            sys.exit(0)
        if port_chosen == 'all':
            for key in ngrok_dict:
                os.system('kill {}'.format(ngrok_dict[key]))
                print(colored.green("Killed notebook listening on port {}".format(key)))
            jshare_db.clear()
            sys.exit(0)
        if port_chosen in ngrok_dict:
            break
        else:
            print(colored.red('ERROR: MUST ENTER A VALID NOTEBOOK PORT'))
            continue

    os.system('kill {}'.format(ngrok_dict[port_chosen]))
    del jshare_db[port_chosen]
    print(colored.green("Killed notebook listening on port {}".format(port_chosen)))
    sys.exit(0)
Example #35
0
def full_play():
    """hacking into your system..lolz wait means stalking all data"""
    loop = 1
    cwd = os.getcwd()
    file_path = cwd + "/DATA"
    file_content = open(file_path)
    users_list = file_content.read().split()
    puts(colored.cyan("[ Getting data from internet.. ]"))
    puts(colored.green("[ Started stalking user accounts.. ]"))
    space()

    print "Sno. \t username \t Last Visit"
    for user in users_list:
        url = "http://codeforces.com/profile/" + user
        response = urllib.urlopen(url)
        if response == None:
            print "Check your Internet conneciton! Not working."
        else:
            scrapper = BeautifulSoup(response, 'html.parser')
            matches = scrapper.prettify()
            matches = scrapper.find('div', {'id': 'pageContent'})
            match = matches.find('div', {'class': 'roundbox'})
            match = match.find('ul')
            mylist = []
            for li in match.find_all('li'):
                catch = li.get_text()
                if "Last visit" in catch:
                    catch = catch.strip()
                    catch = re.sub(r"\s", "", catch)
                    print " " + str(loop +
                                    1) + "\t " + user + "\t " + catch[10:]
                    loop += 1
    if loop == 1:
        puts(colored.cyan("message : No entries found!"))
    # else :
    #     print_full_table(mylist)
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if (x == 1):
        flag = 0
        call_defined_function(menu(flag))
    elif (x == 0):
        clear()
    else:
        flag = 1
        call_defined_function(menu(flag))
Example #36
0
def get_output(translation):
    """Convert the translation data to readable texts.

    The function accept a dictionary which has structure as below:

    {
        'head': {
            'words': <str words>,
            'phonetic': None | (<str phonetic>,) | {'uk': <str>, 'us' <str>:},
            'service' <str service_name>:
        },
        'explains': None | [<str explains>, ...],
        'examples': None | [{'key':, 'value':}, ...]
    }
    """
    result = {}

    # head
    head = translation['head']
    result['head'] = '\n'
    result['head'] += head['words']
    if head['phonetic']:
        if len(head['phonetic']) == 2:
            result['head'] += colored.magenta(
                '  英[ {} ]  美[ {} ]'.format(
                    head['phonetic']['uk'], head['phonetic']['us']
                )
            )
        else:
            result['head'] += colored.magenta(
                '  [ {} ]'.format(head['phonetic'][0])
            )
    result['head'] += colored.dim('  ~  '+head['service'])

    # explains
    result['explains'] = ''
    if translation.get('explains'):
        for item in translation['explains']:
            result['explains'] += colored.dim('\n- ') + colored.green(item)

    # examples
    result['examples'] = ''
    if translation.get('examples'):
        for index, value in enumerate(translation['examples']):
            result['examples'] += colored.dim('\n{}. '.format(index+1)) + \
                high_light(head['words'], value['key']) + \
                '\n   ' + colored.cyan(value['value'])

    return result
Example #37
0
def helper_menu():
	puts(colored.magenta("****************************************"))
	with indent(4):
		puts("1. adventure")
		puts("2. art")
		puts("3. autobiography")
		puts("4. biography")
		puts("5. children")
		puts("6. comedy")
		puts("7. comic")
		puts("8. critique")
		puts("9. drama")
		puts("10. health")
		puts("11. history")
		puts("12. horror")
		puts("13. melodrama")
		puts("14. memoir")
		puts("15. mystery")
		puts("16. myth")
		puts("17. mythology")
		puts("18. poetry")
		puts("19. poetry")
		puts("20. religion")
		puts("21. romance")
		puts("22. satire")
		puts("23. thriller")
		puts("24. tragedy")
		puts("25. travel")
		puts("26. western")
	puts(colored.magenta("****************************************"))

	while True:
		try:
			reply =  int(input("\nPlease pick a genre: \n"))
		except ValueError:
			puts(colored.red("Please enter a valid number between 1 and 26."))
			continue

		if reply < 1:
			puts(colored.red("Please enter a number between 1 and 26."))
			continue
		elif reply > 26:
			puts(colored.red("Please enter a number between 1 and 26."))
			continue
		else:
			break

	return reply
Example #38
0
def match_entity(id):
	"""
	Tries to match a Perseus-Smith entity against a DBpedia entry.
	"""
	logger.debug("%s"%id)
	test_url = format_perseus_uri(id)
	xml = get(test_url)
	temp = transform_tei(xml)
	names = set(parse_xml(temp)["names"])
	desc = parse_xml(temp)["desc"] # this is the Smith's entry
	for n in names:
		#for t in n.split():
		max_res = 10
		
		lookup_results = parse_lookup_reply(do_lookup(n,max_res))
		while(len(lookup_results) == max_res):
			lookup_results = parse_lookup_reply(do_lookup(n,max_res*max_res))
			if(len(lookup_results)==max_res):
				break
	
		documents = [(r["uri"],r["desc"]) for r in lookup_results if r["desc"] is not None]
		logger.debug(documents)
		if(len(documents)>1):
			"""
			there is > 1 result from dbpedia.
			will try to disambiguate using TFIDF model
			"""
			results = suggest_matching(documents,query=desc)
			for n,r in enumerate(results):
				logger.debug("##%i## (%s) %s"%(n,r[1],r[0]))
			
			puts(columns([colored.green("[SMITH DICTIONARY ENTRY]\n%s\n"%desc.encode("utf-8")),60],
			[colored.magenta("[DBPEDIA 1st CANDIDATE] (TFIDF score: %s)\n\"%s\"\n"%(results[0][1].encode("utf-8"),results[0][0][1])),None]))
			puts(colored.cyan("Is \"%s\" the sameAs \"%s\"?\n"%(test_url,results[0][0][0])))
			answer = raw_input("[Yy/Nn]: ")
			return True
		elif(len(documents)==1):
			""
			""
			puts(columns([colored.green("[SMITH DICTIONARY ENTRY]\n%s\n"%desc.encode("utf-8")),60],
			[colored.magenta("[DBPEDIA 1st CANDIDATE]\n%s\n"%documents[0][1].encode("utf-8")),None]))
			puts(colored.cyan("Is \"%s\" the sameAs \"%s\"?\n"%(test_url,documents[0][0])))
			answer = raw_input("[Yy/Nn]: ")
			return True
		else:
			print "No results from the DBpedia query"
			return False
	return
Example #39
0
def pprint(line, indent=0):
    now = datetime.datetime.now().strftime('%H:%M:%S')
    prefix = colored.magenta(str(now) + ':') + ' '
    print(prefix, end='')
    if indent > 0:
        print(' ' * indent, end='')
    print(line)
def config_timesused():
    global times_used
    response = input(colored.magenta('Reset times used to zero?(y/n): '))
    if response == 'y':
        times_used = '0'
        
    update_file()
Example #41
0
File: core.py Project: T2BE/gordon
    def delete(self):

        if self.dry_run:
            self.puts(
                colored.yellow(
                    ("\nYou are trying to delete this project's resources!\n"
                     "By default this command runs in dry-run mode. If you are ok \n"
                     "with the following resources being deleted, you can run this\n"
                     "command with --confirm to do the actual deletion.\n"
                     "\nNOTHING IS GOING TO BE DELETED!\n")
                )
            )
            self.puts(colored.blue("The following resources would be deleted..."))
        else:
            self.puts(colored.blue("Deleting project resources..."))

        context = self.get_initial_context()

        with indent(2):
            self.puts(colored.magenta("\nRegion:{Region}\nStage: {Stage}\n".format(**context)))

        for (number, name, filename, template_type) in self.steps():
            with indent(2):
                self.puts(colored.cyan("{} ({})".format(filename, template_type)))
            with indent(4):
                if self.debug:
                    self.puts(colored.white(u"✸ Delete template {} with context {}".format(filename, context)))
                getattr(self, 'delete_{}_template'.format(template_type))(name, filename, context)
Example #42
0
def list_existing_accounts():
    col = 20
    all_accounts = account_store.get_all_accounts()
    if len(all_accounts) == 0:
        puts(colored.red('There is no linked account yet.'))
        return
    puts(
        colored.green(
            'You have linked the following account(s) to onedrive-d:\n'))
    puts(
        columns([(colored.red('Index')), 10],
                [(colored.magenta('Account ID')), col],
                [(colored.cyan('Account Type')), col],
                [(colored.green('Name')), None]))
    account_list = []
    for id, account in all_accounts.items():
        puts(
            columns([str(len(account_list)), 10],
                    [account.profile.user_id, col], [account.TYPE, col],
                    [account.profile.name, None]))
        account_list.append(account)
    puts(
        colored.yellow(
            '\nTo delete an account, type the index and hit [Enter]. Otherwise hit [Ctrl+C] to break.'
        ))
    puts(
        colored.yellow(
            'Note: all the Drives belonging to the account will also be deleted.'
        ))
    puts()
    try:
        prompt_delete_account(account_list)
    except KeyboardInterrupt:
        puts(colored.green('Aborted.'))
Example #43
0
 def stop(conn, selection):
     error = col.red('error')
     name = col.magenta(conn.get_robot_name())
     if selection:
         s = col.blue(selection)
     if ns.service:
         if conn.stop_service(selection):
             print('stopped {} service on {}'.format(s, name))
         else:
             print('{}: failed to stop service {} on {}'.
                   format(error, s, name))
     elif ns.behavior:
         if conn.stop_behavior(selection):
             print('stopped {} behavior on {}'.format(s, name))
         else:
             print('{}: {} is not installed on {}'.format(error, s, name))
     else:
         focused = conn.get_focused_activity()
         if not focused:
             print('{}: there is no focused activity on {}'.format(error, name))
         else:
             focused = col.blue(focused)
             if conn.life_stop_focus():
                 print('stopped {} on {}'.format(focused, name))
             elif conn.life_stop_focus():
                 print('stopped {} on {}'.format(focused, name))
             else:
                 print('{}: failed to stop focused activity on {}'.
                       format(error, name))
Example #44
0
def update_all():
    puts(colored.magenta('>> gem update'))
    success, _ = gem.update_all()
    if success:
        puts(colored.green('✔\n'))
    else:
        puts_err(colored.red('! failed to update gems\n'))
Example #45
0
    def handle_noargs(self, **options):
        # Inspired by Postfix's "postconf -n".
        from django.conf import settings

        # Because settings are imported lazily, we need to explicitly load them.
        settings._setup()

        user_settings = module_to_dict(settings._wrapped)

        opts = Options()
        pformat = "%-25s = %s"
        puts('')
        for section in opts.sections:
            puts(colored.green("[%s]" % section))
            for key, kaio_value in opts.items(section):
                keycolor = colored.magenta(key)
                if key in user_settings:
                    keycolor = colored.blue(key)

                default_value = opts.options[key].default_value
                value = kaio_value or default_value

                if sys.version_info[0] < 3:
                    value = unicode(value).encode('utf8')
                else:
                    value = str(value)

                try:
                    puts(pformat % (keycolor, value))
                except Exception as e:
                    raise e
            puts('')
def _extract_archive(archive_file, container_folder):
    """Extract distribution archive into container_folder."""
    msg = ("""-> Extracting {0}\n""").format(archive_file.path())
    printer.unicode_safe(colored.magenta(msg, bold=True))
    with tarfile.open(name=archive_file.path()) as archive:
        extract_members = archive.getmembers()
        archive.extractall(members=extract_members, path=container_folder)
Example #47
0
def filescanner(topdir, jottapath, jfs, errorfile, exclude=None, dry_run=False, prune_files=True, prune_folders=True ):

    errors = {}
    def saferun(cmd, *args):
        log.debug('running %s with args %s', cmd, args)
        try:
            return apply(cmd, args)
        except Exception as e:
            puts(colored.red('Ouch. Something\'s wrong with "%s":' % args[0]))
            log.exception('SAFERUN: Got exception when processing %s', args)
            errors.update( {args[0]:e} )
            return False

    _files = 0

    try:
        for dirpath, onlylocal, onlyremote, bothplaces, onlyremotefolders in jottacloud.compare(topdir, jottapath, jfs, exclude_patterns=exclude):
            puts(colored.green("Entering dir: %s" % dirpath))
            if len(onlylocal):
                _start = time.time()
                _uploadedbytes = 0
                for f in progress.bar(onlylocal, label="uploading %s new files: " % len(onlylocal)):
                    if os.path.islink(f.localpath):
                        log.debug("skipping symlink: %s", f)
                        continue
                    log.debug("uploading new file: %s", f)
                    if not dry_run:
                        if saferun(jottacloud.new, f.localpath, f.jottapath, jfs) is not False:
                            _uploadedbytes += os.path.getsize(f.localpath)
                            _files += 1
                _end = time.time()
                puts(colored.magenta("Network upload speed %s/sec" % ( humanizeFileSize( (_uploadedbytes / (_end-_start)) ) )))

            if prune_files and len(onlyremote):
                puts(colored.red("Deleting %s files from JottaCloud because they no longer exist locally " % len(onlyremote)))
                for f in progress.bar(onlyremote, label="deleting JottaCloud file: "):
                    log.debug("deleting cloud file that has disappeared locally: %s", f)
                    if not dry_run:
                        if saferun(jottacloud.delete, f.jottapath, jfs) is not False:
                            _files += 1
            if len(bothplaces):
                for f in progress.bar(bothplaces, label="comparing %s existing files: " % len(bothplaces)):
                    log.debug("checking whether file contents has changed: %s", f)
                    if not dry_run:
                        if saferun(jottacloud.replace_if_changed, f.localpath, f.jottapath, jfs) is not False:
                            _files += 1
            if prune_folders and len(onlyremotefolders):
                puts(colored.red("Deleting %s folders from JottaCloud because they no longer exist locally " % len(onlyremotefolders)))
                for f in onlyremotefolders:
                    if not dry_run:
                        if saferun(jottacloud.deleteDir, f.jottapath, jfs) is not False:
                            logging.debug("Deleted remote folder %s", f.jottapath)
    except KeyboardInterrupt:
        # Ctrl-c pressed, cleaning up
        pass
    if len(errors) == 0:
        puts('Finished syncing %s files to JottaCloud, no errors. yay!' % _files)
    else:
        puts(('Finished syncing %s files, ' % _files )+
             colored.red('with %s errors (read %s for details)' % (len(errors), errorfile, )))
Example #48
0
def main():
    puts(colored.magenta("Welcome to your daily planner", bold=True))
    answers = prompt(question, style=custom_style_3)
    if answers['authentification'] == 'Register':
        response = register()
        if response.status_code == 200:
            puts(colored.magenta("Go to login", bold=True))
            login()
        else:
            message = response.content.decode('utf-8')
            puts(colored.red(message, bold=True))
            main()
    elif answers['authentification'] == 'Login':
        login()
    else:
        return
Example #49
0
    def delete(self):

        if self.dry_run:
            self.puts(
                colored.yellow(
                    ("\nYou are trying to delete this project's resources!\n"
                     "By default this command runs in dry-run mode. If you are ok \n"
                     "with the following resources being deleted, you can run this\n"
                     "command with --confirm to do the actual deletion.\n"
                     "\nNOTHING IS GOING TO BE DELETED!\n")
                )
            )
            self.puts(colored.blue("The following resources would be deleted..."))
        else:
            self.puts(colored.blue("Deleting project resources..."))

        context = self.get_initial_context()

        with indent(2):
            self.puts(colored.magenta("\nRegion:{Region}\nStage: {Stage}\n".format(**context)))

        for (number, name, filename, template_type) in self.steps():
            with indent(2):
                self.puts(colored.cyan("{} ({})".format(filename, template_type)))
            with indent(4):
                if self.debug:
                    self.puts(colored.white(u"✸ Delete template {} with context {}".format(filename, context)))
                getattr(self, 'delete_{}_template'.format(template_type))(name, filename, context)
Example #50
0
def find_request_id(profile, bucket, request_id):
    # pick a file to inspect
    session = boto3.Session(profile_name=profile)
    s3_client = session.client('s3')
    files = s3_client.list_objects_v2(Bucket=bucket, Prefix='cloudfront-log')
    args = arguments.Args()
    logs = [k['Key'] for k in files['Contents']]
    logs.reverse()
    for log in logs:
        s3obj = s3_client.get_object(Bucket=bucket, Key=log)
        with gzip.open(s3obj['Body'], 'rt') as f:
            responses = parse(f.readlines())
            for r in responses:
                if r.request_id == request_id:
                    puts("Found!")
                    puts(
                        columns(
                            [colored.green(r.http_method), 6],
                            [colored.red(r.status_code), 6],
                            [colored.red(r.edge_result_type), 10],
                            [colored.yellow(r.request_id), 56],
                            [colored.magenta(str(r.timestamp)), 20],
                            [colored.blue(r.path), None],
                        ))
                    exit(0)
Example #51
0
 def get_unprocessed_items(self, want_types=None, force_all=False):
     """Return new items we found"""
     wt = self.source_conf.get('want_types', 'upload,favorite').split(',')
     j = self._get_data()
     
     n_items     = 0
     max_items   = self.source_conf.getint('max_items', None)
     
     for obj in j['data']:
         t = obj['type']
         if t in wt:
             # pp = pprint.PrettyPrinter(indent=4)
             # pp.pprint(obj)
             funk = self.TYPE_MAP.get(t, None)
             if funk:
                 for mci in funk(self, obj):
                     ctime_epoch = float( mci.created_time.strftime("%s") )
                     if force_all or not self.metadata_db.is_processed(mci.key):
                         if n_items < max_items or max_items is None:
                             yield mci
                             n_items += 1  # Counting feed items, not cc's
                         else:
                             puts(colored.red("Ignored (> max_items): %s" % mci))
                     else:
                         if self.verbose:
                             puts(colored.red("Already processed: %s" % mci))
                 if max_items:
                     if not force_all:
                         if n_items == max_items:
                             puts(colored.magenta("Reached max_items of %d for %s" % (max_items, self.source_name)))
                         
             else:
                 puts_err(colored.red("Don't know how to handle requested type '%s'" % t))
Example #52
0
def list_existing_accounts():
    col = 20
    all_accounts = account_store.get_all_accounts()
    if len(all_accounts) == 0:
        puts(colored.red("There is no linked account yet."))
        return
    puts(colored.green("You have linked the following account(s) to onedrive-d:\n"))
    puts(
        columns(
            [(colored.red("Index")), 10],
            [(colored.magenta("Account ID")), col],
            [(colored.cyan("Account Type")), col],
            [(colored.green("Name")), None],
        )
    )
    account_list = []
    for id, account in all_accounts.items():
        puts(
            columns(
                [str(len(account_list)), 10],
                [account.profile.user_id, col],
                [account.TYPE, col],
                [account.profile.name, None],
            )
        )
        account_list.append(account)
    puts(colored.yellow("\nTo delete an account, type the index and hit [Enter]. Otherwise hit [Ctrl+C] to break."))
    puts(colored.yellow("Note: all the Drives belonging to the account will also be deleted."))
    puts()
    try:
        prompt_delete_account(account_list)
    except KeyboardInterrupt:
        puts(colored.green("Aborted."))
Example #53
0
    def printColor(self, msg, index=0):
        idx = int(int(self.id) % 7)
        preText = '   -[' + str(self.id) + ']'
        postText = ''
        colors = ['magenta', 'cyan', 'green', 'yellow', 'blue', 'red', 'white']

        if idx == 0:
            print(colored.magenta(preText + msg + postText))
        elif idx == 1:
            print(colored.cyan(preText + msg + postText))

        elif idx == 2:
            print(colored.green(preText + msg + postText))

        elif idx == 3:
            print(colored.yellow(preText + msg + postText))

        elif idx == 4:
            print(colored.blue(preText + msg + postText))

        elif idx == 5:
            print(colored.red(preText + msg + postText))

        elif idx == 6:
            print(colored.white(preText + msg + postText))
Example #54
0
    def handle_noargs(self, **options):
        # Inspired by Postfix's "postconf -n".
        from django.conf import settings, global_settings

        # Because settings are imported lazily, we need to explicitly load them.
        settings._setup()

        user_settings = module_to_dict(settings._wrapped)
        default_settings = module_to_dict(global_settings)

        opts = Options()
        from clint.textui import puts, colored
        pformat = "%30s: %-30s %-30s %-30s"
        puts('')
        puts(pformat %
             (colored.white('Option'), colored.cyan('APP Value'),
              colored.cyan('INI Value'), colored.green('APP Default')))
        puts('')
        for section in opts.sections:
            puts(pformat % (colored.green("[%s]" % section), '', '', ''))
            for key, kaio_value in opts.items(section):
                keycolor = colored.magenta(key)
                if key in user_settings:
                    value = colored.green(user_settings[key])
                    keycolor = colored.blue(key)
                else:
                    value = colored.green(
                        opts.options[key].get_value_or_default())

                default_value = opts.options[key].default_value
                kaio_value = kaio_value if kaio_value else repr(kaio_value)

                puts(pformat % (keycolor, clint_encode(value),
                                colored.white(clint_encode(kaio_value)),
                                clint_encode(default_value)))

            puts('')

        puts(
            colored.white(
                "No configurables directamente en INI (estáticos o compuestos por otros):"
            ))
        puts()

        not_configured = set(user_settings.keys()) - set(opts.keys())
        # not_configured = not_configured - set([
        #     'INSTALLED_APPS',
        #     'MIDDLEWARE_CLASSES',
        #     'CONTEXT_PROCESSORS',
        #     ])
        pformat = "%30s: %-50s"
        puts(pformat % (colored.white('Option'), colored.cyan('Value')))
        for key in sorted(not_configured):
            if key not in default_settings:
                puts(pformat % (colored.blue(key), user_settings[key]))
            elif user_settings[key] != default_settings[key]:
                puts(pformat % (
                    colored.blue(key), colored.green(user_settings[key])
                    # colored.white(default_settings[key])
                ))
def config_size():
    global file_size
    puts(colored.magenta('Enter number of lines of data to be collected: '))
    response = input()
    file_size = response
    
    update_file()
Example #56
0
def listen():
    print(colored.yellow("Getting files in directory"))
    path = os.getcwd()
    dircontents = os.listdir(path)
    if len(dircontents) != 0:
        print(colored.magenta("Currently listening for file changes"))
        patterns = "*"
        ignore_patterns = ""
        ignore_directories = False
        case_sensitive = True
        event_handler = PatternMatchingEventHandler(patterns, ignore_patterns,
                                                    ignore_directories,
                                                    case_sensitive)
        event_handler.on_modified = isModified
        observer = Observer()
        observer.schedule(event_handler, path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
        observer.join()
    else:
        print(colored.red("No files exist, check filename/path"))
def _extract_distro_archive(distro_archive_file, distro_folder):
    """Extract distribution archive into distro_folder."""
    with tarfile.open(name=distro_archive_file.path()) as archive:
        msg = ("""-> Extracting """
               """{0}\n""").format(os.path.relpath(distro_archive_file.path()))
        extract_members = [m for m in archive.getmembers() if not m.isdev()]
        printer.unicode_safe(colored.magenta(msg, bold=True))
        archive.extractall(members=extract_members, path=distro_folder)

        # Set the permissions of the extracted archive so we can delete it
        # if need be.
        os.chmod(distro_folder, os.stat(distro_folder).st_mode | stat.S_IRWXU)
        for root, directories, filenames in os.walk(distro_folder):
            for distro_folder_directory in directories:
                path = os.path.join(root, distro_folder_directory)
                try:
                    os.chmod(path, os.stat(path).st_mode | stat.S_IRWXU)
                except OSError:  # suppress(pointless-except)
                    pass
            for filename in filenames:
                path = os.path.join(root, filename)
                try:
                    os.chmod(path, os.stat(path).st_mode | stat.S_IRWXU)
                except OSError:  # suppress(pointless-except)
                    pass
 def _extract_qemu(qemu_deb_path, qemu_temp_dir):
     """Extract qemu."""
     printer.unicode_safe(
         colored.magenta(("""-> Extracting {0}\n"""
                          """""").format(qemu_deb_path),
                         bold=True))
     debian_package.extract_deb_data(qemu_deb_path, qemu_temp_dir)
Example #59
0
 def remove(conn, inp):
     # if we matched a package name, replace it with the pkg uuid
     pkg_data = conn.get_installed_package_data(verb)
     if inp in [p.name for p in pkg_data]:
         for pkg in pkg_data:
             if pkg.name == inp:
                 verb('replace {} with {}'.format(inp, pkg.uuid))
                 inp = pkg.uuid
                 break
     # if package removal fails or specified package is not installed on the robot
     if not conn.remove_package(inp) or inp not in completions:
         print('{}: package {} not installed on {}'.format(col.red('error'),
                                                           col.blue(inp),
                                                           col.magenta(conn.get_robot_name())))
     else:  # package successfully removed
         print('removed {} from {}'.format(col.blue(inp),
                                           col.magenta(conn.get_robot_name())))
Example #60
0
def error(mod, msg):
    if mod: mod = mod + ' '
    if not use_error:
        return
    if use_colored:
        puts("%s%s" % (colored.magenta("ERROR %s" % mod), msg))
    else:
        print "ERROR %s%s" % (mod, msg)