예제 #1
0
def libs():
    verb = input("Type in a verb: ")
    word_list.append(verb)

    noun = input("Type in a noun: ")
    word_list.append(noun)

    pronoun = input("Type in a pronoun: ")
    word_list.append(pronoun)

    adjective = input("Type in an adjective: ")
    word_list.append(adjective)

    print(red('verb:red'))
    print(green('noun:green'))
    print(blue('pronoun:blue'))
    print(yellow('adjective:yellow'))

    print("I {} some {} then I've seen {}. I didn't realize it's {}".format(
        red(verb), green(noun), blue(pronoun), yellow(adjective)))

    inputs = input('Enter R to show results: ')

    if inputs == 'r' or inputs == 'R':
        for list_item in word_list:
            print(magenta(list_item))
예제 #2
0
    def harvest_twitter(self, handle):
        """Function to lookup the provided handle on Twitter using Tweepy."""
        if self.twit_api is None:
            print(
                yellow(
                    "[*] Twitter API access is not setup, so skipping Twitter handle \
lookups."))
        else:
            # Drop the lonely @ Harvester often includes and common false positives
            if handle == '@' or handle == '@-moz-keyframes' or \
                handle == '@keyframes' or handle == '@media':
                print(
                    yellow("[*] Skipping dead end Twitter handle, {}".format(
                        handle)))
            else:
                try:
                    print(green("[+] Looking up {} on Twitter".format(handle)))
                    user_data = {}
                    user = self.twit_api.get_user(handle.strip('@'))
                    user_data['real_name'] = user.name
                    user_data['handle'] = user.screen_name
                    user_data['location'] = user.location
                    user_data['followers'] = user.followers_count
                    user_data['user_description'] = user.description

                    return user_data
                except Exception as error:
                    print(
                        red("[!] Error involving {} -- could be an invalid \
account.".format(handle)))
                    print(red("L.. Details: {}".format(error)))
예제 #3
0
def sms():
    os.system("clear")
    red()
    print(banner)
    purple()
    print("              |                    1 -->> Download Tool")
    print("              |                    2 -->> Execute Tool")
    print("              |                    3 -->> Exit")

    option = input("              +-> ")
    if option == "1":
        print("Downloading...")
        yellow()
        os.system("git clone https://github.com/Darkmux/SETSMS")
        red()
        print("Downloaded!")
        time.sleep(2)
        while True:
            sms()

    if option == "2":
        os.system("mv SETSMS/* .")
        os.system("chmod 777 SETSMS.sh")
        os.system("bash SETSMS.sh")

    if option == "3":
        start_menu()
예제 #4
0
 def print_data_statistics(data_loader, set_type):
     print(
         colors.yellow('{} images = {:,}'.format(
             set_type, len(data_loader.dataset.image_ids))))
     print(
         colors.yellow('{} annotations = {:,}'.format(
             set_type, len(data_loader.dataset.coco.anns))))
예제 #5
0
def session_parameters(tor=False,user_agent='',verbose=False,proxy=''):
	requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
	if proxy is not '' and tor:
		print colors.yellow('\b[**] ')+"Debe elegir solo una de las opciones, proxy o tor"
		sys.exit()
	if tor:
		p = commands.getoutput("ps -e|grep tor|wc -l")
		if '1' in p:
			os.system("sudo service tor restart")
		elif '0' in p:
			os.system("sudo service tor start")
		print colors.green('\b[*] ')+"Utilizando tor..."
		s = requesocks.Session()
		s.proxies = {'http':  'socks5://127.0.0.1:9050','https': 'socks5://127.0.0.1:9050'}
		if user_agent is not '':
			s.headers = {'User-agent':user_agent[:-1]}
			allow_redirects=False
		print colors.green('[*] ')+" Se asigno la IP: "+s.get('http://ipecho.net/plain').text+"\n" if verbose else '',
		s.verify=False
		return s
	if proxy is not '':
		s = requests.Session()
		s.proxies = s.proxies = {'http': proxy, 'https': proxy}
		if user_agent is not '':
			s.headers = {'User-agent':user_agent[:-1]}
			allow_redirects=False
		print colors.green('[*] ')+" Se esta utilizando la IP: "+s.get('http://ipecho.net/plain').text+"\n" if verbose else '',
		s.verify=False
		return s
	else:
		s = requests.Session()
		if user_agent is not '':
			s.headers = {'User-agent':user_agent[:-1]}
		s.verify=False
		return s
예제 #6
0
    def print_request(self, req, req_body):

        req_header_text = "%s %s %s\n%s" % (req.command, req.path,
                                            req.request_version, req.headers)

        print(yellow(req_header_text))

        if req_body is not '':
            req_body_text = ''
            content_type = req.headers.get('Content-Type', '')

            if content_type.startswith('application/x-www-form-urlencoded'):
                req_body_text = req_body.decode('utf-8')
            elif content_type.startswith('application/json'):
                try:
                    json_obj = json.loads(req_body.decode())
                    json_str = json.dumps(json_obj, indent=2)
                    if json_str.count('\n') < 50:
                        req_body_text = json_str
                    else:
                        lines = json_str.splitlines()
                        req_body_text = "%s\n(%d lines)" % ('\n'.join(
                            lines[:50]), len(lines))
                except ValueError:
                    try:
                        req_body_text = req_body.decode()
                    except UnicodeDecodeError:
                        print('can not decode the body request')
                        req_body_text = req_body
            elif len(req_body) < 1024:
                req_body_text = req_body.decode()
            if req_body_text:
                print(yellow(req_body_text))
예제 #7
0
def eviltrust():
    os.system("clear")
    red()
    print(banner)
    purple()
    print("              |                    1 -->> Download Tool")
    print("              |                    2 -->> Execute Tool")
    print("              |                    3 -->> Exit")

    option = input("              +-> ")
    if option == "1":
        print("Downloading...")
        yellow()
        os.system("git clone https://github.com/s4vitar/evilTrust")
        red()
        print("Downloaded!")
        time.sleep(2)
        while True:
            eviltrust()

    if option == "2":
        os.system("mv evilTrust/* .")
        os.system("clear")
        os.system("sudo bash evilTrust.sh -m terminal")

    if option == "3":
        start_menu()
예제 #8
0
def print_leaderbord(members, mode='star'):
    print ' '.ljust(28)+'  '.join(i for i in map(str, xrange(1, 10)))+' '+' '.join(i for i in map(str, xrange(10, 26))) + '  Total  Diff   G' + '\n'+'-'*120

    leaderboard_rank = sorted(members.itervalues(
    ), key=lambda y: y['local_score'], reverse=True)

    for j, member in enumerate(leaderboard_rank):
        if j == 0:
            top = member['local_score']
        if member['stars']:
            name = member['name'] if member['name'] else 'Anonymous'
            print str(j+1).ljust(2, ' ') + ' ' + name.ljust(24, ' '),
            for day in map(str, xrange(1, 26)):
                if day in member['completion_day_level']:
                    if mode == 'star':
                        if len(member['completion_day_level'][day].keys()) == 1:
                            print blue('~ ', bg='black'),
                        elif len(member['completion_day_level'][day].keys()) == 2:
                            print yellow('* ', bg='black'),
                    elif mode == 'pos':
                        pos = position_in_leaderboard(
                            leaderboard_rank, member['id'], day)
                        if pos:
                            if pos == '1':
                                print yellow(pos.ljust(2, ' ')),
                            elif pos in ['2', '3']:
                                print blue(pos.ljust(2, ' '), bg='black'),
                            else:
                                print pos.ljust(2, ' '),
                else:
                    print '  ',
            print str(member['local_score']).ljust(6, ' '),
            print str(top-member['local_score']).ljust(6, ' '),
            print member['global_score']
예제 #9
0
def phishing():
    os.system("clear")

    red()
    print(banner)
    purple()
    print("              |                    1 -->> Download Tool")
    print("              |                    2 -->> Execute tool")
    print("              |                    3 -->> Exit")
    x = input("              ↳ ")

    print("")
    if x == "1":

        yellow()
        os.system("git clone https://github.com/htr-tech/zphisher")
        print("")
        red()
        print("Downloaded!!")
        time.sleep(1)
        while True:
            phishing()

    if x == "2":
        print("")
        os.system("mv zphisher/* .")
        os.system("mv zphisher/.sites .")
        os.system("bash zphisher.sh")

    if x == "3":
        start_menu()
예제 #10
0
 def getMessages(self):
     messages = None
     try:
         messages = self.bot.getUpdates(self.lastMsgId, timeout=1)
     except:
         return []
     result = []
     lastId = self.lastMsgId
     for msg in messages:
         lastId = max(lastId, int(msg['update_id']) + 1)
         if 'message' not in msg:
             continue
         content = msg['message']
         sender = content.get('from', {}).get('username', None)
         text = content.get('text', None)
         if text:
             text = text[:100]
         if sender and text:
             result.append((sender, text))
             logPrint("%s sent telegram message: %s" %
                      (colors.yellow(sender), colors.yellow(text)))
     if self.lastMsgId < lastId:
         self.lastMsgId = lastId
         with open(self.lastMsgFileName, 'w') as lastMsgFile:
             lastMsgFile.write(str(lastId))
     return result
예제 #11
0
def ddos():
    os.system("clear")
    red()
    print(banner)
    purple()
    print("              |                    1 -->> Download Tool")
    print("              |                    2 -->> Execute tool")
    print("              |                    3 -->> Exit")
    x = input("              ↳ ")

    print("")
    if x == "1":
        yellow()
        print("")
        print("Downloading...")
        os.system(
            "curl https://raw.githubusercontent.com/yorkox0/exaple01/main/ddos.py -o ddos.py"
        )
        red()
        print("Downloaded!!")
        time.sleep(2)
        while True:
            ddos()

    if x == "2":
        print("")
        os.system("python3 ddos.py")

    if x == "3":
        start_menu()
예제 #12
0
    def __init__(self):
        """Everything that should be initiated with a new object goes here."""
        # Collect the API keys from the config file
        try:
            consumer_key = helpers.config_section_map("Twitter")["consumer_key"]
            consumer_key_secret = helpers.config_section_map("Twitter")["key_secret"]
            access_token = helpers.config_section_map("Twitter")["access_token"]
            access_token_secret = helpers.config_section_map("Twitter")["token_secret"]
            twit_auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
            twit_auth.set_access_token(access_token, access_token_secret)
            self.twit_api = tweepy.API(twit_auth)
        except Exception:
            self.twit_api = None
            print(yellow("[!] Could not setup OAuth for Twitter API."))

        try:
            self.emailhunter_api_key = helpers.config_section_map("EmailHunter")["api_key"]
        except Exception:
            self.emailhunter_api_key = ""
            print(yellow("[!] Could not fetch EmailHunter API key."))

        try:
            self.contact_api_key = helpers.config_section_map("Full Contact")["api_key"]
        except Exception:
            self.contact_api_key = ""
            print(yellow("[!] Could not fetch Full Contact API key."))
예제 #13
0
def prepare_domains_list(domain_metrics_obj, domain=None):
    """Function to prepare the list of domains to be enumerated. If a domain is provided, it will
    check if BloodHound has data for that domain. If no domain is provided, it will create a list
    of all domains in BloodHound for which data is available. A list of known domains missing data
    is produced as well.
    """
    if domain:
        all_domains = [domain]

        domain_check = domain_metrics_obj.get_all_domains()
        if not domain in domain_check:
            print(red("[X] No data is available for the specified domain!"))
            exit()
    else:
        all_domains = domain_metrics_obj.get_all_domains()
        all_domains_inc = domain_metrics_obj.get_all_domains(True)

        for domain in all_domains_inc:
            missing_data = []
            if not domain in all_domains:
                missing_data.append(domain)

        if missing_data:
            print(
                yellow(
                    "[!] The following domains were found in the dataset, but we don't have any \
    data for them! Run BloodHound on these domains:"))
            for domain in missing_data:
                print(yellow("\t* %s" % domain))

    return all_domains
예제 #14
0
파일: __main__.py 프로젝트: ximerus/pe-sort
def print_msg(code, msg):
    if code == -1:
        print red("[ERROR]\t" + msg)
    elif code == 1:
        print yellow("[WARNING]\t"+msg)
    else:
        print green("[INFO]\t" + msg)
예제 #15
0
def get_input(opt):
    while True:
        print("")
        background = input(
            yellow(
                "Input the Background Section (<= 100 words or leave empty):\n> "
            ))
        background = nltk.word_tokenize(background)
        if len(background) > 100:
            print(red("Too long, please keep it within 100 words."))
        else:
            break
    while True:
        print("")
        findings = input(
            yellow("Input the Findings Section (<= 500 words):\n> "))
        findings = nltk.word_tokenize(findings)
        if len(findings) > 500:
            print(red("Too long, please keep it within 500 words."))
        elif len(findings) < 2:
            print(red("Too short."))
        else:
            break
    print("")
    return background, findings
예제 #16
0
 def locate(self, target):
     self.target = target
     self.rawdata = pygeoip.GeoIP('GeoLiteCity.dat')
     try:
         self.data = self.rawdata.record_by_addr(self.target)
     except:
         self.data = self.rawdata.record_by_name(self.target)
     self.country = self.data['country_name']
     self.longi = self.data['longitude']
     self.lat = self.data['latitude']
     self.mymap = pygmaps.maps(self.lat, self.longi, 12)
     self.mymap.addpoint(self.lat, self.longi, "Target is near this area")
     self.mymap.draw('./target_location.html')
     print yellow("[!] Target: ") + red(str(self.target))
     print yellow("[x] Target's country: ") + red(str(self.country))
     print yellow("[x] Longitude: ") + red(str(self.longi))
     print yellow("[x] Latitude: ") + red(str(self.lat))
     print yellow('[x] Map of the location >') + red(
         '"target_location.html"')
     while True:
         self.o_map = raw_input(
             "Try to open target_location.html map in browser(y/ n):\n>"
         ).lower()
         if self.o_map.startswith('y'):
             try:
                 self.new = 2
                 webbrowser.open("target_location.html", new=self.new)
                 break
             except:
                 print '[!]Could not open map in web browser. Open "geo_trace.html" -file manually'
             break
         elif self.o_map.startswith('n'):
             break
예제 #17
0
 def regenerate(self, new_min_frequency):  # change threshold - convenience method ig
     """
     Regenerates the corpus with a non-default minimum word frequency
     :param new_min_frequency: the minimum number of times a word must appear in the corpus to be in the vocab
     """
     if new_min_frequency < 1:
         raise ValueError(colors.red("Word frequency threshold must be greater than 0"))
     print colors.yellow("regenerating vocab with required min frequency at %s...\n" % new_min_frequency)
     self.tokenizer.generate(self.handle, new_min_frequency)
예제 #18
0
def connectmysql(host1, user1, passwd1, db1):
    db = MySQLdb.connect(host=str(host1),
                         user=str(user1),
                         passwd=str(passwd1),
                         db=str(db1))
    cursor = db.cursor()
    print red(str(db))
    print yellow(str(cursor))
    return [db, cursor]
예제 #19
0
    def __init__(self):
        """Everything that should be initiated with a new object goes here."""
        # Collect the API keys from the config file
        try:
            consumer_key = helpers.config_section_map(
                "Twitter")["consumer_key"]
            consumer_key_secret = helpers.config_section_map(
                "Twitter")["key_secret"]
            access_token = helpers.config_section_map(
                "Twitter")["access_token"]
            access_token_secret = helpers.config_section_map(
                "Twitter")["token_secret"]
            twit_auth = tweepy.OAuthHandler(consumer_key, consumer_key_secret)
            twit_auth.set_access_token(access_token, access_token_secret)
            self.twit_api = tweepy.API(twit_auth)
        except Exception:
            self.twit_api = None
            print(yellow("[!] Could not setup OAuth for Twitter API."))

        try:
            self.emailhunter_api_key = helpers.config_section_map(
                "EmailHunter")["api_key"]
        except Exception:
            self.emailhunter_api_key = ""
            print(yellow("[!] Could not fetch EmailHunter API key."))

        try:
            self.contact_api_key = helpers.config_section_map(
                "Full Contact")["api_key"]
        except Exception:
            self.contact_api_key = ""
            print(yellow("[!] Could not fetch Full Contact API key."))

        try:
            self.chrome_driver_path = helpers.config_section_map(
                "WebDriver")["driver_path"]
            # Try loading the driver as a test
            browser = webdriver.Chrome(executable_path=self.chrome_driver_path)
            browser.close()
            print(green("[*] Chrome web driver test was successful!"))
        # Catch issues with the web driver or path
        except WebDriverException:
            self.chrome_driver_path = None
            print(
                yellow(
                    "[!] There was a problem with the specified Chrome web driver in your \
keys.config! Please check it. For now ODIN will try to use PhantomJS for HaveIBeenPwned."
                ))
        # Catch issues loading the value from the config file
        except Exception:
            self.chrome_driver_path = None
            print(
                yellow(
                    "[!] Could not load a Chrome webdriver for Selenium, so we will tryuse \
to use PantomJS for haveIBeenPwned."))
예제 #20
0
    def __init__(self):
        """Everything that should be initiated with a new object goes here."""
        # Collect the API keys from the config file
        try:
            shodan_api_key = helpers.config_section_map("Shodan")["api_key"]
            self.shoAPI = shodan.Shodan(shodan_api_key)
        except Exception:
            self.shoAPI = None
            print(yellow("[!] Did not find a Shodan API key."))

        try:
            self.cymon_api_key = helpers.config_section_map("Cymon")["api_key"]
            self.cyAPI = Cymon(self.cymon_api_key)
        except Exception:
            self.cyAPI = Cymon()
            print(
                yellow(
                    "[!] Did not find a Cymon API key, so proceeding without API auth."
                ))

        try:
            self.urlvoid_api_key = helpers.config_section_map(
                "URLVoid")["api_key"]
        except Exception:
            self.urlvoid_api_key = ""
            print(yellow("[!] Did not find a URLVoid API key."))

        try:
            self.contact_api_key = helpers.config_section_map(
                "Full Contact")["api_key"]
        except Exception:
            self.contact_api_key = None
            print(yellow("[!] Did not find a Full Contact API key."))

        try:
            censys_api_id = helpers.config_section_map("Censys")["api_id"]
            censys_api_secret = helpers.config_section_map(
                "Censys")["api_secret"]
            self.cenCertAPI = censys.certificates.CensysCertificates(
                api_id=censys_api_id, api_secret=censys_api_secret)
            self.cenAddAPI = censys.ipv4.CensysIPv4(
                api_id=censys_api_id, api_secret=censys_api_secret)
        except Exception:
            self.cenCertAPI = None
            self.cenAddAPI = None
            print(yellow("[!] Did not find a Censys API ID/secret."))

        try:
            self.chrome_driver_path = helpers.config_section_map(
                "WebDriver")["driver_path"]
        except Exception:
            self.chrome_driver_path = None
예제 #21
0
    def __init__(self, seeds):

        self.urlQueue=UrlQueue()

        if isinstance(seeds, str):
            self.urlQueue.addUnvisitedUrl(seeds)

        elif isinstance(seeds, list):
            for i in seeds:
                self.urlQueue.addUnvisitedUrl(i)

        print yellow("Add seeds {unvisitedUrl} site.".format( unvisitedUrl = \
            str(self.urlQueue.unVisited).lstrip('[').rstrip(']')))
예제 #22
0
def check_ssl(target):
    """Get SSL certificate information for the target IP address or domain."""
    # Return None because we can't navigate to a CIDR for SSL certificates
    if "/" in target:
        print(
            red("[!] Cannot get certicate information for a CIDR. \
Supply a single IP or domain and port."))
        return None
    else:
        try:
            ip, port = target.split(":")
        except:
            ip = target
            port = 443
        next
    try:
        print(yellow("Target:\t\t{}".format(ip)))
        print(yellow("Port:\t\t{}".format(port)))
        cert = ssl.get_server_certificate((ip, port))
    except Exception as error:
        # If it can't connect, then return nothing/fail
        print(yellow("[!] Could not connect or no certificate was found."))
        print(yellow("L.. Details: {}".format(error)))
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ssl_sock = ssl.wrap_socket(s)
        ssl_sock.connect((ip, port))
        peerName = ssl_sock.getpeername()
        print(yellow("Peer Name:\t{}:{}".format(peerName[0], peerName[1])))
        print(yellow("Ciphers:"))
        for c in ssl_sock.cipher():
            print(yellow("\t\t{}".format(c)))
        print(yellow("Version:\t{}".format(ssl_sock.version())))
    except Exception as error:
        print(red("[!] Viper failed to make an SSL wrapped socket!"))
        print(red("L.. Details: {}".format(error)))
    try:
        # Use OpenSSL to collect certificate information
        c = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        subj = c.get_subject()
        comp = subj.get_components()
        print(yellow("\nCertificate Details:"))
        for i in comp:
            print(
                yellow("{}\t\t{}".format(i[0].decode('ascii'),
                                         i[1].decode('ascii'))))
    except Exception as error:
        # If OpenSSL fails to get information, return nothing/fail
        print(red("[!] Viper failed to get the certfication information!"))
        print(red("L.. Details: {}".format(error)))
예제 #23
0
    def printChars():
        print('{:^20}|{:^14s}|{:^14s}|{:^14s}|'.format(colors.yellow('TYPE'),
                                                       colors.yellow('ATK'),
                                                       colors.yellow('DEF'),
                                                       colors.yellow('HP')))
        for chrtype in dictChar.keys():
            chrStats = dictChar[chrtype]

            print('{:^20}|{:^5d}|{:^5d}|{:^5d}|'.format(
                colors.cyan(chrtype), chrStats['atk'], chrStats['def'],
                chrStats['hp']))
        print()
        crclass = str(input("So, What are you?"))
        return crclass
예제 #24
0
def download_source (url, dir):
    """ Download a source package from a URL: tarball o repository"""

    # Cache directory
    cachedir = os.path.join (config.CACHE_DIRECTORY, "packages")

    # Check the cache
    if url.startswith("svn://"):
        did_checkout = False
        cache_file = "SVN-" + url[6:].replace('/','_') + '.tar.gz'
    else:
        cache_file = filter (lambda x: ((".tar.gz" in x) or (".tar.bz2" in x) or (".zip" in x)), url.split('/'))[0]

    exe ("mkdir -p %s" % (cachedir))
    cache_filepath = os.path.join (cachedir, cache_file)

    # Download if it doesn't already exist
    if not os.path.exists (cache_filepath):
        print ("%s: %s" %(colors.yellow("Cache miss"), url))

        if url.startswith("svn://"):
            exe ("svn checkout %s %s" % (url, dir))
            exe ("tar cfvz %s %s" % (cache_filepath, dir))
            did_checkout = True
        elif url.startswith("http://") or url.startswith("ftp://"):
            exe ("wget -q -O '%s' '%s'" % (cache_filepath, url), colorer=colors.green)
        else:
            assert False, "Don't know how to download %s" % (url)
    else:
        print ("%s: %s" %(colors.yellow("Cache hit"), cache_filepath))

    # Uncompress
    if url.startswith("svn://"):
        if not did_checkout:
            exe ("tar xfvz '%s'" % (cache_filepath), colorer=colors.green)
    elif ".bz2" in url:
        exe ("tar xfvj '%s'" % (cache_filepath), colorer=colors.green)
    elif (".tar.gz" in url) or (".tgz" in url):
        exe ("tar xfvz '%s'" % (cache_filepath), colorer=colors.green)
    elif ".zip" in url:
        exe ("unzip '%s'" % (cache_filepath), colorer=colors.green)
    else:
        assert False, "Don't know how to uncompress %s" % (url)

    # Patching
    patches = os.path.join (os.path.dirname (__file__), "patches")
    pkg_path = os.path.join (patches, "%s.diff" % (cache_file))
    if os.path.exists (pkg_path):
        exe ("patch -p0 < %s" % (pkg_path), colorer=colors.yellow)
예제 #25
0
def singledevicereadygroup():

    ivpid = request.args.get('ivpid')
    ip = paserip(str(ivpid))
    #print readyboards(str(ip)
    info = readyboards(str(ip), allencodergroup, alldecodergroup)
    k = info[0]
    all = k['Body']
    boardsgroup = [i for i in all.keys() if 'status' not in i]
    encoder = [d for d in boardsgroup if all[str(d)] in allencodergroup]
    decoder = [d for d in boardsgroup if all[str(d)] in alldecodergroup]
    print encoder, decoder
    finalgroup = {'encoder': encoder, 'decoder': decoder}
    print yellow(str(finalgroup))
    return json.dumps(finalgroup)
예제 #26
0
파일: fox.py 프로젝트: minkione/Fox
def group(self, domain):
    """
    Generate statistics for Active Directory groups, such as average group membership.
    """
    print(
        green("[+] Group Module Selected: Crunching group membership data..."))
    neo4j_driver = setup_database_conn()
    domain_metrics = domains.DomainData(neo4j_driver)
    group_metrics = groups.GroupMetrics(neo4j_driver)
    users_metrics = users.UserMetrics(neo4j_driver)

    if domain:
        all_domains = [domain]
    else:
        all_domains = domain_metrics.get_all_domains()

    for domain in all_domains:
        # We may get a 'None' domain if the label is missing in BloodHound
        if domain:
            print(green("[*] Domain: %s" % domain))

            avg_membership_nonrecur = group_metrics.get_avg_group_membership(
                domain)
            avg_membership_recur = group_metrics.get_avg_group_membership(
                domain, True)
            admin_groups = group_metrics.find_admin_groups(domain)
            local_admin = group_metrics.find_local_admin_groups(domain)
            foreign_groups = group_metrics.find_foreign_group_membership(
                domain)

            print(
                green("L.. Average group membership:\t\t\t%s" %
                      avg_membership_nonrecur))
            print(
                green("L.. Average recursive group membership:\t\t%s" %
                      avg_membership_recur))
            print(
                green("L.. Nested groups increased membership by:\t%s" %
                      float(avg_membership_recur - avg_membership_nonrecur)))
            print(green("L.. Admin groups:"))
            for group in admin_groups:
                print(yellow("\t%s" % group))
            print(green("L.. Non-Admin groups with Local Admin:"))
            for group in local_admin:
                print(yellow("\t%s" % group))
            print(green("L.. Groups with foregin group membership:"))
            for group, foreign_group in foreign_groups.items():
                print(yellow("\t%s -> %s" % (group, foreign_group)))
예제 #27
0
def print_problem(n, members):
    time_str = r"%Y-%m-%dT%H:%M:%S"
    print 'Problem', n.ljust(19), blue('  1st Star', bg='black'), yellow('    2nd Star', bg='black') + '\n' + '-'*51
    start_time = dt.strptime(event+'-12-' + n.zfill(2) + 'T05:00:00', time_str)

    data = []
    for member in members.itervalues():
        if n in member['completion_day_level']:
            t1, t2 = timedelta(days=1000), timedelta(days=1000)
            if '1' in member['completion_day_level'][n]:
                t1 = dt.utcfromtimestamp(
                    int(member['completion_day_level'][n]['1']['get_star_ts'])) - start_time
            if '2' in member['completion_day_level'][n]:
                t2 = dt.utcfromtimestamp(
                    int(member['completion_day_level'][n]['2']['get_star_ts'])) - start_time
            data.append((member, t1, t2))

    for j, (member, t1, t2) in enumerate(sorted(data, key=lambda x: (x[2], x[1]))):
        name = member['name'] if member['name'] else 'Anonymous'
        print str(j+1).ljust(2, ' ') + ' ' + name.ljust(24, ' '),
        if t1 != timedelta(days=1000):
            print ' ', str(t1).ljust(10, ' '),
        if t2 != timedelta(days=1000):
            print ' ', t2,
        print
예제 #28
0
파일: dzero.py 프로젝트: ab7/dzero
def get_chest():	
	global triangle
	global square
	global healthp
	global chest
	comb = ['2', '4', '1', '3']
	ans = []
	print "The chest is locked and has four colored switches on it:\n"
	print green("[1GREEN]"), yellow("[2YELLOW]"), red("[3RED]"), blue("[4BLUE]\n")
	for nums in comb:
		press = raw_input('Which switch should %s press? ' % name)
		ans.append(press)
	if ans == comb:
		pause('+++')
		print "The chest suddenly pops open! There is a hexagon key and a triangle key...\n"
		choo = raw_input('Which one should %s take? ' % name)
		if choo in ('t', 'triangle', 'the triangle'):
			pause('...')
			print "%s takes the triangle shaped key and the chest snaps shut!\n" % name
			triangle = True
			chest = False
		elif choo in ('h', 'hexagon', 'the hexagon'):
			pause('...')
			print "%s takes the hexagon shaped key and the chest snaps shut!\n" % name
			square = True
			chest = False
		else:
			pause('...')
			print "The chest snaps shut!\n"
			get_chest()
	else:
		print "\nThe chest shocks %s!" % name
		health(-10)
		room2()
예제 #29
0
def print_table(table):
    # Print colorized counts for each status
    # Do not print if count is 0
    headers = list()
    cells = list()
    global retval
    ths = table.find_all('th')
    tds = table.find_all('td')
    for th in ths:
        headers.append(th.getText())
    for td in tds:
        cells.append(td.getText())
    results = dict(zip(headers,cells))

    for key, val in results.items():
        if key in ("Up Ok") and val != "0":
            print "{0}: {1}".format(key, green(val))
        elif key in ("Down Critical") and val != "0":
            print "{0}: {1}".format(red(key), red(val))
            retval = 2
        elif key in ("Warning") and val != "0":
            print "{0}: {1}".format(key, yellow(val))
            retval = 1
        elif key in "Pending" and val != "0":
            print "{0}: {1}".format(key, val)
        elif key in ("Unreachable Unknown") and val != "0":
            print "{0}: {1}".format(key, val)
            retval = 3
        else:
            continue
예제 #30
0
def create_config_file():
    """
    Creates the config file in the home folder
    """

    config_location = os.path.expanduser("~") + "/.dotconfig"

    if not os.path.exists(config_location):
        data = """
        {
            "files" : {},
            "dot_path" : ""
        }
        """

        try:
            dotconfig = open(config_location, 'w')
            dotconfig.write(data)
            dotconfig.close()
            return True
        except IOError:
            sys.exit(
                colors.yellow("[ERROR]") + " not able to write to data file")
    else:
        return True
예제 #31
0
def warn(msg, exc_class, line=None):
    if TESTING:
        raise exc_class(msg) from None
    else:
        if line:
            msg = line_error(msg, line)
        print(yellow('WARNING:'), msg)
예제 #32
0
def eden():
    print(
        colors.yellow(
            "very well young adventurer. so to pass, Master Lord (a weird reader) offers you the way if you answer his riddle:"
        ))
    print("")
    riddleans = input(
        colors.cyan(
            "the riddle is: There was a plane crash and every single person died, who survived?:"
        ))
    badans = True
    while badans:
        if riddleans == "married people":
            print("very well. you now have entered the %s." %
                  (colors.red('EDEN')))
            break
        else:
            print("")
            print(
                "the answer is not correct you shall not be granted the %s." %
                (colors.red("WAY")))
            print(" ")
            print(" ")
            riddleans = input(
                colors.cyan(
                    "the riddle is: There was a plane crash and every single person died, who survived?:"
                ))
    import encounter
예제 #33
0
def check_option(cp, src, dst):
  def has_explicit_option(section, key):
    # David tried to avoid poking into cp's guts in https://rbcommons.com/s/twitter/r/1451/ but
    # that approach fails for the important case of boolean options.  Since this is a ~short term
    # tool and its highly likely its lifetime will be shorter than the time the private
    # ConfigParser_sections API we use here changes, it's worth the risk.
    if section == 'DEFAULT':
      # NB: The 'DEFAULT' section is not tracked via `has_section` or `_sections`, so we use a
      # different API to check for an explicit default.
      return key in cp.defaults()
    else:
      return cp.has_section(section) and (key in cp._sections[section])

  def sect(s):
    return cyan('[{}]'.format(s))

  src_section, src_key = src
  if has_explicit_option(src_section, src_key):
    if dst is not None:
      dst_section, dst_key = dst
      print('Found {src_key} in section {src_section}. Should be {dst_key} in section '
            '{dst_section}.'.format(src_key=green(src_key), src_section=sect(src_section),
                                    dst_key=green(dst_key), dst_section=sect(dst_section)),
            file=sys.stderr)
    elif src not in notes:
      print('Found {src_key} in section {src_section} and there is no automated migration path'
            'for this option.  Please consult the '
            'codebase.'.format(src_key=red(src_key), src_section=red(src_section)))

    if (src_section, src_key) in notes:
      print('  Note for {src_key} in section {src_section}: {note}'
            .format(src_key=green(src_key),
                    src_section=sect(src_section),
                    note=yellow(notes[(src_section, src_key)])))
예제 #34
0
파일: reporter.py 프로젝트: terncgod/ODIN
    def prepare_scope(self, scope_file, domain=None):
        """Function to split the user's scope file into IP addresses and domain names."""
        # Generate the scope lists from the supplied scope file, if there is one
        scope = []
        scope = self.DC.generate_scope(scope_file)

        if domain:
            # Just in case the domain is not in the scope file, it's added here
            if not any(domain in d for d in scope):
                print(yellow("[*] The provided domain, {}, was not found in your scope file, so \
it has been added to the scope for OSINT.".format(domain)))
                scope.append(domain)

        # Create lists of IP addresses and domain names from scope
        for item in scope:
            if helpers.is_ip(item):
                self.ip_addresses.append(item)
            elif item == "":
                pass
            else:
                self.domains_list.append(item)

        # Record the scope being used in the database
        self.c.execute('''CREATE TABLE 'ReportScope' ('Target' text)''')
        for target in scope:
            self.c.execute("INSERT INTO ReportScope VALUES (?)", (target,))
            self.conn.commit()

        return scope, self.ip_addresses, self.domains_list
예제 #35
0
def check_option(cp, src, dst):
  def has_explicit_option(section, key):
    # David tried to avoid poking into cp's guts in https://rbcommons.com/s/twitter/r/1451/ but
    # that approach fails for the important case of boolean options.  Since this is a ~short term
    # tool and its highly likely its lifetime will be shorter than the time the private
    # ConfigParser_sections API we use here changes, it's worth the risk.
    if section == 'DEFAULT':
      # NB: The 'DEFAULT' section is not tracked via `has_section` or `_sections`, so we use a
      # different API to check for an explicit default.
      return key in cp.defaults()
    else:
      return cp.has_section(section) and (key in cp._sections[section])

  def sect(s):
    return cyan('[{}]'.format(s))

  src_section, src_key = src
  if has_explicit_option(src_section, src_key):
    if dst is not None:
      dst_section, dst_key = dst
      print('Found {src_key} in section {src_section}. Should be {dst_key} in section '
            '{dst_section}.'.format(src_key=green(src_key), src_section=sect(src_section),
                                    dst_key=green(dst_key), dst_section=sect(dst_section)),
            file=sys.stderr)
    elif src not in notes:
      print('Found {src_key} in section {src_section} and there is no automated migration path'
            'for this option.  Please consult the '
            'codebase.'.format(src_key=red(src_key), src_section=red(src_section)))

    if (src_section, src_key) in notes:
      print('  Note for {src_key} in section {src_section}: {note}'
            .format(src_key=green(src_key),
                    src_section=sect(src_section),
                    note=yellow(notes[(src_section, src_key)])))
예제 #36
0
파일: go_go.py 프로젝트: lclementi/pants
    def execute(self, **kwargs):
        # NB: kwargs are for testing and pass-through to underlying subprocess process spawning.

        go_targets = OrderedSet(target for target in self.context.target_roots
                                if self.is_go(target))
        args = self.get_passthru_args()
        if not go_targets or not args:
            msg = (yellow(
                'The pants `{goal}` goal expects at least one go target and at least one '
                'pass-through argument to be specified, call with:\n') +
                   green('  ./pants {goal} {targets} -- {args}').format(
                       goal=self.options_scope,
                       targets=(green(' '.join(t.address.reference()
                                               for t in go_targets)) if
                                go_targets else red('[missing go targets]')),
                       args=green(' '.join(args))
                       if args else red('[missing pass-through args]')))
            raise self.MissingArgsError(msg)

        go_path = OrderedSet()
        import_paths = OrderedSet()
        for target in go_targets:
            self.ensure_workspace(target)
            go_path.add(self.get_gopath(target))
            import_paths.add(target.import_path)

        self.execute_with_go_env(os.pathsep.join(go_path), list(import_paths),
                                 args, **kwargs)
예제 #37
0
파일: Dir.py 프로젝트: brainysmurf/pydir
    def post_process(self, this, num, max_length):
        """
        Colorizes items in print display
        (1) Makes most recently modified item cyan
        (2) Any directory yellow
        (3) Symlinks green
        (4) Files are left unchanged
        """
        verbose = False
        verbose and print("in post process: {}".format(this))
        item = str(this)
        if not this.is_mounted:
            strikeout = '☓' * len(str(num))
            return (strikeout, green(item))

        if this.default and this.force_default:
            return ( cyan(num), cyan(item) )

        if this.default:
            return ( cyan(num), cyan(item) )

        if this.is_directory:
            return ( num, yellow(item) )

        if this.is_link:
            return ( num, green(item) )
        else:
            # is file
            pass

        ffile, ext = os.path.splitext(item) 
        if ext:
            return ( num, green(ffile + ext) )
        else:
            return ( num, green(item) )
예제 #38
0
파일: isearch.py 프로젝트: fpcsong/iSearch
def colorful_print(raw):

    # print colorful text in terminal.

    lines = raw.split('\n')
    colorful = True
    detail = False
    for line in lines:
        if line:
            if colorful:
                colorful = False
                print(white(line, bg='green') + '\n')
                #                print(colored(line, 'white', 'on_green')+'\n')
                continue
            elif line.startswith('例'):
                print(line + '\n')
                continue
            elif line.startswith('【'):
                print(white(line, bg='green') + '\n')
                #                print(colored(line, 'white', 'on_green')+'\n')
                detail = True
                continue

            if not detail:
                print(yellow(line + '\n'))
#                print(colored(line+'\n', 'yellow'))
            else:
                print(blink(line) + '\n')
예제 #39
0
파일: parse_expr.py 프로젝트: DTSCode/rpn
def parse_expr(expr):
    tokens_list = []
    tokens = []
    token_val = ""
    last_token = None

    for elem in expr:
        if elem in operator_table.ops and elem != "@":
            if token_val != "":
                tokens.append(token_val)
                token_val = ""

            if elem == "-" and (last_token in operator_table.ops or last_token == None):
                tokens.append("-1")
                tokens.append("@")
                last_token = "a"
                pass

            elif elem == "+" and (last_token in operator_table.ops or last_token == None):
                tokens.append("1")
                tokens.append("@")
                last_token = "a"
                pass

            else:
                tokens.append(elem)

        elif elem in " \t\n":
            if token_val != "":
                tokens.append(token_val)
                token_val = ""

        elif elem.isdigit() or elem.isalpha() or elem in "_.":
            token_val = token_val + elem

        elif elem == "#":
            break

        elif elem == ";":
            if token_val != "":
                tokens.append(token_val)

            tokens_list.append(tokens)
            tokens = []
            token_val = ""
            last_token = None

        else:
            print colors.red("(error) token {") + colors.yellow(elem) + colors.red("} is not a valid token")
            return []

        last_token = elem

    if token_val != "":
        tokens.append(token_val)
        token_val = ""

    tokens_list.append(tokens)
    return tokens_list
예제 #40
0
def print_title(string):
    # Colorize title based on retval
    if retval == 0:
        string = green(string)
    elif retval == 2:
        string = red(string)
    else:
        string == yellow(string)
    print bold(string)
예제 #41
0
파일: keys.py 프로젝트: pasalo/common
def create (key_id, key_dir, download_dir, public_url=None):
    re_fp = os.path.join(CACHE_KEYS_DIR, key_id)

    # Reuse
    if os.path.exists(re_fp):
        print (colors.yellow(" * Reusing keys from %s" %(re_fp)))
        shutil.copytree (re_fp, key_dir)
        return

    # Create
    print (colors.yellow(" * Creating key %s"%(key_id)))
    util.pasalo_init_path (key_dir, downloads=download_dir, public_url=public_url)

    # Populate cache
    print (colors.yellow(" * Copying key %s to QA cache: %s -> %s"%(key_id, key_dir, re_fp)))
    if not os.path.exists (CACHE_KEYS_DIR):
        os.makedirs (CACHE_KEYS_DIR, 0700)
    shutil.copytree (key_dir, re_fp)
예제 #42
0
    def display_history_version(self):
        try:
            sftp = self.connection.open_sftp()
            try:
                dirlist = sftp.listdir(self.server_info['remote_path'])
                for item in dirlist:
                    print "远程服务器已部署版本: ", green(item)
            except IOError:
                print yellow("assume %s folder is not exists. Please upload first") \
                      % self.server_info['remote_path']

        except Exception as e:
            print ('*** caught exception: %s: %s' % (e.__class__, e))
            traceback.print_exc()
            # try:
            #     sftp.close()
            # except:
            #     pass
            sys.exit(1)
예제 #43
0
        def internal_uploads(*args):
            try:
                sftp = self.connection.open_sftp()
                for dirpath, dirname, filenames in os.walk(top_path):
                    remote_path = os.path.join(self.server_info['remote_path'],
                                               self.server_info['release_version'],
                                               dirpath[len(top_path)+1:])
                    try:
                        sftp.listdir(remote_path)     # Test if remote folder exists
                    except IOError:
                        dir_path, base_name = os.path.split(remote_path.rstrip('/'))
                        try:
                            sftp.mkdir(dir_path)     # Create remote folder
                        except IOError:
                            print yellow("assume %s create success or target folder exists.") % dir_path
                        try:
                            sftp.mkdir("%s/%s" % (dir_path, base_name))
                        except IOError:
                            print yellow("assume %s/%s create sucess or folder already exists.") % \
                                  (dir_path, base_name)
                    for filename in filenames:
                        if sftp.put(os.path.join(dirpath, filename), os.path.join(remote_path, filename)):
                            print "Upload %s to %s %s " % \
                                  (filename, self.server_info['hostname'],
                                   remote_path), green("success")
                        else:
                            print "Upload %s to %s %s " % \
                                  (filename, self.server_info['hostname'],
                                   remote_path), red("failed")
                sftp.close()

            except Exception as e:
                print('*** Caught exception: %s: %s' % (e.__class__, e))
                traceback.print_exc()
                # try:
                #     sftp.close()
                # except:
                #     pass
                sys.exit(1)
            print green("%s upload success" % top_path)
예제 #44
0
  def __printBranchHealthChart(self, aBranchMap, aStream):
    """
    Print out a 'health chart' of different branches and when they were last
    changed. The health chart will color the given branches such that:
        - Branches with last activity longer than double the number of 'healthy
          days' ago will be colored in RED.
        - Branches with last activity longer than the number of 'healthy days'
          ago will be colored in YELLOW.
        - All other branches will be colored in GREEN

    :param aBranchMap: A list of Branch objects. Note that this list is assumed to
                       be pre-sorted in the order in which they should be output.
    :param aStream: An output stream to print the data to.
    """

    config = self.getConfig()
    badOnly = config.getBadOnly()
    noColor = not config.shouldUseColor()

    log = config.getLog()

    deleteBucket = []
    for someBranch in aBranchMap:
      branchPath = someBranch.getPath()
      branchHealth = someBranch.getHealth()
      lastActivityRel = someBranch.getLastActivityRelativeToNow()

      # If this is an unhealthy branch, then let's put it in the "delete"
      # bucket.
      if branchHealth == Branch.OLD:
        deleteBucket.append(someBranch)

      # Skip healthy and aged branches if we're only looking for bad ones
      if badOnly and not branchHealth == Branch.OLD:
        continue

      if not noColor:
        if branchHealth == Branch.HEALTHY:
          coloredDate = green(lastActivityRel)
        elif branchHealth == Branch.AGED:
          coloredDate = yellow(lastActivityRel)
        else:
          coloredDate = red(lastActivityRel)
      else:
          coloredDate = lastActivityRel

      alignedPrintout = '{0:40} {1}\n'.format(branchPath + ":", coloredDate)
      aStream.write(alignedPrintout)

    if config.shouldDeleteOldBranches():
      manager = BranchManager(config)
      manager.deleteAllOldBranches(deleteBucket)
예제 #45
0
파일: util.py 프로젝트: qix/j.yud.co.za
def proceed(message=DEFAULT_MESSAGE, default=True):
  answers = {
    'y': True,
    'yes': True,
    'n': False,
    'no': False,
    '': default,
  }
  default_text = {False: 'n', True: 'y'}[default]

  # Allow auto_proceed environment flag
  if os.environ.get('AUTO_PROCEED'):
    print yellow('Auto-proceed:', bold=True), message
    print yellow('Taking default option:'), yellow(default_text, bold=True)
    return default

  suggestion = ' [y/n]'
  result = prompt(message + suggestion).strip().lower()
  while not result in answers:
    print red('Could not interpret answer: '), repr(result)
    result = prompt(message + suggestion).strip().lower()
  return answers[result]
예제 #46
0
파일: app.py 프로젝트: vuonghv/letgithub
def main():
    current_dir = os.path.dirname(os.path.abspath(__file__))
    default_conf_file = os.path.join(current_dir, 'config.json')
    theme_file = os.path.join(current_dir, 'themes', 'dracula.json')
    obj = load_config(default_conf_file)
    config.update(obj)
    theme = load_config(theme_file)
    config.update({'THEME': theme})
    users.authenticate_user()
    while True:
        try:
            promt = color(config['THEME']['PROMT'])(config['PROMT_MSG'])
            data = input(promt).strip()
        except EOFError:
            print()
            continue
        except KeyboardInterrupt:
            sys.exit(yellow('\nGoodbye, see you. :)'))
        except Exception:
            continue

        if data == 'q':
            utils.quit(yellow('Bye, see you. :)'), EXIT_SUCCESS)

        try:
            args = data.split()
            cmd = args[0]
            COMMANDS[cmd](*args[1:])
        except (KeyError, ValueError):
            print(red('Command `{}` not found!'.format(data)))
        except (IndexError, KeyboardInterrupt):
            pass
        except TypeError:
            print(red('Sorry, I can\'t understand.'))
        except NotImplementedError:
            utils.perr(red('command hasn\'t implemented yet!'))
        except Exception as err:
            utils.perr(red(err))
예제 #47
0
파일: util.py 프로젝트: qix/j.yud.co.za
  def _task(*args, **kw):
    with settings(hide('running'), warn_only=True, parallel=True):
      results = execute(_per_machine, *args, **kw)

      errors = {
        server: result for server, result in results.items()
        if result != True
      }

      if errors:
        print red('There were %d failures:' % len(errors), bold=True)
        for (server, result) in errors.items():
          print '* %s: %s' % (server, repr(result))

        # Remove all the failed hosts so future commands don't run on them
        failed_hosts = errors.keys()
        env.hosts = [host for host in env.hosts if host not in failed_hosts]

        if len(errors) < len(results):
          okay = len(results) - len(errors)
          print yellow('The remaining %d hosts were successful' % okay, bold=True)
      else:
        print green('Success on %d hosts' % len(results), bold=True)
예제 #48
0
def check_config_file(path):
  cp = Config.create_parser()
  with open(path, 'r') as ini:
    cp.readfp(ini)
  config = SingleFileConfig(path, cp)

  print('Checking config file at {0} for unmigrated keys.'.format(path), file=sys.stderr)
  def section(s):
    return cyan('[{0}]'.format(s))

  for (src_section, src_key), dst in migrations.items():
    def has_explicit_option(section, key):
      # David tried to avoid poking into cp's guts in https://rbcommons.com/s/twitter/r/1451/ but
      # that approach fails for the important case of boolean options.  Since this is a ~short term
      # tool and its highly likely its lifetime will be shorter than the time the private
      # ConfigParser_sections API we use here changes, its worth the risk.
      return cp.has_section(section) and (key in cp._sections[section])

    if has_explicit_option(src_section, src_key):
      if dst is not None:
        dst_section, dst_key = dst
        print('Found {src_key} in section {src_section}. Should be {dst_key} in section '
              '{dst_section}.'.format(src_key=green(src_key), src_section=section(src_section),
                                      dst_key=green(dst_key), dst_section=section(dst_section)),
                                      file=sys.stderr)
      elif (src_section, src_key) not in notes:
        print('Found {src_key} in section {src_section} and there is no automated migration path'
              'for this option.  Please consult the '
              'codebase.'.format(src_key=red(src_key), src_section=red(src_section)))

      if (src_section, src_key) in notes:
        print('  Note: {0}'.format(yellow(notes[(src_section, src_key)])))

  # Check that all values are parseable.
  for sec in ['DEFAULT'] + cp.sections():
    for key, value in cp.items(sec):
      value = value.strip()
      if value.startswith('['):
        try:
          custom_types.list_type(value)
        except ParseError:
          print('Value of {key} in section {section} is not a valid '
                'JSON list.'.format(key=green(key), section=section(sec)))
      elif value.startswith('{'):
        try:
          custom_types.dict_type(value)
        except ParseError:
          print('Value of {key} in section {section} is not a valid '
                'JSON object.'.format(key=green(key), section=section(sec)))
예제 #49
0
def download (url, cachedir=config.CACHE_DIRECTORY, headers=[], agent=None, verbose=False):
    """ Download a file, using the cache """
    # Filename
    filename = url.split('/')[-1]

    # Check cache
    exe ("mkdir -p %s" % (cachedir))
    cache_filepath = os.path.join (cachedir, filename)

    # Parameters
    params = ''

    if not verbose:
        params += "-q "

    params += ' '.join (['--header="%s"'%(x) for x in headers]) + ' '
    if agent:
        params += '-U "%s" ' % (agent)

    if not os.path.exists (cache_filepath):
        print ("%s: %s" %(colors.yellow("Cache miss"), url))
        exe ("wget %s -O '%s' '%s'" % (params, cache_filepath, url), colorer=colors.green)
    else:
        print ("%s: %s" %(colors.yellow("Cache hit"), cache_filepath))
예제 #50
0
def main(args):
    """Main method

    :param args: arguments
    :return: None
    """
    opts = parse_cmdline_params(args[1:])
    if opts.b is not None and opts.l is not None:
        nb = True
    else:
        nb = False
    sequences = cloning(opts.fastq, opts.n, nb, opts.b, opts.l)
    # sequences = create_fastq_dict('sampleFastq')
    total_error_num = 0
    total_errors = 0
    total_lengths = 0
    for key in sequences:
        error_seq_string = ''
        seq_name = key
        seq_string = sequences[key]

        position = 0
        error_num = 0
        for base in seq_string:
            if base not in 'AGCTN':
                raise ValueError("This base,", base, ", is not an A, G, C, T, or N!")
            position += 1
            error_prob = 0.001 * position
            if error_prob * 100 <= 0:
                raise ValueError("The error probability must be greater than 0!")
            # Checks if it needs to add an error
            if random.randint(1, 1000) < (error_prob) * 1000:
                error_seq_string = add_error(error_seq_string, base, True)
                error_num += 1
            else:
                error_seq_string = add_error(error_seq_string, base, False)
        total_errors += error_num
        total_error_num += 1
        error_perc = error_num / len(seq_string)
        total_lengths += len(seq_string)
        print_errors(blue(seq_name), seq_string, error_seq_string, green(str(error_num)))
        print 'The error percent for this sequence is:', yellow(str(error_perc * 100)), '%'
        print 'The new quality string is:            ', create_quality_scores(seq_string), '\n'
    print 'The average number of errors generated was:' \
          '', magenta(str(int(total_errors / total_error_num)))
    print 'The total error percentage is:', magenta(str(total_errors / total_lengths * 100)), '%'
예제 #51
0
def list_items(csvfile):
    my_todo = open(csvfile, "r")
    lines = csv.reader(my_todo, delimiter = "|")

    print(' Priority:  Description:       Deadline: '  )
    for index, line in enumerate(lines):
        print()
        pr_color = line[0] # szinezéshez
        if line[0] == "  High   ":
            print(index+1, red(line[0]), line[1], line[2])
        elif line[0] == " Medium  ":
            print(index+1, yellow(line[0]), line[1], line[2])
        else:
            print(index+1, line[0], line[1], line[2])

    print()
    print()
    my_todo.close()
예제 #52
0
파일: corrin.py 프로젝트: Nirubi/corrin
    def __print_result(self, results, inst_count, error_count, elapsed_sum, cross_print=False):
        def __print_table(results, encoding="gbk"):
            res_table = prettytable.PrettyTable(["Num", "Instance", "Elapsed", "Result"])
            res_table.align["Result"] = "l"
            res_table.align["Instance"] = "l"
            res_table.align["Elapsed"] = "l"
            res_table.padding_width = 1
            res_table.encoding = encoding
            num = 0
            for result in results:
                num += 1
                if result is None or not isinstance(result, ExecuteOut):
                    continue
                if result.succeed:
                    color = "cyan"
                else:
                    color = "red"
                res_table.add_row([num,
                                   str(result.instance) if result.succeed else colors.red(str(result.instance)),
                                   datetime.timedelta(seconds=result.elapsed),
                                   result.result if result.succeed else colors.red(str(result.result))
                ])
            print res_table

        def __print_cross(results, encoding="gbk"):
            num = 0
            for result in results:
                num += 1
                if result is None or not isinstance(result, ExecuteOut):
                    continue
                print "Num:%5s [%40s] Elapsed:%20s" % (num,
                                                       result.instance if result.succeed else colors.red(
                                                           str(result.instance)),
                                                       datetime.timedelta(seconds=result.elapsed))
                print colors.green(str(result.result)) if result.succeed else colors.red(str(result.result))


        print "Count/Error: %s/%s     Elapsed: %s" % (colors.yellow(str(inst_count)),
                                                      colors.red(str(error_count)),
                                                      datetime.timedelta(seconds=elapsed_sum))
        if cross_print:
            __print_cross(results, self.encoding)
        else:
            __print_table(results, self.encoding)
예제 #53
0
파일: dzero.py 프로젝트: ab7/dzero
def leftroom():
	global tri
	repeatlr = '''The room is pitch dark. %s feels along the walls to find the room is in 
the shape of a triangle, doesn't appear to have a door besides the one 
%s came in and has small knobs on each of the walls.\n''' % (name, name)
	stEP = raw_input(prompt)
	if stEP == 'b':
		pause('^^^')
		backpack()
		if flash == True:
			pause(bold(yellow('(oo)')))
			print "%s flashes the light around the room, the knobs light up and a door" % name
			print "appears on the floor. A gigantic muscular imp crawls out and starts"
			print "moving towards %s!\n" % name
			fight('Giant Imp', 300, 4, 11)
			pause('{}{}{}')
			print "The Giant Imp melts into a triangle shaped shield and the door slowly"
			print "starts sliding open..."
			pause('+++')
			print "%s recieves %s!\n" % (name, bold('tri shield'))
			bp.append('tri shield')
			tri = 1
			print'''%s slowly walks into the room. There are candles lit and jars with 
strange bits of flesh and body parts in them. There is a door in 
the back and a chest in the middle of the room.\n''' % name
			bossroom()
		else:	
			leftroom()
	elif stEP in ('h', 'H', 'help'):
		pause('...')
		help()
		leftroom()
	elif stEP == 'l':
		pause('...')
		print repeatlr
		leftroom()
	elif stEP in ('inspect knobs', 'knobs', 'inspect the knobs'):
		pause('...')
		print "%s touches one of the knobs, its feels like some sort of prism..." % name
		pause('...')
		leftroom()
	else:
		print repeatlr
		leftroom()
예제 #54
0
    def process(self):

        visitUrl = self.urlQueue.unVisitedUrlDeQuence()
        print yellow("\nProcessing Url: {url}".format(url=visitUrl))

        print "Get Hyper Links:"
        links = self.getHyperLinks(visitUrl)
        print yellow("\nGet {linkno} new links".format(linkno = len(links)))

        print yellow("\nAdding url: {url} to VisitedQueue".format(url=visitUrl))
        self.urlQueue.addVisitedUrl(visitUrl)

        print yellow("\nVisited url count: {count}".format(count = \
            str(self.urlQueue.getVisitedUrlCount())))

        for link in links:
            print "\nAdding new link {link_name} to UnvisitedUrlQueue."\
                .format(link_name = green(link))
            self.urlQueue.addUnvisitedUrl(link)

        print "\nHave %d unvisited links" % len(self.urlQueue.getUnvisitedUrl())
예제 #55
0
def printBranchHealthChart(aBranchMap, aOptions):
  (badOnly) = aOptions

  for branchTuple in aBranchMap:
    (branchName, lastActivityRel, branchHealth) = branchTuple

    # Skip healthy and aged branches if we're only looking for bad ones
    if badOnly and not branchHealth == OLD:
      continue

    if branchHealth == HEALTHY:
      coloredDate = green(lastActivityRel)
    elif branchHealth == AGED:
      coloredDate = yellow(lastActivityRel)
    else:
      coloredDate = red(lastActivityRel)

    alignedPrintout = '{0:40} {1}'.format(branchName + ":", coloredDate)
    print(alignedPrintout)
예제 #56
0
파일: __main__.py 프로젝트: jsirois/pex
  def _find_literal_node(statement, call_argument):
    # The list of identifiers is large and they represent disjoint types:
    #   'StringNode'
    #   'BinaryStringNode'
    #   'RawStringNode'
    #   'InterpolatedRawStringNode'
    #   ...
    # Instead of trying to keep track of that, since we're specialized to the context of __import__,
    # Just accept any LiteralyEvaluable node (a mixin the above all implement) that python
    # accepts - except NameNode which we don't want and whose existence as a LiteralyEvaluable is
    # questionable to boot. In other words, we do not want to attempt to transform:
    #   variable = 'bob'
    #   __import__(variable, ...)
    # We just accept we'll miss more complex imports like this and have to fix by hand.

    if isinstance(call_argument.value, NameNode):
      print(yellow('WARNING: Skipping {}'.format(statement)), file=sys.stderr)
    elif isinstance(call_argument.value, LiteralyEvaluable):
      return call_argument.value
예제 #57
0
def check_option(cp, src, dst):
    def has_explicit_option(section, key):
        # David tried to avoid poking into cp's guts in https://rbcommons.com/s/twitter/r/1451/ but
        # that approach fails for the important case of boolean options.  Since this is a ~short term
        # tool and its highly likely its lifetime will be shorter than the time the private
        # ConfigParser_sections API we use here changes, its worth the risk.
        if section == "DEFAULT":
            # NB: The 'DEFAULT' section is not tracked via `has_section` or `_sections`, so we use a
            # different API to check for an explicit default.  The defaults are a combination of both
            # 'DEFAULT' section values and defaults passed to the ConfigParser constructor, but we
            # create the `cp` config parser below explicitly with no constructor defaults so this check
            # works.
            return key in cp.defaults()
        else:
            return cp.has_section(section) and (key in cp._sections[section])

    def section(s):
        return cyan("[{0}]".format(s))

    src_section, src_key = src
    if has_explicit_option(src_section, src_key):
        if dst is not None:
            dst_section, dst_key = dst
            print(
                "Found {src_key} in section {src_section}. Should be {dst_key} in section "
                "{dst_section}.".format(
                    src_key=green(src_key),
                    src_section=section(src_section),
                    dst_key=green(dst_key),
                    dst_section=section(dst_section),
                ),
                file=sys.stderr,
            )
        elif src not in notes:
            print(
                "Found {src_key} in section {src_section} and there is no automated migration path"
                "for this option.  Please consult the "
                "codebase.".format(src_key=red(src_key), src_section=red(src_section))
            )

        if (src_section, src_key) in notes:
            print("  Note: {0}".format(yellow(notes[(src_section, src_key)])))
def get_from_multiplechoice(options, message_when_failing):
    """Show the options and let the user choose"""
    if len(options) is 0:
        print yellow(message_when_failing)
        abort()
    if len(options) is 1:
        # check how certain we are
        if options[0]['similarity'] > 0.9:
            return options[0]['dirname']
        # no good enough match found, show the failing message
        print ""  # create some space
        print yellow(message_when_failing)
        print "Is the following name correct?"
        print_options(options)
        answer = raw_input("Y/n/a: ")
        if answer == "" or answer.lower() == "y":
            print magenta("Option " + options[0]['dirname'] + " chosen")
            return options[0]['dirname']
        if answer.lower() == "n" or answer.lower() == "a":
            abort()
        # no option chosen, lets retry
        print red("No valid answer given")
        return get_from_multiplechoice(options, message_when_failing)

    # multiple possible options, display the message and give the options
    print ""  # create some space
    print yellow(message_when_failing)
    print "Choose one of the following:"
    # sort the options
    options = sorted(options, key=lambda k: k['similarity'], reverse=True)
    print_options(options, True)
    answer = raw_input("Enter a number or press enter for the default (1): ")
    if answer.lower() == "a":
        abort()
    else:
        if not answer:
            answer = 1  # the default
        if not str(answer).isdigit():
            print red("Answer not recognized")
            return get_from_multiplechoice(options, message_when_failing)

        answer = int(answer)
        if len(options) > answer-1:
            print magenta("Option " + options[0]['dirname'] + " chosen")
            return options[0]['dirname']
        else:
            print 'Answer out of bounds'
            return get_from_multiplechoice(options, message_when_failing)
예제 #59
0
  def execute(self, **kwargs):
    # NB: kwargs are for testing and pass-through to underlying subprocess process spawning.

    go_targets = OrderedSet(target for target in self.context.target_roots if self.is_go(target))
    args = self.get_passthru_args()
    if not go_targets or not args:
      msg = (yellow('The pants `{goal}` goal expects at least one go target and at least one '
                    'pass-through argument to be specified, call with:\n') +
             green('  ./pants {goal} {targets} -- {args}')
             .format(goal=self.options_scope,
                     targets=(green(' '.join(t.address.reference() for t in go_targets))
                              if go_targets else red('[missing go targets]')),
                     args=green(' '.join(args)) if args else red('[missing pass-through args]')))
      raise self.MissingArgsError(msg)

    go_path = OrderedSet()
    import_paths = OrderedSet()
    for target in go_targets:
      self.ensure_workspace(target)
      go_path.add(self.get_gopath(target))
      import_paths.add(target.import_path)

    self.execute_with_go_env(os.pathsep.join(go_path), list(import_paths), args, **kwargs)
예제 #60
0
def print_diff(diffs):
    """ Pretty print the diffs between files """

    for diff in diffs:
        print '\n' + '=' * 80 + '\n'

        dirs = diff[0]
        file = diff[1]

        print file
        print '---', os.path.join(dirs[0], file)
        print '+++', os.path.join(dirs[1], file)

        result = diff[2][2:]
        for line in result:
            line = line.strip()
            if len(line):
                if line[0] == '-':
                    line = green(line)
                elif line[0] == '+':
                    line = red(line)
                elif line[0] == '?':
                    line = yellow(line)
            print '\t%s' % line