Esempio n. 1
0
File: dzero.py Progetto: ab7/dzero
def end():
	pause('*****************')
	print "%s defeats the Wizard and finds a shaft leading up to the surface!" % name
	pause('*****************')
	print bold("THE F*****G END :D")
	pause('*****************')
	sys.exit(0)
Esempio n. 2
0
def code_array(buf, array_name = 'shellcode', row_width = 16, line_delimiter = '', fancy = False):
	lines = []
	out = array_name +" = \n"

	for i in range(0, len(buf), row_width):
		j = 0
		linebuf = ''
		while (j < row_width and (i+j) < len(buf)):
			linebuf += "\\x%02x" % ( ord(buf[i+j]) )
			j = j + 1

		lines.append(linebuf);

	for i in range(0, len(lines)-1):
		if fancy:
			out += "\t" + colors.bold() + colors.fg('magenta') + "\""
			out += colors.fg("red") + lines[i]
			out += colors.fg('magenta') + "\"" + colors.end()
			out += line_delimiter + "\n"
		else:
			out += "\t\"%s\"%s\n" % ( lines[i], line_delimiter )

	if fancy:
		out += "\t" + colors.bold() + colors.fg('magenta') + "\""
		out += colors.fg("red") + lines[len(lines)-1]
		out += colors.fg('magenta') + "\"" + colors.end() + ";"
		out += "\n\n"
		# out += "\t\"%s\";\n\n" % ( lines[len(lines)-1] )
	else:
		out += "\t\"%s\";\n\n" % ( lines[len(lines)-1] )

	return out
Esempio n. 3
0
def photopost(post):
    photostr = dedent(
        """\
        {}
        \t{}
        """).format(
            bold(post['caption'].encode('utf-8')),
            '\n\t'.join(
                ('* {}\n\t{}\n\t\t({} : {}x{})'.format(
                    bold(photo['caption'].encode('utf-8')),
                    '\n\t'.join(
                        imgterm.show_img(
                        PostImage.id_and_num_to_file(post['id'],
                                                     photo['alt_sizes'][0]['url'],
                                                     i),
                            method='mean'  # better at letters.
                        )
                    ),
                    prettify(photo['alt_sizes'][0]['url'],'dark gray',None),
                    prettify(photo['alt_sizes'][0]['width'],'dark gray',None),
                    prettify(photo['alt_sizes'][0]['height'],'dark gray',None)
                )
                    for (i,photo) in enumerate(post['photos']))
            )
        )
    return photostr
Esempio n. 4
0
def region_fitbit(fb):
    frame = ' '
    print colors.bold(" 个人数据 ", fg='white', bg='black') + colors.color(
        142 * frame, bg='black')
    print ""
    fitbit.showsteps(fb)
    print ""
Esempio n. 5
0
def code_array(buf, array_name = 'shellcode', row_width = 16, line_delimiter = '', fancy = False):
	lines = []
	out = array_name +" = \n"

	for i in range(0, len(buf), row_width):
		j = 0
		linebuf = ''
		while (j < row_width and (i+j) < len(buf)):
			linebuf += "\\x%02x" % ( ord(buf[i+j]) )
			j = j + 1

		lines.append(linebuf);

	for i in range(0, len(lines)-1):
		if fancy:
			out += "\t" + colors.bold() + colors.fg('magenta') + "\""
			out += colors.fg("red") + lines[i]
			out += colors.fg('magenta') + "\"" + colors.end()
			out += line_delimiter + "\n"
		else:
			out += "\t\"%s\"%s\n" % ( lines[i], line_delimiter )

	if fancy:
		out += "\t" + colors.bold() + colors.fg('magenta') + "\""
		out += colors.fg("red") + lines[len(lines)-1]
		out += colors.fg('magenta') + "\"" + colors.end() + ";"
		out += "\n\n"
		# out += "\t\"%s\";\n\n" % ( lines[len(lines)-1] )
	else:
		out += "\t\"%s\";\n\n" % ( lines[len(lines)-1] )

	return out
Esempio n. 6
0
def region_tips(db):
  tips = db.smembers('tips')
  frame = ' '
  print colors.bold(" Tips ", fg='black', bg='green')+colors.color(146*frame, bg='green')
  print ""
  for tip in tips:
    print colors.bold("-- ", fg='red') + colors.blink2(tip, fg='green')
Esempio n. 7
0
 def print(self, tagName=None):
     if tagName is not None:
         tag = self.getTag(tagName)
         print(bold(tag[0], bg='green'), str(tag[1]))
     else:
         for tag in self._tags:
             print(bold(tag[0], bg='green'), str(tag[1]))
  def assert_success_runner(self, workdir, config, cmd, extra_config={}, extra_env={}, expected_runs=1):
    combined_config = config.copy()
    recursively_update(combined_config, extra_config)
    print(bold(cyan('\nrunning: ./pants {} (config={}) (extra_env={})'
                    .format(' '.join(cmd), combined_config, extra_env))))
    run_count = self._run_count(workdir)
    start_time = time.time()
    run = self.run_pants_with_workdir(
      cmd,
      workdir,
      combined_config,
      extra_env=extra_env,
      # TODO: With this uncommented, `test_pantsd_run` fails.
      # tee_output=True
    )
    elapsed = time.time() - start_time
    print(bold(cyan('\ncompleted in {} seconds'.format(elapsed))))

    runs_created = self._run_count(workdir) - run_count
    self.assertEquals(
        runs_created,
        expected_runs,
        'Expected {} RunTracker run to be created per pantsd run: was {}'.format(
          expected_runs,
          runs_created,
        )
    )
    self.assert_success(run)
    return run
Esempio n. 9
0
def c(buf, array_name = 'shellcode', row_width = 16, fancy = False):
	if fancy:
		name  = colors.fg('green') + "unsigned " + colors.bold() + "char " + colors.end()
		name += colors.bold() + array_name + "[]" +  colors.end()
	else:
		name = "unsigned char " + array_name + "[]"

	return code_array(buf, name, row_width, '', fancy);
Esempio n. 10
0
def c(buf, array_name = 'shellcode', row_width = 16, fancy = False):
	if fancy:
		name  = colors.fg('green') + "unsigned " + colors.bold() + "char " + colors.end()
		name += colors.bold() + array_name + "[]" +  colors.end()
	else:
		name = "unsigned char " + array_name + "[]"

	return code_array(buf, name, row_width, '', fancy);
Esempio n. 11
0
def region_tips(db):
    tips = db.smembers('tips')
    frame = ' '
    print colors.bold(" Tips ", fg='black', bg='green') + colors.color(
        146 * frame, bg='green')
    print ""
    for tip in tips:
        print colors.bold("-- ", fg='red') + colors.blink2(tip, fg='green')
Esempio n. 12
0
def do_ropfind(file, match_string):
	gadgets = []

	myelf = elf.fromfile(file)

	if myelf.data[0:4] != "\x7F"+"ELF":
		print "[!] '%s' is not a valid ELF file :(" % (file)
		sys.exit(-1)


	# figure out parameter
	if re.search("^[0-9a-f\?]+$", match_string) != None:
		pattern = match_string
	else:
		pattern = assemble_str(match_string)


	print "[!] pattern: '%s'" % pattern

	for section_name in myelf.strtable:
		if section_name == "":
			continue

		section = myelf.section(section_name)

		# check for PROGBITS type
		if section['type'] != 1:
			continue

		matches = findstr(section['data'], pattern)

		if len(matches) == 0:
			continue

		pstr  = colors.fg('cyan') + ">> section '" + colors.bold() + section_name + colors.end()
		pstr += colors.fg('cyan') + "' [" + colors.bold() + str(len(matches)) + colors.end()
		pstr += colors.fg('cyan') + " hits]"

		m = 0

		for match in matches:
			if match[1] in gadgets:
				continue

			if m == 0:
				print pstr
				m = 1

			disas = disas_str(section['addr'] + match[0], binascii.unhexlify(match[1]))
			fstr =  colors.fg('cyan') + " \_ " + colors.fg('green') + "%08x [" + colors.bold() + match[1] + colors.end()
			fstr += colors.fg('green') + "] "+ colors.bold() + "-> " + colors.end()
			fstr += colors.fg('red') + ' ; '.join(disas).lower() + colors.end()
			print fstr % (section['addr'] + match[0])

			gadgets.append(match[1])

		if m == 1:
			print ""
Esempio n. 13
0
def main(args):
	if len(args) != 1 and len(args) != 2:
		print "usage: moneyshot dumpsym <filename> [filter]"
		return

	myelf = elf.fromfile(args[0])

	sym_filter = ""

	if len(args) == 2:
		sym_filter = args[1]

	if myelf.data[0:4] != "\x7F"+"ELF":
		print "[!] '%s' is not a valid ELF file :(" % (file)
		sys.exit(-1)

	if myelf.elfwidth == 64:
		sixtyfour = True
	else:
		sixtyfour = False

	dynsym = myelf.section(".dynsym")

	if dynsym == False:
		print "ERROR: could not retrieve .dynsym section"
		exit()

	dynstr = myelf.section(".dynstr")
	
	if dynstr == False:
		print "ERROR: could not retrieve .dynstr section"
		exit()

	symbol_names = dynstr['data'].split("\x00")
	symbol_info = {}

	i = 0

	while i < len(dynsym['data']):
		if sixtyfour == True:
						sym_entry = struct.unpack("<LQQBBH", dynsym['data'][i:(i+24)])
						i = i+24
		else:
						sym_entry = struct.unpack("<LLLBBH", dynsym['data'][i:(i+16)])
						i = i+16

		name_len = dynstr['data'][(sym_entry[0]+1):].find("\x00")
		name = dynstr['data'][ (sym_entry[0]) : (sym_entry[0]+name_len+1) ]

		
		if sym_filter != "" and name.find(sym_filter) == -1:
			continue

		fstr  = colors.fg("green") + "[" + colors.bold() + "%08x" + colors.end() + colors.fg("green") + "]" + colors.end() 
		fstr += " '" + colors.fg("red") + colors.bold() + "%s" + colors.end() + "'" 

		print fstr % (sym_entry[1], name)
Esempio n. 14
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)
Esempio n. 15
0
File: dzero.py Progetto: ab7/dzero
def flashlight(expose):
	#NOT GOING TO USE THIS
	print "\n%s shines the flashlight around the dark room ands sees a %s." % (name, expose)
	pickup = raw_input("Pick items up?[Y/N] ")
	if pickup in ('y', 'Y'):
		print "\n%s picks up %s." % (name, bold(expose))
		bp.append(expose)
	else:
		print "\n%s leaves the %s on the ground.\n" % (name, bold(expose))
Esempio n. 16
0
File: dzero.py Progetto: ab7/dzero
def help():
	print bold('''*DZERO HELP*
	
Enter the letter [b] to open up the backpack.
Enter the letter [l] to inspect current room again.

To use items in the backpack, enter the name of the item.
To inspect items, doors, etc of a room, type "inspect [element]".\n''')
	raw_input('Press [Enter] to continue... ')
	print '\n'
Esempio n. 17
0
def region_message(db):
    frame = ' '
    sysinfo = db.get('sysinfo')
    if sysinfo:
        info = sysinfo.split('|')
        internetConnect = info[0]
        alarmSyncy = info[1]
        importMesg = info[2]
    else:
        internetConnect = 'unkown'
        alarmSyncy = 'unkown'
        importMesg = '0'

    print colors.bold(" Internet Connect: ", fg='white', bg='black') \
            +colors.bold(internetConnect, fg='green', bg='black') \
            +colors.color(44*frame, bg='black') \
            +colors.bold("Alarms Syncy: ", fg='white', bg='black') \
            +colors.bold(alarmSyncy, fg='green', bg='black') \
            +colors.color(44*frame, bg='black') \
            +colors.bold(" Important Messages: ", fg='white', bg='black') \
            +colors.bold(importMesg, fg='magenta', bg='black') \
            +colors.color(4*frame, bg='black')
    print ""
    messages = db.smembers('message')
    if messages:
        for message in messages:
            print colors.bold(">_ ", fg='red') + colors.blink2(message,
                                                               fg='green')
    print ""
Esempio n. 18
0
def region_message(db):
  frame = ' '
  sysinfo = db.get('sysinfo')
  if sysinfo:
    info = sysinfo.split('|')
    internetConnect = info[0]
    alarmSyncy = info[1]
    importMesg = info[2]
  else:
    internetConnect = 'unkown'
    alarmSyncy = 'unkown'
    importMesg = '0'

  print colors.bold(" Internet Connect: ", fg='white', bg='black') \
          +colors.bold(internetConnect, fg='green', bg='black') \
          +colors.color(44*frame, bg='black') \
          +colors.bold("Alarms Syncy: ", fg='white', bg='black') \
          +colors.bold(alarmSyncy, fg='green', bg='black') \
          +colors.color(44*frame, bg='black') \
          +colors.bold(" Important Messages: ", fg='white', bg='black') \
          +colors.bold(importMesg, fg='magenta', bg='black') \
          +colors.color(4*frame, bg='black')
  print ""
  messages = db.smembers('message')
  if messages:
    for message in messages:
      print colors.bold(">_ ", fg='red') + colors.blink2(message, fg='green')
  print ""
Esempio n. 19
0
 def selectLesson(self, titles):
     '''Let the user choose between available lessons and return lesson #'''
     print('These are the available lessons for this layout\n')
     i = 0
     validChars = ''
     for title in titles:
         i += 1
         iStr = str(i)
         validChars += iStr
         print('  ' + bold(iStr) + ' - ' + title)
     print()
     return int(CLI.inputChar(bold('Select a lesson:'), validChars))
Esempio n. 20
0
def do_ropfind_raw(file, match_string, single):
    gadgets = []

    sixtyfour = True

    data = open(file).read()

    # figure out parameter
    if re.search("^[0-9a-f\?]+$", match_string) != None:
        pattern = match_string
    else:
        pattern = assemble_str(match_string, sixtyfour)

    print "[!] pattern: '%s'" % pattern

    matches = findstr(data, pattern)

    if len(matches) == 0:
        return

    pstr = colors.fg(
        'cyan') + ">> section '" + colors.bold() + "RAW" + colors.end()
    pstr += colors.fg('cyan') + "' [" + colors.bold() + str(
        len(matches)) + colors.end()
    pstr += colors.fg('cyan') + " hits]"

    m = 0

    for match in matches:
        if single and match[1] in gadgets:
            continue

        if m == 0:
            print pstr
            m = 1

        disas = disas_str(match[0], binascii.unhexlify(match[1]), sixtyfour)
        fstr = colors.fg('cyan') + " \_ " + colors.fg(
            'green') + "%08x [" + colors.bold() + match[1] + colors.end()
        fstr += colors.fg(
            'green') + "] " + colors.bold() + "-> " + colors.end()
        fstr += colors.fg('red') + ' ; '.join(disas).lower() + colors.end()
        print fstr % (match[0])

        gadgets.append(match[1])

    if m == 1:
        print ""
Esempio n. 21
0
def disas_thumb(buf, array_name="", row_width=16, fancy=False):
    insns = struct.unpack("H" * (len(buf) / 2), buf)
    out = ""
    pos = 0
    for insn in insns:
        tmp = ""

        if fancy:
            tmp += colors.fg("cyan")

        tmp += "%.8x: " % (pos)

        if fancy:
            tmp += colors.fg("red") + colors.bold()

        tmp += "%08x " % (insn)

        if fancy:
            tmp += colors.end() + colors.fg("green")

        tmp += str(darm.disasm_thumb(insn))

        if fancy:
            tmp += colors.end()

        out += "  " + tmp + "\n"

        pos = pos + 2

    return out
Esempio n. 22
0
def driveinit():
    creds = None
    SCOPES = [
        'https://www.googleapis.com/auth/drive.readonly',
        'https://www.googleapis.com/auth/userinfo.profile', 'openid',
        'https://www.googleapis.com/auth/userinfo.email'
    ]
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('drive', 'v3', credentials=creds)

    user_service = build('oauth2', 'v2', credentials=creds)
    info = user_service.userinfo().get().execute()
    print("Accessing drive of user {} <{}>".format(blue(bold(info['name'])),
                                                   info['email']))

    return service
Esempio n. 23
0
def grid_search(task,
                default_parameters,
                parameters,
                report=None,
                report_best=None,
                limit=float('inf')):
    best = {'eval': None, 'params': None, 'artifact': None}
    results = []
    import itertools
    names = [k for k, _ in parameters.items()]
    values = [v for _, v in parameters.items()]
    all_params = list(itertools.product(*values))
    random.shuffle(all_params)
    [print(r) for r in all_params]
    try:
        for i, params in enumerate(all_params):
            if i > limit:
                break
            local_parameters = {k: v for k, v in zip(names, params)}
            print("{}/{} {}".format(i, len(all_params), local_parameters))
            artifact, eval = task(
                merge_hash(default_parameters, local_parameters))
            _update_best(artifact, eval, local_parameters, results, best,
                         report, report_best)
    finally:
        from colors import bold
        print(
            bold("*** Best parameter: ***\n{}\neval: {}".format(
                best['params'], best['eval'])))
        print(results)
    return best['artifact'], best['params'], best['eval']
Esempio n. 24
0
 def start(mode='sniffing', path='default', flush=False):
     global pat
     #print(verifyinstall('nikto'))
     pat = path
     if flush is True:
         if pat == 'default':
             username = getpass.getuser()
             path = '/home/' + username + '/.purp/purp.sqlite'
         if pat != 'default':
             path = pat
         database = Database()
         database.setpath(path)
         database.flush()
     if mode == 'sniffing':
         try:
             t = threading.Thread(target=sproxy)
             t2 = threading.Thread(target=inte)
             t.start()
             setpath()
             t2.start()
         except KeyboardInterrupt:
             exit()
     if mode == 'intercepting':
         setpath()
         print(bold(banner))
         print('\n***Intercepting mode***\n')
         print(
             "For quit the program press q or Control+C\n\nWaiting for incoming request from browser..."
         )
         t = threading.Thread(target=sproxy)
         t.start()
         intercept()
Esempio n. 25
0
def inte():
    global global_help
    print(bold(banner))
    print('\n***Sniffing mode***\n')
    if verifyinstall('nmap'):
        mydict.update({'portscan': nmap_portscan})
        global_help = global_help + "portscan <option value>                     View the scan port of value host\n"
    else:
        print(
            "\n--Nmap is not installed and portscan feature is not available\n"
        )
    if verifyinstall('nikto'):
        mydict.update({'nikto': nikto_scan})
        global_help += "    nikto <option value>                        Try to find vulnerability on value host\n"
    else:
        print(
            "\n--Nikto is not installed and vulnerability feature is not available\n"
        )

    while True:
        try:
            text = ""
            completer = Mycompleter(mydict)
            readline.set_completer(completer.complete)
            readline.parse_and_bind("tab: complete")
            text = input('>>> ')
        except KeyboardInterrupt:
            pass
        except EOFError:
            break
        if not text:
            continue
        interpreter = Interpreter(text)
        interpreter.didfunc()
Esempio n. 26
0
def printa(val='10'):
    reqlist = p.get_req()
    reslist = p.get_res()
    titles = ['ID', 'Method', 'Host', 'path', 'R-Code']
    try:
        print(
            bold('{:<6s}{:<10s}{:<40s}{:<40s}{:<20s}'.format(
                titles[0], titles[1], titles[2], titles[3], titles[4])))
        for x in range(len(reqlist)):
            if x > (len(reqlist) - int(val) - 1):
                lenhost = len(reqlist[x].host) + 8
                path = ((str(reqlist[x].path[lenhost:lenhost + 35]) +
                         '...') if len(reqlist[x].path) - lenhost > 30 else
                        reqlist[x].path[lenhost:])
                print('{:<6}'.format(str(reqlist[x].id)), end="")
                print(method_color[str(reqlist[x].command)]('{:<10s}'.format(
                    str(reqlist[x].command))),
                      end="")
                print('{:<40s}{:<40s}'.format(str(reqlist[x].host), path),
                      end="")
                print(response_code_color[str(reslist[x].status)[0]](
                    '{:<20s}'.format(
                        str(reslist[x].status) + ' ' +
                        str(reslist[x].reason))))
    except ValueError:
        print('\n\nYou enter a non number')
    print('\n')
Esempio n. 27
0
 def show(cls, post):
     rows, columns = map(int,os.popen('stty size', 'r').read().split())
     printstr = dedent(
         """\
         {}
         {}
         {} at {} from {}, id is {}
         {} : [{}]
         """).format(
             prettify(' '*columns,'dark gray',None,'underlined'),
             prettify(' '*columns,None,None),
             prettify(post['type'], 'white', 'blue'),
             bold(post['date']),
             prettify(post['blog_name'],None, None,'bold'),
             post['id'],
             prettify('tagged','green',None,'bold'),
             ','.join(
                 list(map(lambda t: underlined(t.encode('utf-8')),
                          post['tags']))
             )
         )
     if 'source_url' in post:
         printstr += "source : {} ({})\n".format(
             post['source_title'].encode('utf-8'),
             post['source_url'].encode('utf-8'))
     printstr += cls.printer[post['type']](post)
     printstr += prettify('({})'.format(post['post_url']).rjust(columns),
                          'dark gray', None)
     printstr += prettify(' '*columns+'\n', 'dark gray',None,'underlined')
     return printstr
Esempio n. 28
0
def disas_arm(buf, array_name = '', row_width = 16, fancy = False):
	insns = struct.unpack("I"*(len(buf)/4), buf)
	out = ""
	pos = 0
	for insn in insns:
		tmp = ""

		if fancy:
			tmp += colors.fg('cyan')

		tmp += "%.8x: " % (pos)

		if fancy:
			tmp += colors.fg('red') + colors.bold()

		tmp += "%08x " % (insn)

		if fancy:
			tmp += colors.end() + colors.fg('green')

		tmp += str(darm.disasm_armv7(insn))

		if fancy:
			tmp += colors.end()

		out += "  " + tmp + "\n"

		pos = pos+4

	return out
Esempio n. 29
0
def submit(args):
    cluster_id = c.CLUSTER_MAP['spark']
    num_run = args.num_runs
    reuse_dataset = args.reuse_dataset
    #exp_filepath = args.exp_file_path if args.exp_file_path else "experiment.json"
    exp_filepaths = args.exp_file_paths if args.exp_file_paths else ["experiment.json"]
    for exp_filepath in exp_filepaths:
        exp_file = Path(exp_filepath)
        if exp_file.exists():
            experiment = json.load(open(exp_filepath))
            try:
                benchmark = experiment["BenchmarkName"]
            except KeyError as error:
                print("ERROR:  {} in experiment file: {}".format(error, exp_filepath))
                exit(1) 
        with utils.open_cfg(mode='w') as cfg:
            for s in cfg.sections():
                if s != 'hdfs':
                    cfg.remove_section(s)
            cfg['main'] = {}
            cfg['main']['tool_on_master'] = 'false'
            cfg['main']['experiment_file'] = exp_filepath
            cfg['main']['process_on_server'] = str(c.PROCESS_ON_SERVER)
            cfg['main']['iter_num'] = str(1)
            cfg['submit'] = {}
            cfg[benchmark] = {}
            #cfg[benchmark]['profile_name'] = '{}'.format(c.VAR_PAR_MAP[benchmark]['profile_name'])
            if reuse_dataset:
                cfg['main']['delete_hdfs'] = str(not reuse_dataset)
        print(bold('Submit experiment {} performing {} runs for benchmark {} on cluster {}'.format(exp_filepath, 
                                                                                num_run, benchmark, 
                                                                                cluster_id,)))
        run_xspark(current_cluster='spark', num_instance=0, num_run=num_run,
                   cluster_id=cluster_id, run=1, terminate=0, reboot=0)
Esempio n. 30
0
 def run(self, num_run):
     with utils.open_cfg(mode='w') as cfg:
         cfg['out_folders'] = {}
         if not 'delete_hdfs' in cfg['main']:
             cfg['main']['delete_hdfs'] = 'true'
         cfg['main']['num_run'] = str(num_run)
         '''
         sess_file = Path("session.txt")
         session_no = 0
         if sess_file.exists():
             with open("session.txt", 'r') as f:
                 fc = f.read()
                 session_no = int(fc) + 1 if len(fc) > 0 else 0
                 f.close()
         with open("session.txt", 'w') as f:
                 f.write(str(session_no))
                 f.close()
         '''
     for i in range(num_run):
         if self.cluster_id == c.CLUSTER_MAP['spark']:
             print(bold('Experiment ({}/{})'.format(i + 1, num_run)))
         try:
             self.retrieve_nodes()
             with utils.open_cfg(mode='w') as cfg:
                 cfg['main']['iter_num'] = str(i + 1)
             x_run.run_benchmark(self.nodes)
             if i == 0:
                 with utils.open_cfg(mode='w') as cfg:
                     cfg['main']['delete_hdfs'] = 'false'
         except (OSError, IOError) as exc:
             print('ERROR: {}\n\nSkipping Experiment ({}/{})'.format(
                 exc, i + 1, num_run))
Esempio n. 31
0
  def __call__(self, parser, namespace, values, option_string):
    # I know this import looks out of place but importing readline has side effects (namely,
    # enabling readline support for all input), so I import it here so at least the side effects
    # are restricted to this method call and not importing this module.
    import readline
    for arg in parser.interactive_args:
      required = arg.get('was_required', False)
      is_boolean = arg.get('action') in ('store_true', 'store_false')

      maybe_default = '(default={})'.format(arg['default']) if 'default' in arg else None
      maybe_optional = '[optional]' if (not required and not is_boolean) else None
      maybe_boolean = '[Y/n]' if is_boolean else None

      modifiers = filter(lambda x: x, [maybe_default, maybe_optional, maybe_boolean])
      prompt = colors.bold('{}{}{}? '.format(
        arg['help'],
        (' ' if len(modifiers) > 0 else ''),  # Space if modifiers nonempty
        ' '.join(modifiers)
      ))
      value = input(prompt)
      # Repeat while input is invalid.
      while (
        (value.strip() == '' and required) or
        (is_boolean and self._convert_to_boolean(value) is None)
      ):
        value = input(prompt)
      if is_boolean:
        value = self._convert_to_boolean(value)
      elif not required:
        value = value or None  # Convert the empty string to None.
      python_name = InteractiveArgumentParser._convert_to_python_name(arg['name'])
      setattr(namespace, python_name, value)
Esempio n. 32
0
def main(args):
	if len(args) != 1 and len(args) != 2:
		print "usage:"
		print "  moneyshot lolsled <length> <words>"
		print "  moneyshot lolsled <dictionary>"

		return 

	# some 'harmless' x86 insns, just inc's and dec's
	whitelist=[
		"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"
	]

	# length?
	if args[0].isdigit():
		rs = emu(args[1])
		fstr = " CLOBBER: "
		cl = False
		for reg in rs:
			if rs[reg] != 0:
				fstr += "%s=%08x " % (reg, rs[reg])
				cl = True

		if cl == False:
			fstr += "No clobbering, yay!"

		print fstr

	# assume dictfile (find mode)
	else:
		words = open(args[0]).readlines()
		for word in words:
			ok = True
			word = word.strip().upper()

			for c in word:
				if c not in whitelist:
					ok = False

			if not ok:
				continue

			fstr = colors.fg('cyan')
			fstr += ">> "
			fstr += colors.fg('green')
			fstr += "'%15s' %s--> " % (word, colors.fg('white')+colors.bold())
			fstr += colors.end() + colors.fg('red')
			r = rop.disas_str(0, word)
			fstr += ' ; '.join(r).lower()
			rs = emu(word)
			fstr += " CLOBBER: "
			cl = False
			for reg in rs:
				if rs[reg] != 0:
					fstr += "%s=%08x " % (reg, rs[reg])
					cl = True

			print fstr

	print colors.end()
Esempio n. 33
0
def disas_thumb(buf, array_name='', row_width=16, fancy=False):
    insns = struct.unpack("H" * (len(buf) / 2), buf)
    out = ""
    pos = 0
    for insn in insns:
        tmp = ""

        if fancy:
            tmp += colors.fg('cyan')

        tmp += "%.8x: " % (pos)

        if fancy:
            tmp += colors.fg('red') + colors.bold()

        tmp += "%08x " % (insn)

        if fancy:
            tmp += colors.end() + colors.fg('green')

        tmp += str(darm.disasm_thumb(insn))

        if fancy:
            tmp += colors.end()

        out += "  " + tmp + "\n"

        pos = pos + 2

    return out
Esempio n. 34
0
def do_ropfind_raw(file, match_string, single):
	gadgets = []

	sixtyfour = True

	data = open(file).read()

	# figure out parameter
	if re.search("^[0-9a-f\?]+$", match_string) != None:
		pattern = match_string
	else:
		pattern = assemble_str(match_string, sixtyfour)


	print "[!] pattern: '%s'" % pattern

	matches = findstr(data, pattern)

	if len(matches) == 0:
		return

	pstr  = colors.fg('cyan') + ">> section '" + colors.bold() + "RAW" + colors.end()
	pstr += colors.fg('cyan') + "' [" + colors.bold() + str(len(matches)) + colors.end()
	pstr += colors.fg('cyan') + " hits]"

	m = 0

	for match in matches:
		if single and match[1] in gadgets:
			continue

		if m == 0:
			print pstr
			m = 1

		disas = disas_str(match[0], binascii.unhexlify(match[1]), sixtyfour)
		fstr =  colors.fg('cyan') + " \_ " + colors.fg('green') + "%08x [" + colors.bold() + match[1] + colors.end()
		fstr += colors.fg('green') + "] "+ colors.bold() + "-> " + colors.end()
		fstr += colors.fg('red') + ' ; '.join(disas).lower() + colors.end()
		print fstr % (match[0])

		gadgets.append(match[1])


	if m == 1:
		print ""
Esempio n. 35
0
 def get_received_headers(self):
     received = self.eml.get_all("Received")
     if received:
         for receive in received:
             print(bold(white(f"<Received>")), ":", receive)
     else:
         print("No", bkgrd(white("`Received`"), 'red'),
               "header for this email")
Esempio n. 36
0
    def cmd_help(self, *args):

        print(bold("Commands:"))

        rows = []
        for command_name, command_item in self.commands.items():
            rows.append([command_name, command_item['description']])

        print(table(['Command', 'Description'], rows))
Esempio n. 37
0
def print_codes(codes, depth = 0):
	for key in codes.keys():
		if "description" in codes[key]:
			second_col = "%s%4d%s bytes -- %s" % (colors.fg('green'), get_code_size(codes[key]), colors.end(), codes[key]['description'])
			print "  " * (depth+1) + key.ljust(40 - (depth*2)) + second_col
			
		else:
			print "  " * (depth+1) + colors.bold() + key + colors.end()
			print_codes(codes[key], depth+1)
Esempio n. 38
0
def reboot_cluster(cluster):
    cluster_id = c.CLUSTER_MAP[cluster]
    print(bold('Reboot {}...'.format(cluster_id)))
    run_xspark(current_cluster=cluster,
               num_instance=0,
               cluster_id=cluster_id,
               run=0,
               terminate=0,
               reboot=1)
Esempio n. 39
0
 def summarize(self):
     """Print summary information"""
     printed_header = False
     for matcher in self.matchers:
         if matcher.count > 0:
             if not printed_header:
                 print(colors.bold(self.name + ':'))
                 printed_header = True
             print('  %r' % matcher)
Esempio n. 40
0
def photopost(post):
    photostr = dedent(
        """\
        {}
        \t{}
        """).format(
            bold(post['caption'].encode('utf-8')),
            '\n\t'.join(
                ('* {}\n\t\t({} : {}x{})'.format(
                    bold(photo['caption'].encode('utf-8')),
                    prettify(photo['alt_sizes'][0]['url'],'dark gray',None),
                    prettify(photo['alt_sizes'][0]['width'],'dark gray',None),
                    prettify(photo['alt_sizes'][0]['height'],'dark gray',None)
                )
                    for photo in post['photos'])
            )
        )
    return photostr
Esempio n. 41
0
def banner():
	asquee = """
    __   __  ______.___   __  _____._  __._______._ __  ____._________
   /  \ /  \/  __  |    \|  |/  ___| \/  /\  ___/  |  |/ __  \__   __/
  /    '    \   /  |  |\    |   _|_\    /__\   \|     |   /  |  |  |
 /___\  /    \_____|__|  \__|______||__||______/|__|__|\_____|  |__|
      \/ _____\\   """

	sys.stderr.write(colors.bold() + colors.fg('cyan') + asquee + colors.end() + "\n\n")
Esempio n. 42
0
def header():
	art = """
              ___    ___   __._____  ___   __.__    __  ____. ___   __ 
             /   \  |    \|  |  __  \   \/  /|  |  |  |/ __  \    \|  |
            /  \  \ |  |\    |   /  / \    / |  |__|  |   /  |  |\    |
           /__/ \__\|__|  \__|__|\__\  |__|  |_____|__|\_____|__|  \__|
                   """

	sys.stderr.write(colors.bold() + colors.fg('cyan') + art + colors.end() + "\n\n")
Esempio n. 43
0
File: dzero.py Progetto: 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()
Esempio n. 44
0
def textpost(post):
    return dedent(
        """\
        ==={}===
        {}
        """).format(
            prettify(post['title'].encode('utf-8') if post['title'] else '',
                     'green', None, 'bold', 'underlined'),
            bold(post['body'].encode('utf-8'))
        )
Esempio n. 45
0
 def execute(self) -> None:
     with Logger(f":dizzy: {underline('Execution:')}") as logger:
         if self._manifest.context.confirm == ConfirmationMode.ONCE:
             if ask(logger=logger,
                    message=bold('Execute?'),
                    chars='yn',
                    default='n') == 'n':
                 raise UserError(f"user aborted")
         for resource in self._manifest.resources.values():
             resource.execute()
Esempio n. 46
0
def answerpost(post):
    return dedent('''\
           {} Asked {} ({}):
           \t {}
           
           --{}'''.format(
               post['asking_name'].encode('utf-8'),
               post['blog_name'], post['asking_url'],
               post['question'].encode('utf-8'),
               bold(post['answer'].encode('utf-8'))
           ))
Esempio n. 47
0
def chatpost(post):
    dialog = post['dialogue']
    title = post['title']
    if not title: title=''
    diastr = '\n\n'.join(
        ('{}\n\t{}'.format(
            log['label'].encode('utf-8'),
            '\n\t'.join(log['phrase'].encode('utf-8').split('\n')))
        for log in dialog)
    )
    return bold(title.encode('utf-8')) + diastr
Esempio n. 48
0
    def layout(self):
        '''Let the user make a choice between layouts, return layout tuple'''
        print('Colemak tutor allows you to emulate a layout so you can')
        print('learn and practice typing in colemak without installing')
        print('an implementation for your operating system\n')
        print(bold('  1') +
              ' - Practise colemak using a qwerty layout (emulated)')
        print(bold('  2') + ' - Practise colemak using a colemak layout')
        print(bold('  3') +
              ' - Practise qwerty using a colemak layout (emulated)')
        print(bold('  4') + ' - Practise qwerty using a qwerty layout\n')

        inp = CLI.inputChar(bold('Select an option:'), '1234')
        if inp == '1':
            return ('qwerty', 'colemak')
        elif inp == '2':
            return ('colemak', 'colemak')
        elif inp == '3':
            return ('colemak', 'qwerty')
        return ('qwerty', 'qwerty')
Esempio n. 49
0
    def header(self, mapper=None):
        '''Clear the terminal screen and print the program header'''
        os.system('cls' if os.name == 'nt' else 'clear')
        print(('=' * 80))
        div = lambda x: ((' ' * x) + '---' + (' ' * x))
        print(bold(colemaktutor.colemaktutor.versionStr) + div(14) + '')

        if mapper:
            print('\nkeyboard layout: in = {in_} / out = {out}'
                  .format(in_=mapper.layout_in, out=mapper.layout_out))
        print(('=' * 80) + '\n')