def check_port_available(self): all_enable = True logger.info('Check status of ports for master...') meta = [['HOST', 'PORT', 'STATUS']] for node in self.master_ip_list: for port in self.master_port_list: result, status = net.is_port_empty(node, port) if not result: all_enable = False meta.append([node, port, color.red(status)]) continue meta.append([node, port, color.green(status)]) table = AsciiTable(meta) print(table.table) if self.slave_ip_list: logger.info('Check status of ports for slave...') meta = [['HOST', 'PORT', 'STATUS']] for node in self.slave_ip_list: for port in self.slave_port_list: result, status = net.is_port_empty(node, port) if not result: all_enable = False meta.append([node, port, color.red(status)]) continue meta.append([node, port, color.green(status)]) table = AsciiTable(meta) print(table.table) return all_enable
def getLabObject(labdb): ''' Used to generate a pjl lab object from the labDB.xml database Args: labdb (pjlDB.labDB) entire lab database object generated by pjlDB Return: lab (pjlDB._LabItem) individual lab item generated by pjlDB ''' if debug: print(color.green("[Debug - getLabObject] entering")) validID = False while not validID: idnum = input(color.yellow("Enter lab ID number: ")) if len(idnum) == 4 and idnum.isdigit() == True: try: lab = labdb.getLab(idnum) validID = True except pjlDB.IDDoesNotExist: ### not working properly print("Message") else: print( color.red("[ERROR] ") + "ID formate in not valid. Valid IDs are of the form ####. Please try again" ) validID = False if debug: print(color.green("[Debug - getLabObject] leaving")) return lab
def cvsCO(projectName,tagName='',dirName=''): #TODO check is there is CVSROOT variable - if no, ask user #do cvs check out print color.yellow('Checking project from cvs ...') command = 'cvs co ' if(dirName != ''): command = command + '-d ' + dirName if(tagName != ''): command = command + ' -r ' + tagName + ' ' + projectName else: command = command + ' ' + projectName if(debug): print color.blue('Command is: ') print color.blue(command) timeStart = time.time() os.system(command) timeEnd = time.time() print color.yellow('Check out finished, elapsed time [s]: ' + str(timeEnd - timeStart)) #check if check out was OK - look if the directory is created print color.yellow('Now checking consistency...') if(dirName != ''): coDir = dirName else: coDir = projectName if not(os.path.exists(coDir)): print color.red('Directiry ' + coDir + ' does not exist - EXIT!') sys.exit(1) else: print color.green('Check out OK') print return coDir
def rsync_fb_conf(): logger.info('Sync conf...') cluster_id = config.get_cur_cluster_id() if not validate_id(cluster_id): logger.warn('Invalid cluster id: {}'.format(cluster_id)) return cluster_list = get_cluster_list() if cluster_id not in cluster_list: logger.warn('Cluster not exist: {}'.format(cluster_id)) return my_address = config.get_local_ip_list() path_of_fb = config.get_path_of_fb(cluster_id) props_path = path_of_fb['redis_properties'] key = 'sr2_redis_master_hosts' nodes = config.get_props(props_path, key, []) meta = [['HOST', 'RESULT']] path_of_fb = config.get_path_of_fb(cluster_id) conf_path = path_of_fb['conf_path'] cluster_path = path_of_fb['cluster_path'] for node in nodes: if net.get_ip(node) in my_address: meta.append([node, color.green('OK')]) continue client = net.get_ssh(node) if not client: meta.append([node, color.red('SSH ERROR')]) continue if not net.is_dir(client, cluster_path): meta.append([node, color.red('NO CLUSTER')]) continue net.copy_dir_to_remote(client, conf_path, conf_path) meta.append([node, color.green('OK')]) utils.print_table(meta)
def build(binary,projectDir=''): if(binary == ''): print color.red('Build: Name of not specified - EXIT!') sys.exit(1) command = 'make' origPath = os.path.abspath('./') if(projectDir != ''): if(os.path.exists(projectDir)): os.chdir(projectDir) else: print color.red('Directiry ' + projectDir + ' does not exist - EXIT!') sys.exit(1) if not (os.path.exists('Makefile')): print color.red('Makefile ' + os.path.abspath('./') + '/Makefile does not exist - EXIT!') sys.exit(1) print color.yellow('Build start ...') if(debug): print color.blue('Directory is ') print color.blue(os.path.abspath('./')) timeStart = time.time() os.system(command) timeEnd = time.time() print color.yellow('Build finished, elapsed time [s]: ' + str(timeEnd - timeStart)) os.chdir(origPath) #check if check out was OK - look if the directory is created print color.yellow('Now checking consistency...') if not(os.path.exists(projectDir+'/'+binary)): print color.red('File ' + os.path.abspath(projectDir) + '/' + binary + ' does not exist - EXIT!') sys.exit(1) else: print color.green('Build OK') print return os.path.abspath(projectDir) + '/' + binary
def logo(): """ droidpot ascii art :return: """ logos = [] logos.append(""" ___ _ _ ___ _ / \_ __ ___ (_) __| | / _ \___ | |_ / /\ / '__/ _ \| |/ _` |/ /_)/ _ \| __| / /_//| | | (_) | | (_| / ___/ (_) | |_ /___,' |_| \___/|_|\__,_\/ \___/ \__| """) logos.append(""" .___ .__ .___ __ __| _/______ ____ |__| __| _/_____ _____/ |_ / __ |\_ __ \/ _ \| |/ __ |\____ \ / _ \ __| / /_/ | | | \( <_> ) / /_/ || |_> > <_> | | \____ | |__| \____/|__\____ || __/ \____/|__| \/ \/|__| """) print green(random.choice(logos))
def test_readNext2(self) : dataIn = ['/file/path.iced:6', '/file-2-path.iced:8', '/file-2-path.iced:12'] pyOutPutParse.writeFile(dataIn) dataOut = pyOutPutParse.read('/file-2-path.iced:6', "next") color.green("dataOut") print(dataOut) expected = '/file-2-path.iced:8' self.assertEqual (dataOut, expected)
def test_filerRead(self) : dataIn = ['/Users/maks/Library/Application Support/Sublime Text 3/Packages/move_near_replace/replace_require_test.py:6', '/Users/maks/Library/Application Support/Sublime Text 3/Packages/move_near_replace/replace_require.py:9'] pyOutPutParse.writeFile(dataIn) dataOut = pyOutPutParse.readFile() color.green("dataOut") print(dataOut) expected = dataIn self.assertEqual (dataOut, expected)
def equipInfoReview(eqdb, originalItem): ''' Controls the review and editing of equipment list. Asks user to input id numbers and quantity of equipment needed for the new lab. User also can input an alternate/secondary equipment item for each primary item Input id numbers are check for correctness Args: eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB originalItem (pjlDB._LabItem) individual lab item generated by pjlDB Return: equipItems (list of dictionaries) ''' if debug: print(color.green("[Debug - equipInfoReview] entering")) equipItems = [] if originalItem.equipment: for i in originalItem.equipment: print("ID Number [" + i['id'] + "]: Name [" + i['name'] + "]: Alternate Name: [" + i['alt-name'] + "]: Amount [" + i['amount'] + "]") if input(color.yellow("Would you like to edit this entry? y/N: ") ).lower() == "y": equipID = input("Enter new id number [" + i['id'] + "], enter 'delete' to remove this item ") if equipID == "": equipID = i['id'] if equipID == "delete": print("deleting " + i['id'] + " " + i['name']) else: if debug: print( color.green( "[Debug - equipInfoReview] editing equipment item???" )) item = addEquipItem(eqdb, equipID) if not item == "": if debug: print( color.green( "[Debug - equipInfoReview] adding edited entry???" )) equipItems.append(item) else: equipItems.append(i) # if not equipID == "delete": # item = addEquipItem(eqdb,equipID) # print("enter editing code here") # else: # print("deleting " + i['id'] + " " + i['name']) else: equipItems.append(i) if debug: print(color.green("[Debug - equipInfoReview] leaving")) return equipItems
def equipNameOptions(item): ''' Sometimes a piece of a equipment is a piece of the kit. In these cases it can be useful for the name in the equipment list to appear as the part, but keep the equipment id number of the kit. This function allows the user to choose a name from the list of components in a kit. Args: item (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB Return: name (str) Name of equipment item ''' if debug: print(color.green("[Debug - equipNameOptions] entering")) print() print( color.yellow( "What name you would like displayed for this item? Pick a number [default = 0]." )) print() # print("[0] " + item.name) kitItems = item.kit.split(",") kitItems[:0] = [item.name] for i in range(0, len(kitItems)): index = str(i) print("[" + index + "] " + kitItems[i].strip()) validName = False while not validName: #selection = int(input(color.yellow("Please Choose a Name for This Item? [0] "))) selection = input( color.yellow("Please Choose a Name for This Item? [0] ")) if selection == "": selection = 0 elif selection.isdigit(): selection = int(selection) #else #print(selection) if debug: print( color.green("[Debug - equipNameOptions] selection " + str(selection))) #if 1 <= selection <= len(kitItems) + 1: if 0 <= selection <= len(kitItems): name = kitItems[selection].strip() validName = True elif selection == 0: name = item.name validName = True else: print(selection + " is not a option.") if input(color.yellow( "Do you wish to try again? Y/n: ")).lower() == "n": exit() return name
def print_eflags(self): eflags = pykd.reg('efl') eflags_str = color.green("EFLAGS: {:#x}".format(eflags)) eflags_str += " [" for bit, flag_name in self.context.eflags_tbl.items(): is_set = eflags & (1 << bit) eflags_str += " " if is_set: eflags_str += color.dark_red(flag_name) else: eflags_str += color.green(flag_name) eflags_str += " ]" pykd.dprintln(eflags_str, dml=True)
def clone_or_update(repo, path): """Clone or update a repo.""" if not os.path.exists(path): print(color.green("\nCloning dotfiles repo...")) run(["git", "clone", "-q", repo, path]) try: print(color.green("\nUpdating dotfiles repo...")) run(["git", "pull", "-q"], cwd=path) run(["git", "submodule", "-q", "init"], cwd=path) run(["git", "submodule", "-q", "update"], cwd=path) except subprocess.CalledProcessError: print("WARNING git pull failed, continuing anyway, repo might be outdated")
def runTests(settings): #load user setting projectName = settings['projectName'] binary = settings['binary'] cardName = settings['cardName'] cardDir = settings['cardDir'] tagName1 = settings['tagName1'] dirName1 = settings['dirName1'] tagName2 = settings['tagName2'] dirName2 = settings['dirName2'] debug = settings['debug'] #check out datacards dataCardsDir = cvsCO(cardName,dirName=cardDir) #check out versions coDir1 = cvsCO(projectName,tagName1,dirName1) coDir2 = cvsCO(projectName,tagName2,dirName2) #build versions bin1 = build(binary,coDir1) bin2 = build(binary,coDir2) #setup paths etc. absDir = os.path.abspath('./') dataCardsDir = absDir + '/' + dataCardsDir logDir1 = absDir + '/' + 'logs1' logDir2 = absDir + '/' + 'logs2' cardNames = getDataCardNames(dataCardsDir) #run tests #runDataCards(bin1,dataCardsDir,logDir1) #runDataCards(bin2,dataCardsDir,logDir2) #compare results (log files) #compare log files cmpTwoLogDir(logDir1,logDir2,cardNames) #copare cross sections cs1 = getCSFromLog(cardNames,logDir1) cs2 = getCSFromLog(cardNames,logDir2) i = 0 diffs = [] for card in cardNames: diffs.append(cs1[i] - cs2[i]) i = i + 1 print color.green('Differences in cross sections:') for diff in diffs: print diff print
def cmpTwoLogDir(logPath1,logPath2,dataCardNames): if not(os.path.isdir(logPath1)): print color.red('Log directory ' + logPath1 + ' does not exist - EXIT!') sys.exit(1) if not(os.path.isdir(logPath2)): print color.red('Log directory ' + logPath2 + ' does not exist - EXIT!') sys.exit(1) logFiles = [] for card in dataCardNames: logFiles.append(card+'.log') cmps = filecmp.cmpfiles(logPath1,logPath2,logFiles) print color.green('=====================================================') print color.green('Files which are the same:') for file in cmps[0]: print color.green(file) print color.green('=====================================================') print print color.red('=====================================================') print color.red('Files which are NOT the same:') for file in cmps[1]: print color.red(file) print color.red('=====================================================') print print color.yellow('=====================================================') print color.yellow('Files which script was not able to compare:') for file in cmps[2]: print color.yellow(file) print color.yellow('=====================================================') print
def main(): parser = argparse.ArgumentParser( description= 'Verify SSL certificate validation for one or more tested application') parser.add_argument('app_or_capture', metavar='appname', nargs='?', help='Application name or network capture file') args = parser.parse_args() app = args.app_or_capture if args.app_or_capture: check_app(app) else: for entry in os.listdir('results'): if os.path.isdir(os.path.join('results', entry)): app = entry check_app(app) eprint('') eprint(color.bright('SSL test summary:')) eprint(color.bright(color.red(('Failed:')))) for app in ssl_failed: eprint(app) if ssl_notest: eprint(color.bright('Not tested:')) for app in ssl_notest: eprint(app) eprint(color.bright(color.green(('Passed:')))) for app in ssl_passed: eprint(app)
def PlayAVfile(self, fname): # play with mplayer if not os.path.isfile(fname): raise RuntimeError("'%s' is not a file" % fname) fname.replace("'", "\\'") log.info(color.green("*** playing '%s'" % fname)) cmd = self.mplayer_cmd.copy() # copy list cmd.append(fname) # pre-play hooks for hook in self.pre_play_hooks: hook(fname) log.debug("calling %s", cmd) p = subprocess.Popen(cmd) try: p.wait() log.info("subprocess finished.") except KeyboardInterrupt: log.info("KeyboardInterrupt: terminating %s subprocess...", cmd[0]) try: p.terminate() except OSError: pass p.wait() log.info("subprocess was terminated.") raise # re-raise the interrupt # post-play hooks for hook in self.post_play_hooks: hook(fname)
def check_hosts_connection(self, hosts, show_result=False): host_status = [] success_count = 0 for host in hosts: try: client = get_ssh(host) client.close() logger.debug('{} ssh... OK'.format(host)) success_count += 1 host_status.append([host, color.green('OK')]) except HostNameError: host_status.append([host, color.red('UNKNOWN HOST')]) logger.debug('{} gethostbyname... FAIL'.format(host)) except HostConnectionError: host_status.append([host, color.red('CONNECTION FAIL')]) logger.debug('{} connection... FAIL'.format(host)) except SSHConnectionError: host_status.append([host, color.red('SSH FAIL')]) logger.debug('{} ssh... FAIL'.format(host)) if show_result: table = AsciiTable([['HOST', 'STATUS']] + host_status) print(table.table) if len(hosts) != success_count: return False return True
def lsvpc(): with settings(warn_only=True), hide('stdout', 'stderr', 'running', 'warnings'): for region in getregions(): jr = json.loads(local('aws ec2 describe-vpcs --region ' + region, capture=True)) dj = ddl(jr) print(green(region)) print(str(dj.Vpcs))
def equipValid(eqdb, itemID): ''' Checks if equipment item added by user for new lab is valid Args: eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB itemID (str) Id number of equipment item to add Return: validItem (bool) name (str) Name of equipment item errorMessage (str) Information on why a equipment entry is invalid ''' if debug: print(color.green("[Debug - equipValid] entering")) errorMessage = "" if len(itemID) == 4 and itemID.isdigit() == True: try: item = eqdb.getItem(idnum=itemID) if item.is_kit: name = equipNameOptions(item) else: name = item.name errorMessage = "" return True, name, errorMessage except pjlDB.EQIDDoesNotExist as e: errorMessage = ("Invalid Equipment: Item " + itemID + " does not exist.") name = "null" return False, name, errorMessage else: errorMessage = ("Invalid Equipment: Id needs to be a 4 digit number") name = "null" return False, name, errorMessage
def _format_review(self): if not self.reviews['reviews']: return '' review = self.reviews['reviews'][self._current_review] return '%s\n User: %s\n Rating: %s\n Review: %s\n' % ( color.green('Review'), color.cyan(review['user']['name']), color.yellow('*' * review['rating']), review['excerpt'])
def get_search_results(pkt): ''' Parse through packets that match tshark filter for search ''' global found, foundunenc, searchterm # Searches are case insensitive pcre = re.compile('(?i)' + searchterm) print( color.green( color.bright('Found match in %s packet [%d] (%s):' % (pcapfile, int(pkt.number), pkt.highest_layer)))) found = True foundunenc = True for layer in pkt.layers: for field_line in layer._get_all_field_lines(): if pcre.search(field_line): print('%s: %s' % (layer.layer_name, field_line.rstrip())) print( color.bright( color.red('%s found in unencrypted %s traffic!' % (searchterm, pkt.highest_layer)))) if args.verbose: print('----- Full packet dump begin -----') print(pkt) print('----- Full packet dump end -------')
def lskeys():# {{{ with settings(warn_only=True), hide('stdout', 'stderr', 'running', 'warnings'): for region in getregions(): jr = json.loads(local('aws ec2 describe-key-pairs --region ' + region, capture=True)) if jr.get('KeyPairs'): for pair in jr.get('KeyPairs'): print(green(region)) print(turquoise(pair['KeyName'] + " => " + pair['KeyFingerprint']))
def report(worklog, config): lines = [] total = timedelta(seconds=0) rollup = dict() lines.append('{} {}'.format( color.bold('Worklog Report for'), color.purple(worklog.when.strftime('%F'), bold=True))) if len(worklog) == 0: lines.append(' no entries') else: for task, next_task in worklog.pairwise(): if isinstance(task, GoHome): continue if isinstance(next_task, DummyRightNow): colorize_end_time = color.yellow else: colorize_end_time = color.green delta = next_task.start - task.start if task.include_in_rollup(): total += delta if task.description not in rollup: rollup[task.description] = delta else: rollup[task.description] += delta if delta > timedelta(): if not task.logged: task.logged = False lines.append(' {:5s} {} {:5s} {}{!s:>7}{} {} {} {}'.format( color.green(task.start.strftime('%H:%M')), color.black('-', intense=True), colorize_end_time(next_task.start.strftime('%H:%M')), color.black('(', intense=True), Duration(delta).colorized(), color.black(')', intense=True), { True: color.green('*'), False: color.red('*') }[task.logged], task.ticket, task.description)) lines.append('\n {!s:>7} {}'.format( Duration(total).colorized(underline=True), color.colorize('TOTAL', bold=True, underline=True))) for key in sorted(rollup.keys()): lines.append(' {!s:>7} {}'.format( Duration(rollup[key]).colorized(), color.bold(key))) print('\n'.join(lines))
def _format_review(self): if not self.reviews['reviews']: return '' review = self.reviews['reviews'][self._current_review] return '%s\n User: %s\n Rating: %s\n Review: %s\n' % ( color.green('Review'), color.cyan(review['user']['name']), color.yellow('*' * review['rating']), review['excerpt'] )
def getEquipList(eqdb, originalItem): ''' generates a list of equipment Args: eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB originalItem (pjlDB._LabItem) individual lab item generated by pjlDB Return: equipItems (list of dictionaries) ''' if debug: print(color.green("[Debug - getEquipList] entering")) print("") if input( color.yellow( "Would you like to edit the equipment list for this lab? y/N ") ).lower() == "y": print("") print("Current Equipment List") print("-------------------") for i in originalItem.equipment: # i['alt-name'] = "TEST NAME" # i['alt-id'] = "0000" print(i['id'] + " " + i['name'] + " [" + i['alt-id'] + " " + i['alt-name'] + "] " + " (" + i['amount'] + ")") equipItems = [] equipItems = equipInfoReview(eqdb, originalItem) allItems = False while not allItems: print("") if input( color.yellow( "Would you like to add a new piece of equipment for this lab? y/N " )).lower() == "y": itemId = input(color.yellow("Enter the equipment id number: ")) equipItems.append(addEquipItem(eqdb, itemId)) else: allItems = True else: equipItems = originalItem.equipment if debug: print(color.green("[Debug - getEquipList] leaving")) return equipItems
def update(conf, args): '''Apply updates from the upstream repository.''' print('Checking for updates...') # fetch changes from the canonical repo git.fetch(constants.GIT_REMOTE, no_tags=True, quiet=True) # get a list of the commit messages for the incoming changes updates = git('--no-pager', 'log', '..FETCH_HEAD', oneline=True) updates = [tuple(m.split(None, 1)) for m in updates.splitlines()] # print out a list of the incoming updates if len(updates) > 0: print('Available updates:') max_updates = 10 for commit, msg in updates[:max_updates]: print(color.yellow('*'), msg) # print a special message if too many updates are available if len(updates) > max_updates: print('...and', color.green(len(updates) - max_updates), 'more!') print('Run `git log ..FETCH_HEAD` to see the full list') # bail if we have uncommitted changes (git exits non-0 in this case) if git.diff(exit_code=True, quiet=True, _ok_code=(0, 1)).exit_code != 0: raise ValueError('The repository has uncommitted changes. Handle them, ' 'then try updating again.') print('Applying the update...') # stash _all_ changes to the repo git.stash(include_untracked=True, all=True, quiet=True) # squash all the fetched commits together and merge them into master git.merge('@{u}', squash=True, quiet=True) # add a nice update commit that includes the latest upstream commit hash commit_message = 'Update dotparty to %s' % updates[0][0] git.commit(m=commit_message, quiet=True) # TODO: if squash merge failed, roll back to the pre-update state and # complain with instructions for the user to do their own update. # un-stash all our old changes git.stash('pop', quiet=True) # push our changes back up to the remote git.push(quiet=True) print('Update successful!') else: print('Already up-to-date!')
def runDataCards(binaryPath,dataCardPath,logPath): '''binaryPath - absolut path to executelbe file dataCardPath - absolut path to datacards directory logPath - absolut path to log directory''' if not(os.path.isfile(binaryPath)): print color.red('Binary file ' + binaryPath + ' does not exist - EXIT!') sys.exit(1) if not(os.path.isdir(dataCardPath)): print color.red('Data card file ' + dataCardPath + ' does not exist - EXIT!') sys.exit(1) if not(os.path.isdir(logPath)): print color.red('Log directory ' + logPath + ' does not exist - EXIT!') sys.exit(1) binaryDir = (binaryPath.rsplit('/',1))[0] if not(os.path.isdir(binaryDir)): print color.red('Directory with binary file does not exist - probably not used absoluth path to executeble file - EXIT!') sys.exit(1) dataCards = os.listdir(dataCardPath) origDir = os.path.abspath('./') os.chdir(binaryDir) for dataCard in dataCards: cardFile = dataCardPath+'/'+dataCard logFile = logPath+'/'+dataCard+'.log' if(os.path.isfile(cardFile)): print color.yellow('Now running ' + dataCard) command = binaryPath + ' < ' + cardFile + ' > ' + logFile if(debug): print color.blue('Command is:') print color.blue(command) timeStart = time.time() os.system(command) timeEnd = time.time() print color.yellow('Test ' + dataCard + ' finisehd, elapsed time [s]: ' + str(timeEnd - timeStart)) if(os.path.isfile(logFile)): print color.green('Log file ' + logFile + ' created') else: print color.red('WARNING: log file ' + logFile + ' was not created - something goes wrong!!!' ) else: print color.yellow(dataCard + ' not a file, skipping...') os.chdir(origDir)
def stringDiffByLines(str1, str2): # color.warn('actual') # beatyPrint(str1) # color.warn('expected') # beatyPrint(str2) if isinstance(str1, str): color.red('actual') color.green(str1) color.red('expected') color.warn(str2) colorDiff.do(str1, str2) assert str1.strip() == str2.strip(), "not equal" else: color.red('actual') print(str1) color.red('expected') print(str2) assert str1 == str2, "not equal"
def main(args): """Install the dotfiles.""" clone_or_update(REPOSITORY, DOTFILES_PATH) symlink_files(args) for d in ("~/.vim/temp/temp", "~/.vim/temp/backup", "~/.config/nvim"): os.makedirs(os.path.expanduser(d), exist_ok=True) if args.with_apps: install_apps() if args.with_settings: run_settings() print(color.green("\nInstall complete."))
def test_combination(): print tpl = color.green('the quick {} jump over the {} dog') f = tpl.format( color.yellow('brown fox'), color.red_bg('lazy'), ) print repr(f) print f tpl = color.green_bg('the quick {} jump over the {} dog') f = tpl.format( color.yellow('brown fox'), color.red_bg('lazy'), ) print repr(f) print f
def symlink(args): """Symlink the files.""" print(color.green("\nSymlinking configuration files...")) for f in CONFIGURATION_FILES: if isinstance(f, (tuple, list)): symlink_configuration_file( *f, base_path=args.symlink_base, force=args.symlink_force, dry_run=args.dry_run, ) else: symlink_configuration_file( f, base_path=args.symlink_base, force=args.symlink_force, dry_run=args.dry_run, )
def getEditInfo(originalItem, eqdb, disciplineSource, topicSource, softwareSource, testMode): ''' Main function that collects information for new version of lab entry Args: originalItem (pjlDB._LabItem) individual lab item generated by pjlDB eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB disiplineSource (str) path of file that contains all valid disciplines topicSource (str) path of file that contains all valid topics testMode (bool) allows script to be run in testing mode. No output written. Return: originalItem (pjlDB._LabItem) updated individual lab item updatedVersion (dict) new information related to an updated version ''' if debug: print(color.green("[Debug - getEditInfo] entering")) print("Editing info for \"" + originalItem.name + "\".") originalItem.equipment = getEquipList(eqdb, originalItem) print("") originalItem.software = getSoftwareList(originalItem, softwareSource) print("") originalItem.disciplines = getDisciplineList(originalItem, disciplineSource) print("") originalItem.topics = getTopicList(originalItem, topicSource) print("") updatedVersion = {} if input(color.yellow("Would you like to updated a version of lab? y/N ") ).lower() == "y": # if not testMode: updatedVersion = updateVersionInfo(originalItem) originalItem.versions = updateVersion(originalItem, updatedVersion) # else: # updatedVersion = {'course': 'PHYS 227', 'semester': 'Fall', 'year': '2019', 'originalDir': '/home/pgimby/labs/under-construction/227FA2019/0023/', 'pdf': 'Lab-01-IntroToComputationalModelling.pdf', 'directory': '/data/repository/0023-Introduction-to-3D-Computational-Modelling/0023-PHYS227FA2019', 'labFolder': '/data/repository/0023-Introduction-to-3D-Computational-Modelling/', 'path': '/data/repository/0023-Introduction-to-3D-Computational-Modelling/0023-PHYS227FA2019/Lab-01-IntroToComputationalModelling.pdf'} # tmp = updateVersion(originalItem,updatedVersion) # print("") #moveVersionDir(updatedVersion,root) #tmp2 = validDB(updatedVersion,originalItem,labdb) #print(tmp2) return originalItem, updatedVersion
def create_new_case(prefix, case_name, topo, document, project): """create new case through the name and topo of case""" print(green("Create New Testcase NAME:%s, TOPO:%s" % (case_name, topo))) if topo == "": case_title = "{}: {}".format(prefix, case_name) else: case_title = "{}: {} FUNC={}".format(prefix, case_name, topo) try: case_item = TestCase.create(project, title=case_title, desc="", caseimportance="high", caseautomation="automated", caseposneg="positive", caselevel="component", testtype="functional", subtype1="-") document.move_work_item_here(case_item.work_item_id, None) except: return create_new_case(prefix, case_name, topo, document, project) return case_item.work_item_id
def addEquipItem(eqdb, itemId): ''' Adds a new piece of equipment to a lab object Args: eqdb (pjlDB.EquipDB) entire equipment inventory database object generated by pjlDB itemId (str) equipment id number entered by user Return: equipItem (dict) dicitonary for single equipment item ''' if debug: print(color.green("[Debug - addEquipIten] entering")) equipItem = {} validItem = False validAlt = False validNum = False itemName = "" altName = "" amount = "" # adds main item while not validItem: if itemId == "retry": itemId = input(color.yellow("Enter the equipment id number: ")) validItem, itemName, itemError = equipValid(eqdb, itemId) if not validItem: print(itemError) if input(color.yellow( "Do you wish to try again? Y/n: ")).lower() == "n": break else: itemId = "retry" else: equipItem['id'] = itemId equipItem['name'] = itemName validItem = True # adds alternate item while not validAlt: altId = input( color.yellow( "Enter id number of an alternate for this item. If none hit Enter. " )) if not altId == "": validAlt, altName, altError = equipValid(eqdb, altId) if not validAlt: print(altError) if input(color.yellow( "Do you wish to try again? Y/n: ")).lower() == "n": break else: altId = "" altName = "" validAlt = False else: equipItem['alt-name'] = altName equipItem['alt-id'] = altId validAlt = True else: equipItem['alt-name'] = "" equipItem['alt-id'] = "" validAlt = True # adds the number of units needed while not validNum: amount = input( color.yellow("Please enter how many " + itemName + "(s) are needed? ")) if amount.isdigit(): equipItem['amount'] = amount validNum = True else: print(color.cyan(amount + " is not a valid number.")) if input(color.yellow( "Do you wish to try again? Y/n: ")).lower() == "n": break equipItem["id"] = itemId return equipItem
def get_dtls_info(pkt): global dtlspacketcount, dtlsversions, negotiateddtlsciphers try: dtlspkt = pkt.dtls dtlspacketcount = dtlspacketcount + 1 handshake = dtlspkt.handshake if handshake == 'Handshake Protocol: Client Hello': dtlshost = get_host_contacted(pkt) # print(pkt) maxdtlsversion = 0 ciphersuitelist = [] destination_host = get_host_contacted(pkt) for field_line in dtlspkt._get_all_field_lines(): if field_line.startswith('\tVersion: '): intdtlsversion = extract_intval(field_line) if intdtlsversion > maxdtlsversion: # Newer DTLS version than we've seen so far maxdtlsversion = intdtlsversion dtlsversion = extract_property( field_line, 'Version') if field_line.startswith('\tCipher Suite: '): ciphersuite = extract_property( field_line, 'Cipher Suite') if ciphersuite not in requesteddtlsciphers: requesteddtlsciphers.append(ciphersuite) if ciphersuite in mandatory_ciphers: ciphersuite = color.bright( color.green(ciphersuite)) elif ciphersuite in optional_ciphers: ciphersuite = color.bright(ciphersuite) ciphersuitelist.append(ciphersuite) # print('%s: %s' % # (color.bright('Cipher suite'), ciphersuite)) # Add host to list of hosts contacted per DTLS version dtlsversions = addonlynew( dtlsversions, dtlsversion, dtlshost) if str(dtlsversion) == 'DTLS 1.2': dtlsversion = color.green(dtlsversion) else: dtlsversion = color.red(dtlsversion) if args.verbose: print('Client request handshake with %s: %s' % (destination_host, color.bright(dtlsversion))) for ciphersuite in ciphersuitelist: if args.verbose: print('%s: %s' % ('Client-supported cipher suite', ciphersuite)) elif handshake == 'Handshake Protocol: Server Hello': dtlshost = get_source_host(pkt) #print('Server hello!') negotiated_ciphersuite = pkt.dtls.handshake_ciphersuite.showname negotiated_ciphersuite = extract_notab_property( negotiated_ciphersuite, 'Cipher Suite') # print('*** Negotiated DTLS ciphersuite: %s' % # negotiated_ciphersuite) # if negotiated_ciphersuite not in negotiateddtlsciphers: # negotiateddtlsciphers.append(negotiated_ciphersuite) negotiateddtlsciphers = addonlynew( negotiateddtlsciphers, negotiated_ciphersuite, dtlshost) if args.verbose: print('Negotiated ciphersuite with %s: %s' % (dtlshost, color.bright(negotiated_ciphersuite))) print('***********') except AttributeError: pass
def install_apps(): print(color.green("\nInstall apps...")) run([os.path.join(DOTFILES_PATH, "install/install-apps-all.sh")])
for line in g.stdout.xreadlines(): print " ", line.strip() assert g.wait() == 0 for publisher in publish_to: check_prog = "%s/check_%s.py" % (root, publisher) if not os.path.exists(check_prog): check_prog = "%s/check_root.py" % (root,) update_prog = "%s/update_%s.py" % (root, publisher) assert os.path.exists(update_prog), update_prog print " Checking", publisher c = subprocess.Popen("python -u %s %s" % (check_prog, domain), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) for line in c.stdout.xreadlines(): print " ", line.strip() retcode = c.wait() if retcode != 0: print color.yellow(" Need to update!") u = subprocess.Popen("python -u %s %s" % (update_prog, domain), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1) for line in u.stdout.xreadlines(): print " ", line.strip() retcode = u.wait() if retcode != 0: print color.red(" Update failed!") else: print color.green(" Update successful!") else: print color.green(" Everything up to date!") os.chdir(curdir)
def generate_report(app, pcapfile=''): ''' Print report based on collected data ''' global sslpacketcount if app.endswith('.pcap'): app_or_pcap = 'pcap' jsonfile = '%s.%s' % (pcapfile, json_output) else: app_or_pcap = 'application' jsonfile = os.path.join(os.path.dirname(pcapfile), json_output) report = {} report['app'] = app report['testtime'] = os.path.getmtime(pcapfile) report['sslversions'] = net.sslversions report['requestedciphers'] = net.requestedciphers report['negotiatedciphers'] = net.negotiatedciphers report['dtlsversions'] = net.dtlsversions report['negotiateddtlsciphers'] = net.negotiateddtlsciphers seen_mandatory_ciphers = [] seen_optional_ciphers = [] seen_other_ciphers = [] failedtest = False failedreasons = [] print('') print('Summary for application: %s' % color.bright(color.cyan(app))) print('') if net.sslpacketcount > 0: print(color.bright('TLS/SSL protocols used:')) # For each target (unsorted) for sslversion in net.sslversions: if sslversion == 'TLS 1.2': sslversion = color.bright(color.green(sslversion)) else: failedtest = True failedreasons.append('%s is used, rather than TLS 1.2' % sslversion) sslversion = color.bright(color.red(sslversion)) print(sslversion) print( color.bright('Hosts using %s:' % color.decolorize(sslversion))) for host in net.sslversions[color.decolorize(sslversion)]: print(host) print('') for ciphersuite in net.requestedciphers: if ciphersuite in net.mandatory_ciphers: #ciphersuite = color.bright(color.green(ciphersuite)) seen_mandatory_ciphers.append(ciphersuite) elif ciphersuite in net.optional_ciphers: #ciphersuite = color.bright(ciphersuite) seen_optional_ciphers.append(ciphersuite) else: #ciphersuite = color.dim(ciphersuite) seen_other_ciphers.append(ciphersuite) if len(seen_mandatory_ciphers) == 0: failedtest = True failedreasons.append('%s is not supported by client' % net.mandatory_ciphers[0]) print( color.bright( 'Observed mandatory ciphers in TLS/SSL client requests:')) for cipher in seen_mandatory_ciphers: print(color.bright(color.green(cipher))) report['seen_mandatory_ciphers'] = seen_mandatory_ciphers print('') print( color.bright( 'Observed optional ciphers in TLS/SSL client requests:')) for cipher in seen_optional_ciphers: print(cipher) report['seen_optional_ciphers'] = seen_optional_ciphers print('') print( color.bright('Observed other ciphers in TLS/SSL client requests:')) for cipher in seen_other_ciphers: print(color.dim(cipher)) report['seen_other_ciphers'] = seen_other_ciphers print('') print(color.bright('Negotiated TLS/SSL ciphers:')) for ciphersuite in net.negotiatedciphers: if ciphersuite in net.mandatory_ciphers: ciphersuite = color.bright(color.green(ciphersuite)) elif ciphersuite in net.optional_ciphers: pass #ciphersuite = color.bright(ciphersuite) else: ciphersuite = color.dim(ciphersuite) print(ciphersuite) print( color.bright('Hosts using %s:' % color.decolorize(ciphersuite))) for host in net.negotiatedciphers[color.decolorize(ciphersuite)]: print(host) print('') print('') else: print(color.bright(color.green('No TLS/SSL traffic seen'))) print('') if net.dtlspacketcount > 0: print(color.bright('DTLS protocols used:')) # For each target (unsorted) for dtlsversion in net.dtlsversions: if dtlsversion == 'DTLS 1.2': dtlsversion = color.bright(color.green(dtlsversion)) else: failedtest = True failedreasons.append('%s is used, rather than DTLS 1.2' % dtlsversion) dtlsversion = color.bright(color.red(dtlsversion)) print(dtlsversion) print( color.bright('Hosts using %s:' % color.decolorize(dtlsversion))) for host in net.dtlsversions[color.decolorize(dtlsversion)]: print(host) print('') report['dtlsciphers'] = net.requesteddtlsciphers for ciphersuite in net.requesteddtlsciphers: if ciphersuite in net.mandatory_ciphers: #ciphersuite = color.bright(color.green(ciphersuite)) seen_mandatory_ciphers.append(ciphersuite) elif ciphersuite in net.optional_ciphers: #ciphersuite = color.bright(ciphersuite) seen_optional_ciphers.append(ciphersuite) else: #ciphersuite = color.dim(ciphersuite) seen_other_ciphers.append(ciphersuite) if len(seen_mandatory_ciphers) == 0: failedtest = True failedreasons.append('%s is not supported by client' % net.mandatory_ciphers[0]) print( color.bright( 'Observed mandatory ciphers in DTLS client requests:')) for cipher in seen_mandatory_ciphers: print(color.bright(color.green(cipher))) print('') report['seen_mandatory_dtls_ciphers'] = seen_mandatory_ciphers print( color.bright('Observed optional ciphers in DTLS client requests:')) for cipher in seen_optional_ciphers: print(cipher) print('') report['seen_optional_dtls_ciphers'] = seen_optional_ciphers print(color.bright('Observed other ciphers in DTLS client requests:')) for cipher in seen_other_ciphers: print(color.dim(cipher)) print('') report['seen_other_dtls_ciphers'] = seen_other_ciphers print(color.bright('Negotiated DTLS ciphers:')) for ciphersuite in net.negotiateddtlsciphers: if ciphersuite in net.mandatory_ciphers: ciphersuite = color.bright(color.green(ciphersuite)) elif ciphersuite in net.optional_ciphers: pass #ciphersuite = color.bright(ciphersuite) else: ciphersuite = color.dim(ciphersuite) print(ciphersuite) print( color.bright('Hosts using %s:' % color.decolorize(ciphersuite))) for host in net.negotiateddtlsciphers[color.decolorize( ciphersuite)]: print(host) print('') print('') else: print(color.bright(color.green('No DTLS traffic seen'))) report['failedtest'] = failedtest report['failedreasons'] = failedreasons if failedtest: print( color.bright( color.red('App %s failed crypto checking because:' % app))) for reason in failedreasons: print(color.bright(color.red(reason))) else: print(color.bright(color.green('App %s passed crypto checking' % app))) # print(report) with open(jsonfile, 'w') as fp: json.dump(report, fp)
print("Adding new lab.") lab = labdb.newLab(labdb.new_id) newLabInfo = getNewLabInfo(lab, testMode) lab.name = newLabInfo["name"] lab.type = newLabInfo["type"] confirmEntry(newLabInfo) if validDB(newLabInfo, lab, labdb): if not testMode: os.system("mkdir " + newLabInfo["labFolderPath"]) moveVersionDir(newLabInfo, root) addSupportFolder(newLabInfo, root) labdb.addLab(lab) labdb.save(destXML, ignore_validation=validate, error_log=True) else: os.system("echo mkdir " + newLabInfo["labFolder"]) labdb.addLab(lab) labdb.save(destXML, ignore_validation=validate, error_log=True) if args.edit: print("Editing existing lab.") lab = getLabObject(labdb) if debug: print(color.green("[Debug - edit] ")) lab, versionInfo = getEditInfo(lab, eqdb, disciplineSource, topicSource, softwareSource, testMode) if displayLabItem(lab): labdb.save(destXML, ignore_validation=validate, error_log=True) if bool(versionInfo): moveVersionDir(versionInfo, root) '''confirms that the script has ended properly''' print("...and then there will be cake")
def run_settings(): print(color.green("\nSettings things up...")) run([os.path.join(DOTFILES_PATH, "install/set-config-all.sh")])
def visual(self): color.green() glRotate(90 + self.vector[0],0,1,0) glRotate(-self.vector[1],1,0,0) glutSolidCone(0.2,1,10,10)
def get_ssl_info(pkt): global sslpacketcount, sslversions, negotiatedciphers try: # Assume SSLv3 or TLS sslpkt = pkt.ssl sslpacketcount = sslpacketcount + 1 handshake = sslpkt.handshake if handshake == 'Handshake Protocol: Client Hello': # print(pkt) maxsslversion = 0 ciphersuitelist = [] sslhost = get_host_contacted(pkt) for field_line in sslpkt._get_all_field_lines(): if field_line.startswith('\tVersion: '): intsslversion = extract_intval(field_line) if intsslversion > maxsslversion: # Newer SSL/TLS version than we've seen so far maxsslversion = intsslversion sslversion = extract_property( field_line, 'Version') if field_line.startswith('\tCipher Suite: '): ciphersuite = extract_property( field_line, 'Cipher Suite') if ciphersuite not in requestedciphers: requestedciphers.append(ciphersuite) if ciphersuite in mandatory_ciphers: ciphersuite = color.bright( color.green(ciphersuite)) elif ciphersuite in optional_ciphers: ciphersuite = color.bright(ciphersuite) ciphersuitelist.append(ciphersuite) # print('%s: %s' % # (color.bright('Cipher suite'), ciphersuite)) # Add host to list of hosts contacted per SSL version sslversions = addonlynew( sslversions, sslversion, sslhost) if str(sslversion) == 'TLS 1.2': sslversion = color.green(sslversion) else: sslversion = color.red(sslversion) if args.verbose: print('Client request handshake with %s: %s' % (sslhost, color.bright(sslversion))) for ciphersuite in ciphersuitelist: if args.verbose: print('%s: %s' % ('Client-supported cipher suite', ciphersuite)) elif handshake == 'Handshake Protocol: Server Hello': sslhost = get_source_host(pkt) #print('Server hello!') negotiated_ciphersuite = pkt.ssl.handshake_ciphersuite.showname negotiated_ciphersuite = extract_notab_property( negotiated_ciphersuite, 'Cipher Suite') # print('*** Negotiated SSL/TLS ciphersuite: %s' % # negotiated_ciphersuite) # if negotiated_ciphersuite not in negotiatedciphers: # negotiatedciphers.append(negotiated_ciphersuite) negotiatedciphers = addonlynew( negotiatedciphers, negotiated_ciphersuite, sslhost) if args.verbose: print('Negotiated ciphersuite with %s: %s' % (sslhost, color.bright(negotiated_ciphersuite))) print('***********') except AttributeError: # SSLv2 doesn't have "handshake" structure try: sslpkt = pkt.ssl sslhost = get_host_contacted(pkt) if sslpkt.record == 'SSLv2 Record Layer: Client Hello': sslversion = 'SSLv2' if sslversion not in sslversions: sslversions.append(str(sslversion)) destination_host = get_host_contacted(pkt) if args.verbose: print('Client request handshake with %s: %s' % (destination_host, color.bright(color.red('SSLv2')))) for field_line in sslpkt._get_all_field_lines(): if field_line.startswith('\tCipher Spec: '): ciphersuite = extract_property( field_line, 'Cipher Spec') if ciphersuite not in requestedciphers: requestedciphers.append(ciphersuite) if ciphersuite in mandatory_ciphers: ciphersuite = color.bright( color.green(ciphersuite)) elif ciphersuite in optional_ciphers: ciphersuite = color.bright(ciphersuite) if args.verbose: print('%s: %s' % ('Client-supported cipher spec', ciphersuite)) elif sslpkt.record == 'SSLv2 Record Layer: Server Hello': negotiated_cipherspec = pkt.ssl.handshake_cipherspec.showname negotiated_cipherspec = extract_notab_property( negotiated_cipherspec, 'Cipher Spec') if negotiated_cipherspec not in negotiatedciphers: negotiatedciphers.append(negotiated_cipherspec) if negotiated_cipherspec not in optional_ciphers and negotiated_cipherspec not in mandatory_ciphers: negotiated_cipherspec = color.red( negotiated_cipherspec) destination_host = get_source_host(pkt) if args.verbose: print('Negotiated cipherspec with %s: %s' % (destination_host, color.bright(negotiated_cipherspec))) print('***********') except AttributeError: pass
def visual(self): color.green() glutSolidSphere(self.colornum,10,10)
# model.add(Dense(1)) # # mean_squared_error, mean_squared_error # model.compile(loss='mse', optimizer='rmsprop', metrics=['accuracy']) # model.summary() model = Sequential() model.add(Dense(units=16, input_shape=(len(data[0]), 6))) model.add(Dense(units=12)) model.add(Dense(units=1)) # mean_squared_error, mean_squared_error model.compile(loss='mse', optimizer='rmsprop', metrics=['accuracy']) model.summary() print(color.green('Starting training')) history = model.fit(data, target, epochs=100) model.save('train.model') plt.plot(history.history['loss']) plt.show() sys.exit() #print((y_test*100).tolist()) #print(x_test.tolist()) # print(color.cyan(int(model.predict(np.array([[[101./100], [101./100], [103./100], [104./100], [105./100]]], dtype=float))[0][0]*100))) # print(model.predict(x_test).tolist()) result = model.predict(data) print(color.yellow(data.tolist()))
# thousandparsec.com. IN DS 57841 5 2 DEA43569E59B6F2FEB99B799BCD39927769A3CA369A846122DE11595 D31A728A ds_domain, in_, ds_, keytag, algorithm, digest_type, digest = line.split(None, 6) new_records.append({ 'digest': "".join(digest.split()), 'digestType': digest_type, 'algorithm': algorithm, 'keyTag': keytag, 'maxSigLife': str(3600*24*90), # FIXME(tansell): Defaulting to 90 days... }) to_add = [] for dsrecord in sorted(current_records): dsid = dsrecord['keyTag']+" "+str(dsrecord['algorithm']) if dsrecord in new_records: print color.green("Current %s" % dsid) else: print color.red("Removing %s" % dsid) req = DeleteRequest( url="https://www.gkg.net/ws/domain/%s/ds/%s" % (domain, dsrecord['digest']), ) print urllib2.urlopen(req).read() for dsrecord in sorted(new_records): if dsrecord in current_records: continue dsid = dsrecord['keyTag']+" "+str(dsrecord['algorithm']) print color.yellow("Adding %s" % dsid) url = "https://www.gkg.net/ws/domain/%s/ds" % domain r = urllib2.urlopen(url, data=simplejson.dumps(dsrecord))
def copmare_2_texts(actual, expected, self): color.green ("actual") print(actual) color.green ("expected") print(expected) actualLines = actual.split('\n') expectedLines = expected.split('\n') color.green("actualLines") print(actualLines) color.green("expectedLines") print(expectedLines) zipped = zip(actualLines, expectedLines) color.green ("zipped") print(zipped) color.green ("compare zipped") color.blue("comparing") for i,j in zipped: color.green (i) color.red (j) self.assertEqual(i.strip(),j.strip())
def lsregions():# {{{ for r in boto.ec2.regions(): print(green(r.name))
def visual(self): color.green() glutSolidSphere(self.colornum, 10, 10)
def infomsg (text): print (green( "[info] %s" % (text) ) )
# Size of data transfered size = len(r.content) req['size'] += size # Method method = str(r.request)[18:-2] # Print request data print( color.blue('HTTP/1.1 ', status, '\t', time, 'secs:\t', size, 'bytes ==> ', method, '\t', url)) hits += 1 i += 1 print(color.green('\nTransactions:\t\t\t', req['trans'], '\thits')) print( color.green('Availability:\t\t\t', (req['success'] * 100) / req['trans'], '\t%')) print(color.green('Elapsed time:\t\t\t', round(req['time'], 2), '\tsecs')) print( color.green('Data transfered:\t\t', round(req['size'] / 1048576, 2), '\tMB')) print( color.green('Response time:\t\t\t', round(req['time'] / req['trans'], 2), '\tsecs')) print( color.green('Transaction rate:\t\t', round(req['trans'] / req['time'], 2), '\ttrans/sec')) print( color.green('Throughput:\t\t\t',