Exemplo n.º 1
0
Arquivo: Qbot.py Projeto: qria/Qbot
def jama_representation(jama_count):
    if jama_count > 1080:
        return red('●●●●●●')
    small = jama_count % 6
    big = (jama_count % 30) // 6
    gem = (jama_count % 180) // 30
    return red('●'* gem) + '◎'* big + 'o' * small
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 test_testName(self):
		color.blue("test here baby")
		inputText = """if inlist:
			print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
			color.red('inlist')
			print(inlist)
			print('*****************************************************************')
			currentIndex = allList.index(current) #todo: make test to test when current item not in list
			chooseNumber =  currentIndex + 1
			if chooseNumber >= len(allList):"""
		filename = os.path.join(currentFolder, 'files/printColor.poligon')

		filer.write(filename, inputText)

		clear.pyFile(filename)
		result = filer.read(filename)
		
		expected = """if inlist:
			currentIndex = allList.index(current) #todo: make test to test when current item not in list
			chooseNumber =  currentIndex + 1
			if chooseNumber >= len(allList):"""
		print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
		color.red('expected')
		print(expected)
		print('*****************************************************************')	
		self.assertEqual(result, expected)
Exemplo n.º 4
0
	def test_testName(self):
		color.blue("test here baby")
		inputText = """
	def test_testName(self):
		color.blue("test here baby")
		intpuText = 
		beatyModel.py(inputText)	
	def test_testName(self):
		color.blue("test here baby")
		intpuText = 
		beatyModel.py(inputText)"""
		filename = os.path.join(currentFolder, 'files/poligon')
		filer.write(filename, inputText)
		expected = """\tdef test_testName(self):
		color.blue("test here baby")
		intpuText = 
		beatyModel.py(inputText)


	def test_testName(self):
		color.blue("test here baby")
		intpuText = 
		beatyModel.py(inputText)
		"""
		beatyModel.pyFile(filename)	
		result = filer.read(filename)
		color.red("inputText")
		print(repr(inputText))
		print(inputText)
		assertMy.stringDiffByLines(result, expected)
def splitArgs(commaStringArgs):
    commaStringArgs = commaStringArgs.strip()
    if len(commaStringArgs)==0:
        return []
    else:
        color.red("commaStringArgs")
        print(commaStringArgs)
        ### comma split - split for different args###
        args = commaStringArgs.split(",")
        print("args")
        print(args)
        varTypeStructureList = []
        ### reversing for args like (arg1, arg2 string) - to get first args with type ###
        argsReversed = reversed(args)
        for arg in argsReversed:
            arg = arg.strip()
            print("arg")
            print(arg)
            ### space split - split for arg name and type ###
            argParts = arg.split(" ")
            color.red("argParts")
            print(argParts)
            ### first - it is var name, second = var type ###
            thereIsType = len(argParts)==2
            if thereIsType:
                (var, varType) = argParts
                lastOkType = varType
            else:
                var = argParts[0]
                varType = lastOkType
            varTypeStructure=generateVarTypeStructure(var, varType)
            varTypeStructureList.append(varTypeStructure)
        ### reverse back ###
        return varTypeStructureList[::-1]
Exemplo n.º 6
0
def do(str1, str2):
    if str1 is None:
        str1 = ""
    len1 = len(str1)
    len2 = len(str2)
    splited1 = list(str1)
    splited2 = list(str2)
    short = splited1 if len1 < len2 else splited2
    if len1 != len2:
        add = range(0,abs(len2-len1))
       
        for i in add:
            
            short += "_"
      
    zipped = zip(splited1, splited2)
    colorStr1 = colorStr2 = ''
    for (i, j) in zipped:
        
        
        
        iRepr = util.goodRepr(i)
        jRepr = util.goodRepr(j)
        if i == j:
            colorStr1 += color.color(iRepr, 'green')    
            colorStr2 += color.color(jRepr, 'green')    
        else:
            colorStr1 += color.color(iRepr, 'red')  
            colorStr2 += color.color(jRepr, 'yellow')   
    color.red('diff:')        
    print(colorStr1)        
    print(colorStr2)
Exemplo n.º 7
0
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
Exemplo n.º 8
0
 def test_testName(self):
     color.blue("test here baby")
     result = util.goodRepr("\n")
     print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
     color.red("result")
     print(result)
     print("*****************************************************************")
Exemplo n.º 9
0
Arquivo: center.py Projeto: mnms/share
    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
Exemplo n.º 10
0
def test_named_colors():
    for i in color_names:
        print(getattr(color, i)(i) + color.red('compare'))
        print(
            color.black(getattr(color, i + '_bg')(i + '_bg')) +
            color.red('compare'))
        print(getattr(color, i + '_hl')(i + '_hl') + color.red('compare'))
Exemplo n.º 11
0
def filename2(filename, obj):

    data = filer.read(filename)

    color.red("obj")
    print(repr(obj))

    regex = "(\S+) as " + obj

    color.red("regex")
    print(repr(regex))

    m = re.findall(regex, data)
    match = len(m)
    if match:
        obj = m[0]

    # folder = os.path.join(os.path.dirname(filename), obj+ '.py')
    rel2 = "./" + obj
    filename2 = absRel.AbsAddExtension(filename, rel2)
    if not os.path.isfile(filename2):
        regex2 = "sys.path.insert\(0, '(.+)'\)"
        matches = re.findall(regex2, data)
        for m in matches:
            filename2 = os.path.join(m, obj + ".py")
            if os.path.isfile(filename2):
                break
    if not os.path.isfile(filename2):
        filename2 = filename
    return filename2
def generateFuncUsageByLineContentGo(lineContent):

    # get func parts:
    (caller, method, args, returnParams) = g.getGoFuncDeclarationPartsByLineContent(lineContent)
    returnParamsSplitedList = g.splitArgs(returnParams)
    color.red("returnParamsSplitedList")
    print(returnParamsSplitedList)

     # split args
    argsSplitedList = g.splitArgs(args)
    # get vars commas str
    (_, varsCommasStr, _) = g.getVarBlockByStructureListOfNameTypeName(argsSplitedList)    
    # get return params comma string
    (_, returnParamsCommasStr, _) = g.getVarBlockByStructureListOfNameTypeName(returnParamsSplitedList)    

    callerVarName = g.getCallerVarName(caller)


    funcCall = g.innerTestFuncPartGoTestPrepare_callTestableFunc(callerVarName, method, returnParamsCommasStr, varsCommasStr)

    # get var block and add before funcCall
    (varBlock, _, _) = getVarBlock(caller, args, returnParams)

    # func usage total
    funcUsageTotal = "/*{}*/\n{}".format(varBlock, funcCall)
    return funcUsageTotal
	def test_testName(self):
		color.blue("test here baby")
		inputText = """
	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')

	 


	def testFolder(self):	
		self.dataFolder = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/workflow/testData"
"""
		expected = """
	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')


	def testFolder(self):	
		self.dataFolder = "/Users/maks/Library/Application Support/Sublime Text 3/Packages/workflow/testData"
		"""
		result = beatyModel.py(inputText)	
		color.red("inputText")
		print(repr(inputText))
		print(inputText)
		assertMy.stringDiffByLines(result, expected)
Exemplo n.º 14
0
Arquivo: center.py Projeto: mnms/share
 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
Exemplo n.º 15
0
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 test_testName(self):
		color.blue("test here baby")
		inputText = """
	def dataFile(self):
		return os.path.join (self.dataFolder, 'iterations.data')






	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')
"""
		expected = """
	def dataFile(self):
		return os.path.join (self.dataFolder, 'iterations.data')


	def currentFile(self):
		return os.path.join (self.dataFolder, 'current.data')"""
		result = beatyModel.py(inputText)	
		color.red("inputText")
		print(repr(inputText))
		print(inputText)
		assertMy.stringDiffByLines(result, expected)
def removeAfterModuleExports(fileContent):
    color.red("fileContent in relativeRequireIced_model.py")
    print(fileContent)
    sub = "module.exports"
    if sub in fileContent:
        index = fileContent.index(sub)
        fileContent = fileContent[:index]
    return fileContent
	def test_testName(self):
		inputText = repr("'")
		result = util.replaceLastAndFirstQuotes(inputText)

		print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
		color.red('result')
		print(repr(result))
		print('*****************************************************************')
def removeRowsStartingFromSpace(fileContent):
    # should remove the second and third strings from the following content:
    # module.exports = (input, test)->
    # 	th.log "input"
    # 	th.log input
    fileContentWithouIntendedRows = re.sub(r"\n\s+.*", "", fileContent)
    color.red("fileContentWithouIntendedRows in py")
    print(fileContentWithouIntendedRows)
    return fileContentWithouIntendedRows
	def test_testName(self):
		clip = """File "/Users/maks/Library/Application Support/Sublime Text 3/Packages/navigateTo/findRequire_test.py", line 17"""



		result = pyOutPutParse.parse(clip)
		color.red('result')
		print(result)
		self.assertEqual(result, ['/Users/maks/Library/Application Support/Sublime Text 3/Packages/navigateTo/findRequire_test.py:17'])
 def run(self, edit):
     color.red ("duplicate line called")
     for region in self.view.sel():
         if region.empty():
             line = self.view.line(region)
             line_contents = self.view.substr(line) + '\n'
             self.view.insert(edit, line.begin(), line_contents)
         else:
             self.view.insert(edit, region.begin(), self.view.substr(region))
Exemplo n.º 22
0
def createFromPosition(filename, position):
	### read from file ###
	text = filer2.read(filename)
	### get method name ###
	methodName = navigateToModel.method(text, position)
	color.red('methodName')
	print(repr(methodName))
	### generate test file and write it to disk ###
	return create(filename, methodName)
Exemplo n.º 23
0
def clearEmptyLines(text):
	regex = '\n*\s*\n+'
	m = re.findall(regex, text)
	color.red('m')
	print(repr(m))
	result = re.sub(regex, '\n', text)

	
	return result	
	def test_testName(self):
		color.blue("test here baby")
		inputText = """import sublime
import sublime_plugin
import os
from os import listdir
from os.path import isfile, join
import sys
sys.path.insert(0, '/Users/maks/Library/Application Support/Sublime Text 3/Packages/goodPath')

import findAllRelative_model
class repaire_relative_paths_plugin_Command(sublime_plugin.WindowCommand):
    def run(self):
       print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
       print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
       print("new run repaire_relative_paths_plugin_")
       print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
       print('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++')
       window = self.window
       view = window.active_view()
       filename = view.file_name()
       findAllRelative_model.goAndWrite(filename)
       sublime.status_message("repaire_relative_paths_plugin done")
       


"""
		filename = os.path.join(currentFolder, 'files/printColor.poligon')

		filer.write(filename, inputText)

		clear.pyFile(filename)
		result = filer.read(filename)
		
		color.red('result')
		print(repr(result))

		expected = """import sublime
import sublime_plugin
import os
from os import listdir
from os.path import isfile, join
import sys
sys.path.insert(0, '/Users/maks/Library/Application Support/Sublime Text 3/Packages/goodPath')
import findAllRelative_model
class repaire_relative_paths_plugin_Command(sublime_plugin.WindowCommand):
    def run(self):
       window = self.window
       view = window.active_view()
       filename = view.file_name()
       findAllRelative_model.goAndWrite(filename)
       sublime.status_message("repaire_relative_paths_plugin done")"""
		color.red('expected')
		print(expected)
		
		assertMy.stringDiffByLines(result, expected	)
Exemplo n.º 25
0
def getDataCardNames(dataCardPath):
    if not(os.path.isdir(dataCardPath)):
        print color.red('Data card file ' + dataCardPath + ' does not exist - EXIT!')
        sys.exit(1)
    dataCardNames = []
    dataCards = os.listdir(dataCardPath)
    for card in dataCards:
        if(os.path.isfile(dataCardPath+'/'+card)):
            dataCardNames.append(card)
    return dataCardNames
Exemplo n.º 26
0
	def test_testName(self):
		color.blue("test here baby")
		findUsagesModel = FindUsagesModel(os.path.join(currentFolder, 'dataPoligon/'))
		findUsagesModel.i.currentSet(('/path/to/first.py', 1))
		result = findUsagesModel.next()

		color.red('result')
		print(repr(result))
		expected = ('/path/to/second.py', 2, '2 of 3')
		assertMy.equals(result, expected)
Exemplo n.º 27
0
def findRequire(text, objectName):
    regex = "{} =.+'(.+)'".format(objectName)
    
    color.red('regex')
    print(repr(regex))
    result = re.findall(regex, text)
    if len(result):
        return result[0]
    else:
        return None
	def test_testName(self):
		color.blue("test here baby")
		inputText = repr('\n')
		result = util.replaceLastAndFirstQuotes(inputText)		

		color.red('inputText')
		print(inputText)

		color.red('result')
		print(result)
def writeTestFileBySourceFileTargetAndPosition(targetFileName, position):
    ### read target file name ###
    targetFileContent = filer2.read(targetFileName)
    ### generate test file content by targetFileContent and position ###
    testFileContent = createTestFileContentBySourceFileTargetAndPosition(targetFileContent, position)
    color.red("testFileContent")
    print(testFileContent)

    methodName = getMethodNameByFileContentAndPosition(targetFileContent, position)
    return create(targetFileName, methodName, testFileContent)
Exemplo n.º 30
0
	def test_testName(self):
		color.blue("test here baby")
		filename = os.path.abspath(os.path.join(currentFolder, '../../util/filer2.py'))
		position = 131
		findUsagesModel = FindUsagesModel(os.path.join(currentFolder, 'dataPoligon2/'))
		result = findUsagesModel.find(filename, position)
		color.red('result')
		print(repr(result))
		expected = (os.path.abspath(os.path.join(currentFolder, '../../util/replace_require_test.py')), 1194, "2 of 2")
		self.assertEquals(result, expected)
def coffeeCompile(filename):
    bashCommand = 'coffee -cb "{}"'.format(filename)
    color.red("bashCommand")
    print(bashCommand)

    #    process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE)
    #    output = process.communicate()[0]

    #    import subprocess
    # subprocess.Popen(bashCommand)
    bash.run_script(bashCommand)
def getArgsByLineContentGo(lineContent):
    color.red("lineContent")
    print(lineContent)
    regex = re.compile(r"\S\(([^\(]+)\)")
    m = regex.findall(lineContent)
    if m:
        lastGroup = m[-1]
        result = lastGroup
        return result
    else:
        return ""
Exemplo n.º 33
0
def getReturnParamsForAutocbCommaSeparated(fileContent): # cb arg1, arg2
	fileContent = fileContent.strip()
	m = re.findall(r"cb (.+)", fileContent)

	if m:

		commaSeparatedArgs = m[-1]
		color.red("commaSeparatedArgs")
		print(commaSeparatedArgs)
		return replaceNullByErr(commaSeparatedArgs)
	else:
		return "()" # no params for func: (cb)->
Exemplo n.º 34
0
def returnParamsForSyncExpressionOrReturn(targetFileContent):
	returnParams = justArgsForSync(targetFileContent)	
	color.red ("returnParams")
	print (returnParams)
	if returnParams == 'actual':
		
		returnParamsExpression = returnArgsByExpressionWithoutWordReturn(targetFileContent)
		color.red("returnParamsExpression")
		print(returnParamsExpression)
		if not returnParamsExpression == "exports": # exception	
			returnParams = returnParamsExpression
	return returnParams
Exemplo n.º 35
0
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 -------')
Exemplo n.º 36
0
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)
Exemplo n.º 37
0
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
Exemplo n.º 38
0
def check_app(app):
    failedssltest = False
    badrequests = []

    # Get mitmproxy log file location
    if app.endswith('.log'):
        flowfile = app
        jsonfile = '%s.%s' % (flowfile, json_output)
        if os.path.exists(flowfile):
            sys.stdout = Logger('%s.%s' % (flowfile, report_output))
    else:
        flowfile = os.path.join('results', app, 'ssltest.log')
        jsonfile = os.path.join(os.path.dirname(flowfile), json_output)
        if os.path.exists(flowfile):
            sys.stdout = Logger(os.path.join('results', app, report_output))

    if os.path.exists(flowfile):
        badsslmsgs = []

        with open(flowfile, "rb") as logfile:
            freader = io.FlowReader(logfile)
            pp = pprint.PrettyPrinter(indent=4)
            try:
                for msg in freader.stream():
                    scheme = msg.request.scheme
                    if scheme == 'https':
                        failedssltest = True
                        badsslmsgs.append(msg)
                if failedssltest:
                    ssl_failed.append(app)
                    print(
                        color.bright(
                            '%s fails to validate SSL certificates properly' %
                            app))
                    print('Offending URIs accessed:')
                    for msg in badsslmsgs:
                        method = msg.request.method
                        uri = msg.request.pretty_url
                        request = '%s %s' % (method, uri)
                        badrequests.append(request)
                        request = color.bright(color.red((request)))
                        print(request)
                else:
                    print('No HTTPS traffic detected for app %s' % app)
                    ssl_passed.append(app)
            except FlowReadException as e:
                print("Flow file corrupted: {}".format(e))

        report = {}
        report['app'] = app
        report['testtime'] = os.path.getmtime(flowfile)
        report['failedtest'] = failedssltest
        report['ssl_failed'] = badrequests

        with open(jsonfile, 'w') as fp:
            json.dump(report, fp)

    else:
        ssl_notest.append(app)
Exemplo n.º 39
0
def diff(n1, n2):
    if n2 is None:
        return color.cyan(' %9f') % n1

    if n1 > n2:
        return color.blue('+%9f') % (n1)
    elif n1 < n2:
        return color.red('-%9f') % (n1)
    else:
        return color.yellow(' %9f') % n1
Exemplo n.º 40
0
def set_document(project, document_name):
    # DOC need be created before running the script
    try:
        document = Document(project, document_name, None, None, None)
    except PylarionLibException:
        print(
            red("Error: Can't not open \"KernelNetworkQE/KN-TC Kernel NIC Driver New Test Cases\" "
                "to move new case into it.\n Please create it in polarion.\n"))
        raise
    else:
        return document
Exemplo n.º 41
0
 def render(self):
     clear()
     print(gray("( To exit, hit Ctrl + C )\n\n"))
     count = "(" + str(len(
         self.used_incorrect_letters)) + "/" + str(CHANCES) + ")"
     if (CHANCES - len(self.used_incorrect_letters) < 3):
         count = red(count)
     else:
         count = gray(count)
     render_noose(len(self.used_incorrect_letters))
     print("Used " + count + ": " + " ".join(self.used_incorrect_letters))
     print(self.make_word_bar())
     print(self.make_message_box())
Exemplo n.º 42
0
def get_case_id(case_title_prefix, case_name, topo, document, project, dryrun):
    """get or create case_id"""
    case_name = case_name.replace("/kernel/networking/", "")
    try:
        if topo == "":
            case_list = get_case_id_by_sql(case_title_prefix, case_name, topo,
                                           project)
        else:
            tmp1 = get_case_id_by_sql(case_title_prefix, case_name,
                                      "TOPO=%s" % topo, project)
            tmp2 = get_case_id_by_sql(case_title_prefix, case_name,
                                      "FUNC=%s" % topo, project)
            case_list = tmp1 + tmp2
    except WebFault:
        # retry
        time.sleep(3)
        return get_case_id(case_title_prefix, case_name, topo, document,
                           project, dryrun)
    except PylarionLibException:
        # retry
        time.sleep(3)
        return get_case_id(case_title_prefix, case_name, topo, document,
                           project, dryrun)
    if len(case_list) == 1:
        logger.debug("There is only one %s" % case_list[0].work_item_id)
        return case_list[0].work_item_id
    elif len(case_list) == 0:
        logger.warning("Can't find right case-NAME: {}, TOPO: {}".format(
            case_name, topo))
        if not dryrun:
            try:
                # logger.info("%s can't be found" % case_name)
                return create_new_case(case_title_prefix, case_name, topo,
                                       document, project)
            except:
                logger.error("Can't create new test case automatically.")
                raise
    else:
        # 找到多个,通过“TOPO=” 或者“--FUNC=”过滤case
        logger.error("Find more than one case. \"{}\", \"{}\".".format(
            case_name, topo))
        print(
            red("Find more than one case. \"{}\", \"{}\".".format(
                case_name, topo)))
        with open("fail.csv", "a") as fcsv:
            fcsv.write("Error: Find more than one case-----\n")
            fcsv.write(time.ctime() + "\n")
            fcsv.write("{},{}\n".format(case_name, topo))
        return None
Exemplo n.º 43
0
def testHost(host):
    '''
	Test what computer this being run on. As of now it is machinne specific
	
	Args:
		host (str) name of host script was designed for
	
	Return:
		none
	'''
    thishost = os.uname()[1]
    if thishost not in host:
        print(
            color.red("[ERROR] ") + "This script is designed to be run on " +
            host + " only. Exiting...")
        exit()
Exemplo n.º 44
0
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))
Exemplo n.º 45
0
def addSupportFolder(info, root):
    '''
	adds contents of Support_Docs folder to repository

	Args:
		info (dict) information about new lab object

	Return:
		none
	'''
    originDir = info["originalDir"] + "Support_Docs"
    destinationDir = root + info["labFolder"] + "/Support_Docs"
    if os.path.isdir(originDir):
        if not os.path.isdir(destinationDir):
            print("Support_Docs Folder does not exist. Adding new folder " +
                  destinationDir)
            os.system("mkdir " + destinationDir)
        if os.path.isdir(destinationDir):
            os.system("rsync -avz " + originDir + "/ " + destinationDir)
        else:
            print(color.red("Something when wrong. Exiting..."))
            exit()
Exemplo n.º 46
0
def post_runs(run_ids, case_ids, case_results, case_comments, run_path,
              project, login, run_plannedin, dryrun):
    """posting function which doesn't consider the role of case, compared with post_runs_filter_by_role """
    for index, (case_id, run_id, result, comment) in enumerate(
            zip(case_ids, run_ids, case_results, case_comments)):
        if "%s.xml" % run_id in os.listdir(run_path):
            tr = open("{}/{}.xml".format(run_path, run_id), 'a')
        else:
            tr = open("{}/{}.xml".format(run_path, run_id), 'a')
            tr.write(
                xml_testrun_init.format(project, login, login, run_plannedin,
                                        "true", dryrun, run_id,
                                        "featureverification"))
        if case_id is not None and result == "passed":
            tr.write(xml_testcase_passed.format(case_id))
        elif case_id is not None and result == "failed":
            tr.write(xml_testcase_failed.format(case_id))
        else:
            print(red("%s is None" % case_id))
        tr.close()
    for file_name in os.listdir(run_path):
        if file_name.endswith(".xml"):
            with open("{}/{}".format(run_path, file_name), 'a') as tr:
                tr.write(xml_testrun_end)
Exemplo n.º 47
0
from keras.layers import LSTM
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Dropout
import matplotlib.pyplot as plt

from prepare import prepare
import color

data, target = prepare('./data/XRP_usdt_xrp_1.csv',
                       './data/XRP_usdt_btc_1.csv',
                       './data/XRP_btc_xrp_1.csv')


data = np.array(data, dtype=float)
print(color.red(data.shape))

target = np.array(target, dtype=float)
print(color.red(target.shape))


# model = Sequential()
# model.add(LSTM(60, return_sequences=True, batch_input_shape=(None, len(data[0]), 6)))
# model.add(Dropout(0.35))
# model.add(LSTM(100, return_sequences=False))
# model.add(Dropout(0.35))
# model.add(Dense(1))
# # mean_squared_error, mean_squared_error
# model.compile(loss='mse', optimizer='rmsprop', metrics=['accuracy'])
# model.summary()
Exemplo n.º 48
0
def test_notty():
    """
    Run `nosetests -vs test/notty_test.py | less` to see red is not red
    """
    color.use_color_no_tty(False)
    print color.red('red')
Exemplo n.º 49
0
import color
print(color.blue('-=' * 20))
print(color.green('CALCULADORA DE HEXADECIMAL - OCTAL - BINÁRIO'))
print(color.blue('-=' * 20))

num = int(input('Digitite um número qualquer que seja inteiro: '))
print(color.blue('-=' * 20))
print(color.yellow('[1] HEXADECIMAL '))
print(color.red('[2] OCTAL'))
print(color.green('[3] BINÁRIO'))
print(color.blue('-=' * 20))
opcao = int(input('Escolha uma das opções: '))
print(color.blue('-=' * 20))
if opcao == 1:
    print(
        color.yellow(' O numero {} convertido para HEXADECIMAL É {}'.format(
            num,
            hex(num)[2:])))
elif opcao == 2:
    print(
        color.red('O numero {} convertido para OCTAL é {}'.format(
            num,
            oct(num)[2:])))
elif opcao == 3:
    print(
        color.green('O numero {} convertido para BINÁRIO é {}'.format(
            num,
            bin(num)[2:])))
else:
    print('\033[2;30;41mOPÇÃO INVALIDA\033[m')
print(color.blue('-=' * 20))
Exemplo n.º 50
0
def error(msg, indent=0):
    log(indentString(color.red('ERROR: ' + msg), indent))
Exemplo n.º 51
0
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)
Exemplo n.º 52
0
def test_decorations():
    for i in ['bold', 'italic', 'underline', 'strike', 'blink']:
        print '#' + i
        for j in color_names:
            c = getattr(color, j)(j)
            print getattr(color, i)(c) + color.red('compare')
Exemplo n.º 53
0
 def visual(self):
     if self.colornum == 0:
         color.gold()
     elif self.colornum == 1:
         color.red()
     glutSolidTeapot(1)
Exemplo n.º 54
0
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
Exemplo n.º 55
0
    'size': 0,
    'long': '0',
    'short': '0'
}

# Check for valid url
try:
    r = requests.get(url)
    print(color.magenta('STARTING SERVER BENCHMARKING'))
    print(color.magenta('URL:\t\t', url))
    print(color.magenta('Clients:\t', clients))
    print(color.magenta('Requests:\t', max_hits, '\n'))
    time.sleep(1)

except:
    print(color.red('Bad url, stopping'))
    sys.exit(1)

print(color.yellow('** Cattle of Geryon 2.0'))
print(color.yellow('** Preparing 1 concurrent users for battle.'))
print(color.yellow('The server is now under siege...'))

# Start benchmark
i = 0
while i < clients:
    hits = 0
    while hits < max_hits:
        r = requests.get(url)

        # Status of request
        status = r.status_code
Exemplo n.º 56
0
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
Exemplo n.º 57
0
def main(argv):
    logger = Logger(__file__)

    # initial parameters
    dryrun = False
    document_name = 'KernelNetworkQE/KN-Pylarion'
    case_title_prefix = 'KN-TC New-Test case Pylarion'
    run_xml_path = './testruns'

    try:
        opts, args = getopt(argv[1:], "hu:d:s:f:p:i:t:n", [
            "user="******"password="******"doc=", "sheet=", "file=", "project=",
            "plannedin=", "title=", "dryrun"
        ])
    except:
        usage()
        exit(-1)
    else:
        for opt, arg in opts:
            if opt == '-h':
                usage()
                exit(-1)
            elif opt in ("-u", "--user"):
                user = arg
            elif opt in ("--password", ):
                password = arg
            elif opt in ("-d", "--doc"):
                doc = arg
            elif opt in ("-s", "--sheet"):
                sheet = arg
                run_xml_path = './%s' % sheet
            elif opt in ("-f", "--file"):
                csv_file = arg
            elif opt in ("-p", "--project"):
                project = arg
            elif opt in ("-i", "--plannedin"):
                run_plannedin = arg
            elif opt in ("-t", "--title"):
                run_id_prefix = arg
            elif opt in ("-n", "--dryrun"):
                dryrun = True
        if "project" not in locals() or "run_plannedin" not in locals(
        ) or project == "" or run_plannedin == "":
            usage()
            exit(-1)
        if "password" not in locals():
            password = authentication()
            if password is None:
                print(
                    red("Configuration File of Pylarion Can\'t Be Found, Please Input Your Kerberos Password"
                        ))
                password = raw_input()
        if doc != '' and sheet != '':
            ws = WorkSheet(doc, sheet)
            cases = ws.cases
            if ws.check_cases() is False:
                logger.error('Missing Cols')
                exit(-1)
        elif csv_file != '':
            cases = []
            with open(csv_file, 'r') as fcsv:
                for row in csv.reader(fcsv):
                    cases.append(row)
        else:
            usage()
            exit(-1)

        logger.info('Start time: %s' % time.ctime())
        print(blue('Start time: %s' % time.ctime()))
        document = set_document(project, document_name)

        logger.info('filter_useless_cases')
        print(blue('filter_useless_cases'))
        cases = cases_filter(cases)

        logger.info('get_cases_ids')
        print(blue('get_cases_ids'))
        cases_ids = get_cases_ids(cases, case_title_prefix, document, project,
                                  dryrun)

        if dryrun:
            for index, (case, case_id) in enumerate(zip(cases, cases_ids)):
                print('the %s-th case: %s' % (index, case))
                print('the %s-th case_id: %s' % (index, case_id))
            logger.info('Ending time: %s' % time.ctime())
            print(blue('Ending time: %s' % time.ctime()))
            return None

        logger.info('get_cases_results_and_comments')
        print(blue('get_cases_results_and_comments'))
        cases_results = get_cases_results(cases)
        cases_comments = get_cases_comments(cases)

        logger.info('rm -rf %s' % run_xml_path)
        print(blue('rm -rf %s' % run_xml_path))
        clear_path(run_xml_path)

        logger.info('Updating %s' % run_xml_path)
        print(blue('Updating %s' % run_xml_path))
        runs_ids = gen_runs_ids_for_cases(cases, run_id_prefix)
        # post_runs(runs_ids, cases_ids, cases_results, cases_comments, run_xml_path, project, user, run_plannedin, dryrun)
        post_runs_filter_by_role(runs_ids, cases_ids, cases_results,
                                 cases_comments, run_xml_path, project, user,
                                 run_plannedin, dryrun)

        logger.info('Post %s' % run_xml_path)
        print(blue('Post %s' % run_xml_path))
        post(user, password, run_xml_path)

        logger.info('Ending time: %s' % time.ctime())
        print(blue('Ending time: %s' % time.ctime()))
Exemplo n.º 58
0
 def error(word):
     Log._print("[-] %s\n" % color.red(word))
Exemplo n.º 59
0
 def context(context):
     Log._print("%s" % (color.red(context)))
Exemplo n.º 60
0
def evaluate_solutions(results):
    ''' Evaluates the solutions returned by TS

    Parameters
    ----------
    results : list
        A list with the results of the TS. This list is a list of dicts under
        the following form:
        {
            'time': float, # The time wasted in the search
            'best': list # The best solution found in the search,
            'total_i': int, # The number of the final iteration 
            'i_best': int, # The iteration where the best solution was found
            'fault': list, # The list with the faulted lines
            'i_local': int, # The parameter of the max local search
            'itm': int, # The parameter of the max iteration to reset the TS
            'max_i': int, # The parameter of the max iteration set in the TS
        }
    
    Raises
    ------
    Exception
        In case the solution don't match any supported network model.
    '''

    for i, res in enumerate(results):
        print(color.blue('\nSEARCH #%d ------------' % i))
        validation = ev.validate(res['best'])
        if validation:
            if len(res['best']) == len(default_topologies['10-bus']):
                default = default_topologies['10-bus'].copy()
            elif len(res['best']) == len(default_topologies['16-bus']):
                default = default_topologies['16-bus'].copy()
            elif len(res['best']) == len(default_topologies['33-bus']):
                default = default_topologies['33-bus'].copy()
            elif len(res['best']) == len(default_topologies['119-bus']):
                default = default_topologies['119-bus'].copy()
            else:
                raise (Exception('No such model to this solution.'))

            faulted = default.copy()
            for f in res['fault']:
                faulted[f] = 0

            value = ev.value(res['best'])

            zeros = list()
            for j, element in enumerate(default):
                if element == 0:
                    zeros.append(j)

            ones = list()
            for j, element in enumerate(default):
                if element == 1:
                    ones.append(j)

            opened_switches = list()
            for j, element in enumerate(res['best']):
                if element == 0 and j not in zeros:
                    opened_switches.append(j)

            closed_switches = list()
            for j, element in enumerate(res['best']):
                if element == 1 and j not in ones:
                    closed_switches.append(j)

            print(color.green('VALIDATION: %s' % validation, 'b'))
            print('VALUE:', value)
            print('NAB:', len(ev.unsupplied_buses(faulted)))
            print(
                'NRB:', value -
                (ev.value(default) - len(ev.unsupplied_buses(faulted))))
            print('OPENED SW:', opened_switches)
            print('CLOSED SW:', closed_switches)
            print('TIME:', res['time'])
        else:
            print(color.red('VALIDATION: %s' % validation, 'b'))