Esempio n. 1
0
	def do_String(self, args):
		command = docopt(str(self.doc), args)
		e = ExecHelper()
		e.reset("String")
		#e.Log(args)
		if command["split"]:
			split = command['<input>'].split(command['<delimiter>'])
			result = ""
			for i in command['INDEX']:
				result += split[int(i)] + command['<outputdelimiter>']
		elif command["join"]: # should be command['use']
			result = ""
			for s in command['STRINGS']:
				result += s + command['<outputdelimiter>']
		elif command["replace"]:
			result = ""
			for s in command['STRINGS']:
				result += s.replace(command['<old>'], command['<new>']) + " "
		elif command["trim"]:
			result = str(command['<input>']).strip()
		elif command["clip"]:
			start = int(command['<start>'])
			end = int(command ['<end>'])
			if end == 0:
				end = - len(command['<input>'])
			result = str(command['<input>'] [start:] [:-end])		
		print result
		e.setExecCodes(command, result, "Pass")
Esempio n. 2
0
 def do_Sleep(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Sleep")
     e.Log("Sleep executing")
     time.sleep(int(command['<sec>']))
     e.setExecCodes(args, "Lion sleeps 20 h per day", "Pass")
Esempio n. 3
0
 def do_RegTest(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("RegTest")
     e.OutputEquals(
         "/usr/bin/regget " + command['<section>'] + " " +
         command['<value>'], command['<expectation>'])
Esempio n. 4
0
 def do_Skip(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Skip")
     e.Log("Skip command executing")
     outstring = ("Skip", command['<fromrank>'], command['<torank>'], "null")
     e.setExecCodes(args, outstring, "Skip")
 def do_GsettingsTest(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("GsettingsTest")
     e.OutputEquals("gsettings get " + command['<section>'] + " " + command['<value>'],
             command['<expectation>'])
     print e.r.retVal
Esempio n. 6
0
 def do_Dot1x(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Dot1x")
     e.EvalRetVal("regset --temp Network-eth0 Enable802 yes")
     e.EvalRetVal("regset Network-eth0 ca_cert " + command['<cacert>'])
     if (command["tls"] == True):
         e.Log("Configuring for tls")
         e.EvalRetVal("regset Network-eth0 Authentication TLS")
         e.EvalRetVal("regset Network-eth0 client_cert " + command['<clientcert>'])
         e.EvalRetVal("regset Network-eth0 private_key " + command['<privkey>'])
         e.EvalRetVal("regset Network-eth0 private_key_password " + command['<pkeypass>'])
         e.EvalRetVal("regset Network-eth0 Authmode " + command['<authmode>'])
     elif(command["peap"] == True):
         e.Log("Configuring for PEAP")
         e.EvalRetVal("regset Network-eth0 Authentication PEAP")
         e.EvalRetVal("regset Network-eth0 Authmode " + command['<authmode>'])
     elif(command["reset"] == True):
         e.Log("Doing dot1x reset")
         e.EvalRetVal("regdel Network-eth0 Authmode")
         e.EvalRetVal("regdel Network-eth0 Authentication")
         e.EvalRetVal("regdel Network-eth0 Enable802")
         e.EvalRetVal("regdel Network-eth0 ca_cert")
         e.EvalRetVal("regdel Network-eth0 client_cert")
         e.EvalRetVal("regdel Network-eth0 private_key")
         e.EvalRetVal("regdel Network-eth0 private_key_password")
Esempio n. 7
0
 def do_Echo(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Echo")
     cmd = "echo -n " + ' '.join(command['ARGS'])
     e.Log(cmd)
     e.RetOutput(cmd)
     print e.r.output
 def do_Depends(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Depends")
     depstring = (command['<ipaddr>'], command['<rank>'])
     e.Log("Waiting for 30 secs for %s to finish test case whose rank is %s" % (command['<ipaddr>'], command['<rank>']))
     print "Waiting for 30 secs for %s to finish test case whose rank is %s" % (command['<ipaddr>'], command['<rank>'])
     time.sleep(30)
     e.setExecCodes(args, depstring, "Wait")
Esempio n. 9
0
 def do_Mcast(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Mcast")
     if command['server']:
         cmd = "python /tmp/mcastfirmware/server.py %s" %(command['<filepath>'])
         e.Spawn(cmd)
     elif command['client']:
         cmd = "python /tmp/mcastfirmware/client.py"
         e.Execute(cmd)
     e.Log(e.r.getOutput())
Esempio n. 10
0
 def do_Browser(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Browser")
     if command["clearHistory"]:
         e.Log(
             "Browser clearHistory command is not implemented, marking Pass"
         )
         e.setExecCodes(args, "Not implemented", "Pass")
     elif command["kiosk"]:
         e.Log("Browser kiosk command is not implemented, marking Pass")
         e.setExecCodes("Browser kiosk", "Not implemented", "Pass")
Esempio n. 11
0
 def do_Network(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Network")
     if (command["on"] == True):
         e.EvalRetVal("service network start")
     elif(command["off"] == True):
         e.EvalRetVal("service network stop")
     elif(command["restart"] == True):
         e.EvalRetVal("service network stop")
         e.EvalRetVal("service network start")
     e.Log(e.r.getOutput())
 def do_SimulateDomain(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("SimulateDomain")
     if (command["Logon"] == True):
         print "regset --temp System Username " + command['<user>']
         print "regset --temp System Domain " + command['<domain>']
         print "regset --temp --encrypt System Password " + command[
             '<password>']
     elif (command["Logoff"] == True):
         print "regdel --temp System Username "
         print "regdel --temp System Domain "
         print "regdel --temp System Password "
Esempio n. 13
0
 def initialize(self, sudopassword):
     cmds = [
         "sudo -S iptables -F AF", "sudo iptables -F OUTPUT",
         "sudo iptables -X AF", "sudo -S iptables -N AF",
         "sudo -S iptables -A AF -p tcp --dport 80 -m string --string 'GET /' --algo bm -j ACCEPT",
         "sudo -S iptables -A AF -p tcp --dport 80 -m string --string 'POST /' --algo bm -j ACCEPT",
         "sudo -S iptables -A AF -p tcp --dport 80 -m string --string 'PUT /' --algo bm -j ACCEPT",
         "sudo -S iptables -A OUTPUT -o lo -j AF"
     ]
     e = ExecHelper()
     for c in cmds:
         cmd = "echo %s|%s" % (sudopassword, c)
         e.Execute(cmd)
Esempio n. 14
0
 def do_Math(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Math")
     e.Log(args)
     if command["add"]:
         result = int(command['<one>']) + int(command['<two>'])
     elif command["subtract"]:
         result = int(command['<two>']) - int(command['<one>'])
     elif command["multiply"]:
         result = int(command['<one>']) * int(command['<two>'])
     elif command["divide"]:
         result = int(command['<one>']) / int(command['<two>'])
     print result
     e.setExecCodes(command, result, "Pass")
Esempio n. 15
0
 def do_Network(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Network")
     if (command["on"] == True):
         e.EvalRetVal("service network start")
     elif (command["off"] == True):
         e.EvalRetVal("service network stop")
     elif (command["restart"] == True):
         e.EvalRetVal("service network stop")
         e.EvalRetVal("service network start")
     e.Log(e.r.getOutput())
Esempio n. 16
0
	def do_Xenapp(self, args):
		command = docopt(str(self.doc), args)
		e = ExecHelper()
		e.reset("Xenapp")
		if command["application"] or command["desktop"]:
			citrixuser = command['<username>']
			citrixpass = command['<password>']
			citrixurl = command['<url>']
			citrixapp = " ".join(command['APPNAME'])
			citrixappmod = citrixapp.replace(" ", "_0020")
				#driver = webdriver.Firefox()
			profpath = os.path.join(os.getenv('HOME'),".mozilla", "firefox", "wyse_default")
			if os.path.exists(profpath):
				e.Log("using existing profile")
				profile = FirefoxProfile(profpath)
			else:
				e.Log("using a temporary profile")
				profile = FirefoxProfile()
				driver = webdriver.Firefox(profile)
				driver.implicitly_wait(60)
				driver.get(citrixurl)
				#driver.find_element_by_id("skipWizardLink").click()
				driver.find_element_by_id("user").clear()
				driver.find_element_by_id("user").send_keys(citrixuser)
				driver.find_element_by_id("password").clear()
				driver.find_element_by_id("password").send_keys(citrixpass)
				driver.find_element_by_css_selector("span.rightDoor").click()
			if command["desktop"]:
				e.Log("finding ")
				driver.find_element_by_css_selector("#Desktops_Text > span").click()
			try:
				appid = "a[id*='%s']" % citrixappmod
				element =  driver.find_element_by_css_selector(appid)
				element.click()
				#e.setExecCodes(args, "Check app launch using Process alive wfica.orig","Pass")
			except Exception as e:
				print str(e)
				e.Log(str(e))
				print "Oops app not found!!", citrixapp
				e.setExecCodes(args, "Could not locate app","Fail")
			#The app takes its own sweet time coming up. Should sleep time be a parameter?
			print "Waiting for 90 secs before checking for window creation"
			time.sleep(90)
			chkcmd = "./agent/cli/bin/windowinfo.sh '%s'" % citrixapp
			e.RetOutput(chkcmd)
			e.Log(e.r.getOutput())
Esempio n. 17
0
 def do_Repeat(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Repeat")
     outstring = ('Repeat', command['<fromrank>'], command['<torank>'], command['<times>'])
     e.Log("Repeat command called")
     e.setExecCodes(args, outstring, "Repeat")
Esempio n. 18
0
 def do_Sleep(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Sleep")
     e.Log("Sleep executing")
     time.sleep(int(command['<sec>']))
     e.setExecCodes(args, "Lion sleeps 20 h per day", "Pass")
Esempio n. 19
0
 def do_Skip(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Skip")
     e.Log("Skip command executing")
     outstring = ("Skip", command['<fromrank>'], command['<torank>'],
                  "null")
     e.setExecCodes(args, outstring, "Skip")
 def SandboxExec(self, c):
     e = ExecHelper()
     cliThread = multiprocessing.Process(target=cliInterface.CliExecCommandMultiprocess,
                 args=(c,self.cliQueue))
     cliThread.start()
     i = 0
     while i < self.timeout:
         i += 1
         sleep(1)
         if not cliThread.is_alive():
             break
     if cliThread.is_alive():
         self.tee("Terminating on timeout")
         e.setExecCodes(c, "Operation timed out", "Fail")
         cliThread.terminate()
     else:
         q = json.loads(self.cliQueue.get_nowait())
         e.setExecCodes(c, q['output'], q['retVal'])
         e.r.resetLog(q['log'])
Esempio n. 21
0
 def do_Browser(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Browser")
     if command["clearHistory"]:
         e.Log("Browser clearHistory command is not implemented, marking Pass")
         e.setExecCodes(args, "Not implemented", "Pass")
     elif command["kiosk"]:
         e.Log("Browser kiosk command is not implemented, marking Pass")
         e.setExecCodes("Browser kiosk","Not implemented","Pass")
Esempio n. 22
0
 def do_String(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("String")
     #e.Log(args)
     if command["split"]:
         split = command['<input>'].split(command['<delimiter>'])
         result = ""
         for i in command['INDEX']:
             result += split[int(i)] + command['<outputdelimiter>']
     elif command["join"]:  # should be command['use']
         result = ""
         for s in command['STRINGS']:
             result += s + command['<outputdelimiter>']
     elif command["replace"]:
         result = ""
         for s in command['STRINGS']:
             result += s.replace(command['<old>'], command['<new>']) + " "
     elif command["trim"]:
         result = str(command['<input>']).strip()
     elif command["clip"]:
         start = int(command['<start>'])
         end = int(command['<end>'])
         if end == 0:
             end = -len(command['<input>'])
         result = str(command['<input>'][start:][:-end])
     print result
     e.setExecCodes(command, result, "Pass")
Esempio n. 23
0
    def do_Gdm(self, args):
        command = docopt(str(self.doc), args)
        e = ExecHelper()
        e.reset("Gdm")
        cmd = "pidof X"
        pid = e.RetOutput(cmd).strip()
        cmd = "sh -c 'xargs -0 < /proc/" + pid + "/cmdline'"
        e.Log(cmd)
        xcmdline = e.RetOutput(cmd).split()
        count = len(xcmdline)
        i = 0
        while i < count:
            if xcmdline[i] == "-auth":
                xauthority = xcmdline[i + 1]
            i += 1
        os.environ['XAUTHORITY'] = xauthority
	if command['login']:
        	for word in command['PHRASE']:
            		word = word.strip()
            		if word == "{Tab}":
                		cmd = 'echo %s|sudo -S xdotool key Tab' %(command['<sudopassword>'])
            		elif word == "{Return}":
                		cmd = 'echo %s|sudo -S xdotool key Return' %(command['<sudopassword>'])
            		elif word == "{Clear}":
                		cmd = 'echo %s|sudo -S xdotool key ctrl+a Delete' %(command['<sudopassword>'])
            		elif word == "{Space}":
                		cmd = 'echo %s|sudo -S xdotool key space' %(command['<sudopassword>'])
            		else:
                		cmd = 'echo %s|sudo -S xdotool type %s' %(command['<sudopassword>'], word)
            		e.Log(cmd)
            		e.Execute(cmd)
            		time.sleep(2)
            		e.Log(e.r.output)
	else:
		cmd = "xdotool key ctrl+alt+Delete"
		e.Execute(cmd)
		time.sleep(2)
		e.Execute("sleep 30 && xdotool key Return &")
	        e.setExecCodes("Reboot","Going out in 1/2 minute", "Reboot")
		e.Log(e.r.output)
Esempio n. 24
0
 def do_Echo(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Echo")
     cmd = "echo -n " + ' '.join(command['ARGS'])
     e.Log(cmd)
     e.RetOutput(cmd)
     print e.r.output
Esempio n. 25
0
 def do_Mcast(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Mcast")
     if command['server']:
         cmd = "python /tmp/mcastfirmware/server.py %s" % (
             command['<filepath>'])
         e.Spawn(cmd)
     elif command['client']:
         cmd = "python /tmp/mcastfirmware/client.py"
         e.Execute(cmd)
     e.Log(e.r.getOutput())
Esempio n. 26
0
 def do_Depends(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Depends")
     depstring = (command['<ipaddr>'], command['<rank>'])
     e.Log(
         "Waiting for 30 secs for %s to finish test case whose rank is %s" %
         (command['<ipaddr>'], command['<rank>']))
     print "Waiting for 30 secs for %s to finish test case whose rank is %s" % (
         command['<ipaddr>'], command['<rank>'])
     time.sleep(30)
     e.setExecCodes(args, depstring, "Wait")
Esempio n. 27
0
 def do_Reboot(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Reboot")
     e.setExecCodes("Reboot","Unknown error", "Fail")
     prepare = 'echo %s|sudo -S shutdown -k +1' %(command['<sudopassword>'])
     e.Log("Checking our permissions")
     e.Log(prepare)
     if e.Execute(prepare) == 0:
         cmd = 'shutdown -r +1 &'
         e.Log(cmd)
         e.Log("Alert: This will wipe out all the variables created before.")
         p = e.Execute('echo %s|sudo -S %s' % (command['<sudopassword>'], cmd))
         e.setExecCodes("Reboot","Going down in 1 minute", "Reboot")
Esempio n. 28
0
 def do_Math(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Math")
     e.Log(args)
     if command["add"]:
         result = int(command['<one>']) + int(command['<two>'])
     elif command["subtract"]:
         result = int(command['<two>']) - int(command['<one>'])
     elif command["multiply"]:
         result = int(command['<one>']) * int(command['<two>'])
     elif command["divide"]:
         result = int(command['<one>']) / int(command['<two>'])
     print result
     e.setExecCodes(command, result, "Pass")
Esempio n. 29
0
	def do_Http(self, args):
		command = docopt(str(self.doc), args)
		e = ExecHelper()
		e.reset("Http")
		try:
			if command["download"]:
				e.Log("Http downloading")
				urllib.urlretrieve (command["<url>"], command["<localfile>"])
				e.setExecCodes("Http", "File downloaded", "Pass")
			else:
				e.Log("Http uploading")
				toUpload = UploadFile(command["<localfile>"], 'r')
				theHeaders= {'Content-Type': 'text/xml'}
				theRequest = urllib2.Request(command["<url>"], toUpload, theHeaders)
				response = urllib2.urlopen(theRequest)
				toUpload.close()
			e.Log("Http command passed")
		except Exception as e:
			print str(e)
			e.Log("Http failed " + str(e))
			e.setExecCodes("", str(e), "Fail")
 def do_HTTPCounter(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("HTTPCounter")
     sudopassword = command['<sudopassword>']
     if command["initialize"]:
         e.Log("HTTPCounter initalizing")
         self.initialize(sudopassword)
         e.setExecCodes(args, "Warning: Does not verify execution", "Pass")
     elif command["resetCounter"]:
         cmd = "echo %s|sudo -S iptables -Z AF" % (sudopassword)
         e.Log("HTTPCounter resetCounter")
         e.Execute(cmd)
         e.setExecCodes(args,"Warning: Does not verify execution","Pass")
     elif command["getCount"]:
         cmd = "sh -c 'echo %s|sudo -S iptables -vL AF'" % (sudopassword)
         lines = e.RetOutput(cmd).split(os.linesep)
         output =  " GET  " + lines[2].split()[0]
         output += " POST " +  lines[3].split()[0]
         output += " PUT " + lines[4].split()[0]
         e.r.setOutput(output)
         print output
 def SandboxExec(self, c):
     e = ExecHelper()
     cliThread = multiprocessing.Process(
         target=cliInterface.CliExecCommandMultiprocess,
         args=(c, self.cliQueue))
     cliThread.start()
     i = 0
     while i < self.timeout:
         i += 1
         sleep(1)
         if not cliThread.is_alive():
             break
     if cliThread.is_alive():
         self.tee("Terminating on timeout")
         e.setExecCodes(c, "Operation timed out", "Fail")
         cliThread.terminate()
     else:
         q = json.loads(self.cliQueue.get_nowait())
         e.setExecCodes(c, q['output'], q['retVal'])
         e.r.resetLog(q['log'])
Esempio n. 32
0
 def do_Dot1x(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Dot1x")
     e.EvalRetVal("regset --temp Network-eth0 Enable802 yes")
     e.EvalRetVal("regset Network-eth0 ca_cert " + command['<cacert>'])
     if (command["tls"] == True):
         e.Log("Configuring for tls")
         e.EvalRetVal("regset Network-eth0 Authentication TLS")
         e.EvalRetVal("regset Network-eth0 client_cert " +
                      command['<clientcert>'])
         e.EvalRetVal("regset Network-eth0 private_key " +
                      command['<privkey>'])
         e.EvalRetVal("regset Network-eth0 private_key_password " +
                      command['<pkeypass>'])
         e.EvalRetVal("regset Network-eth0 Authmode " +
                      command['<authmode>'])
     elif (command["peap"] == True):
         e.Log("Configuring for PEAP")
         e.EvalRetVal("regset Network-eth0 Authentication PEAP")
         e.EvalRetVal("regset Network-eth0 Authmode " +
                      command['<authmode>'])
     elif (command["reset"] == True):
         e.Log("Doing dot1x reset")
         e.EvalRetVal("regdel Network-eth0 Authmode")
         e.EvalRetVal("regdel Network-eth0 Authentication")
         e.EvalRetVal("regdel Network-eth0 Enable802")
         e.EvalRetVal("regdel Network-eth0 ca_cert")
         e.EvalRetVal("regdel Network-eth0 client_cert")
         e.EvalRetVal("regdel Network-eth0 private_key")
         e.EvalRetVal("regdel Network-eth0 private_key_password")
Esempio n. 33
0
 def do_Process(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Process")
     if command["monitor"]:
         psopts = "/bin/ps -C %s o pcpu,pmem --cumulative --no-heading" %(command["<name>"])
         e.Log("Executing monitor " + psopts)
         counter = 0
         cpu = float(0)
         mem = float(0)
         while (counter < int(command["<duration>"])):
             pcpu,pmem = self.parse(e.RetOutput(psopts))
             cpu = cpu + pcpu
             mem = mem + pmem
             time.sleep(1)
             counter = counter + 1
         output = "%s consumed %s%% cpu and %s %% memory" % (command["<name>"],cpu/counter,mem/counter)
         e.Log(output)
         print output
         if cpu > 0 or mem > 0:
             e.setExecCodes("Process monitor",output,"Pass")
         else:
             e.setExecCodes("Process monitor",output,"Fail")
     elif command["kill"]:
         killopts = "/usr/bin/killall %s" %(command["<name>"])
         e.Log(killopts)
         e.EvalRetVal(killopts)
     elif command["spawn"]:
         spawnopts = ' '.join(command["PATH"])
         e.Log(spawnopts)
         e.Spawn(spawnopts)
     elif command["exec"]:
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " %(execopts)
         e.EvalRetVal(execopts)
     elif command["forfeit"]:
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " %(execopts)
         e.EvalRetVal(execopts)
         e.r.setRetVal("Fail")
     elif command["thrive"]:
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " %(execopts)
         e.EvalRetVal(execopts)
         e.r.setRetVal("Pass")
     elif command["alive"]:
         killopts = "/usr/bin/killall -s 0 %s" %(command["<name>"])
         e.Log(killopts)
         e.EvalRetVal(killopts)
     elif command["dead"]:
         killopts = "pidof %s" %(command["<name>"])
         e.Log(killopts)
         e.EvalRetVal(killopts, 1)
     elif command["pid"]:
         execopts = "pidof %s" %(command["<name>"])
         e.Log(execopts)
         e.EvalRetVal(execopts)
     elif command["output"]:
         #  Process output contains 1360x78  xdpyinfo  | grep dimensions
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " %(execopts)
         output = e.RetOutput(execopts)
         if command['<expectation>'] in output:
             e.setExecCodes(execopts, output, "Pass")
         else:
             e.setExecCodes(execopts, output, "Fail")
     e.Log(e.r.getOutput())
     print e.r.getRetVal()
Esempio n. 34
0
    def do_Ftp(self, args):
        command = docopt(str(self.doc), args)
        e = ExecHelper()
        e.reset("Ftp")
        try:
            ftpconn = ftplib.FTP(command['<server-ip>'])
            ftpconn.login(command['<user>'],  command['<password>'])
            ftpconn.cwd(os.path.dirname(command['<remotefile>']))

            if command['upload']:
                localfile = open(command['<localfile>'], 'r')
                ftpconn.storlines('STOR ' + command['<remotefile>'], localfile)
                localfile.close()
                ftpconn.quit()
                e.setExecCodes("", "File uploaded", "Pass")
            elif command['download']:
                ftpconn.retrbinary("RETR " + os.path.basename(command['<remotefile>']),
                            open(command['<localfile>'], 'wb').write)
                e.setExecCodes("", "File downloaded", "Pass")
            e.Log("Ftp command passed")
        except Exception as e:
            print str(e)
            e.Log("Ftp failed " + str(e))
            e.setExecCodes("", str(e), "Fail")
 def ExecServerCommand(self):
     if self.command == "QuitAgent":
         if os.path.exists(self.logFile):
             self.sendFile(self.logFile, "/fileupload/runlog.txt")
         self.tee("Server asked us to quit")
         return None
     elif self.command == "Associated":
         self.tee("Server acknowleged us")
         return False
     elif self.command == "OK":
         self.tee("Result posted")
         return False
     elif self.command == "WAITON":
         return False
     elif self.command == "UPLOADED":
         self.tee("file uploaded")
         return False
     else:
         self.currentTest = json.loads(self.command)
         e = ExecHelper()
         e.resetTestcase(self.currentTest['desc'])
         e.r.resetLog()
         e.Log("Starting " + self.currentTest['name'])
         qstore = ResultStore.getResultStore()
         for c in self.currentTest['commands']:
             try:
                 self.tee("Executing: " + c)
                 varstring = False
                 if c.startswith('Capability add'):
                     c = c.strip()
                     upgradeurl = c.split(' ')[2]
                     plugins = c.split(' ')[3:]
                     retVal = self.installPlugins(upgradeurl, plugins, e)
                 elif c.startswith('Capability remove'):
                     retVal = self.uninstallPlugins(e)
                 elif c.startswith('Timeout set'):
                     self.tee("setting timeout with command " + c)
                     self.timeout = int(c.split(' ')[2])
                 else:
                     #handle all ${}substitution here
                     if c.startswith('${'):
                         varstring = True
                         split = c.split("=", 1)
                         if len(split) == 2:
                             varname = c.split("=", 1)[0]
                             c = c.split("=", 1)[1]
                         else:
                             self.tee("command '" + c + "' syntax error")
                             break
                     c = self.clientInfo.preProcessCli(c)
                     #Write it to history file
                     self.hist.write(c + "\n")
                     #Execute in sandbox so that agent doesnt get killed on plugin exception
                     self.SandboxExec(c)
                     retVal = qstore.getRetVal()
                     if varstring:
                         varvalue = qstore.getOutput().strip()
                         if len(varvalue) == 0:
                             varvalue = "null"
                         self.clientInfo.addInfo(varname, varvalue)
                 # Break on first failure in a testcase
                 # continue on to the next testcase
                 if retVal == "Fail" or retVal == "Wait":
                     # This should be logged
                     self.tee("command '" + c + "' caused abort")
                     break
             except Exception as ex:
                 e.setExecCodes(c, str(ex), "Fail")
                 self.tee(str(ex))
                 self.tee("command '" + c +
                          "' caused abort. Probably syntax error.")
                 break
         return True
Esempio n. 36
0
 def do_Process(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Process")
     if command["monitor"]:
         psopts = "/bin/ps -C %s o pcpu,pmem --cumulative --no-heading" % (
             command["<name>"])
         e.Log("Executing monitor " + psopts)
         counter = 0
         cpu = float(0)
         mem = float(0)
         while (counter < int(command["<duration>"])):
             pcpu, pmem = self.parse(e.RetOutput(psopts))
             cpu = cpu + pcpu
             mem = mem + pmem
             time.sleep(1)
             counter = counter + 1
         output = "%s consumed %s%% cpu and %s %% memory" % (
             command["<name>"], cpu / counter, mem / counter)
         e.Log(output)
         print output
         if cpu > 0 or mem > 0:
             e.setExecCodes("Process monitor", output, "Pass")
         else:
             e.setExecCodes("Process monitor", output, "Fail")
     elif command["kill"]:
         killopts = "/usr/bin/killall %s" % (command["<name>"])
         e.Log(killopts)
         e.EvalRetVal(killopts)
     elif command["spawn"]:
         spawnopts = ' '.join(command["PATH"])
         e.Log(spawnopts)
         e.Spawn(spawnopts)
     elif command["exec"]:
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " % (execopts)
         e.EvalRetVal(execopts)
     elif command["forfeit"]:
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " % (execopts)
         e.EvalRetVal(execopts)
         e.r.setRetVal("Fail")
     elif command["thrive"]:
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " % (execopts)
         e.EvalRetVal(execopts)
         e.r.setRetVal("Pass")
     elif command["alive"]:
         killopts = "/usr/bin/killall -s 0 %s" % (command["<name>"])
         e.Log(killopts)
         e.EvalRetVal(killopts)
     elif command["dead"]:
         killopts = "pidof %s" % (command["<name>"])
         e.Log(killopts)
         e.EvalRetVal(killopts, 1)
     elif command["pid"]:
         execopts = "pidof %s" % (command["<name>"])
         e.Log(execopts)
         e.EvalRetVal(execopts)
     elif command["output"]:
         #  Process output contains 1360x78  xdpyinfo  | grep dimensions
         execopts = ' '.join(command["PATH"])
         e.Log(execopts)
         execopts = "/bin/sh -c '%s' " % (execopts)
         output = e.RetOutput(execopts)
         if command['<expectation>'] in output:
             e.setExecCodes(execopts, output, "Pass")
         else:
             e.setExecCodes(execopts, output, "Fail")
     e.Log(e.r.getOutput())
     print e.r.getRetVal()
 def tee(self, line):
     logger = logging.getLogger("AutomationAgent")
     e = ExecHelper()
     e.Log(line)
     logging.info(line)
     print line
Esempio n. 38
0
 def do_RegTest(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("RegTest")
     e.OutputEquals("/usr/bin/regget " + command['<section>'] + " " + command['<value>'],
             command['<expectation>'])
Esempio n. 39
0
 def do_Selenium(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Selenium")
     if command["start"]:
         e.Spawn("python ./agent/cli/bin/SeleniumWorker.py %s" % (command['<which>']) )
         time.sleep(5)
         retval, output = self.ReadWorkerResult()
     elif command["stop"]:
         self.SendWorkerCommand("stop")
         retval, output = self.ReadWorkerResult()
     elif command["clickcss"]:
         self.SendWorkerCommand("clickcss " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clickname"]:
         self.SendWorkerCommand("clickname " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clickid"]:
         self.SendWorkerCommand("clickid " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clickxpath"]:
         self.SendWorkerCommand("clickxpath " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clickmenuitem"]:
         self.SendWorkerCommand("clickmenuitem " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clearcss"]:
         self.SendWorkerCommand("clearcss " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clearname"]:
         self.SendWorkerCommand("clearname " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clearid"]:
         self.SendWorkerCommand("clearid " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["clearxpath"]:
         self.SendWorkerCommand("clearxpath " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["open"]:
         self.SendWorkerCommand("open " + command['<which>'] + "")
         retval, output = self.ReadWorkerResult()
     elif command["fillcss"]:
         self.SendWorkerCommand("fillcss " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["fillname"]:
         self.SendWorkerCommand("fillname " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["fillid"]:
         self.SendWorkerCommand("fillid " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["fillxpath"]:
         self.SendWorkerCommand("fillxpath " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["counttags"]:
         self.SendWorkerCommand("counttags " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["namecontains"]:
         self.SendWorkerCommand("namecontains " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["idcontains"]:
         self.SendWorkerCommand("idcontains " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["csscontains"]:
         self.SendWorkerCommand("csscontains " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["xpathcontains"]:
         self.SendWorkerCommand("xpathcontains " + command['<which>'] + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     elif command["pagecontains"]:
         self.SendWorkerCommand("pagecontains " + "null" + " " + ' '.join(command['WHAT']) + "")
         retval, output = self.ReadWorkerResult()
     else:
         retval, output = "Fail", "Invalid command"
     
     e.Log(output)
     e.setExecCodes(args, output, retval)
Esempio n. 40
0
 def do_Gdm(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Gdm")
     cmd = "pidof X"
     pid = e.RetOutput(cmd).strip()
     cmd = "sh -c 'xargs -0 < /proc/" + pid + "/cmdline'"
     e.Log(cmd)
     xcmdline = e.RetOutput(cmd).split()
     count = len(xcmdline)
     i = 0
     while i < count:
         if xcmdline[i] == "-auth":
             xauthority = xcmdline[i + 1]
         i += 1
     os.environ['XAUTHORITY'] = xauthority
     if command['login']:
         for word in command['PHRASE']:
             word = word.strip()
             if word == "{Tab}":
                 cmd = 'echo %s|sudo -S xdotool key Tab' % (
                     command['<sudopassword>'])
             elif word == "{Return}":
                 cmd = 'echo %s|sudo -S xdotool key Return' % (
                     command['<sudopassword>'])
             elif word == "{Clear}":
                 cmd = 'echo %s|sudo -S xdotool key ctrl+a Delete' % (
                     command['<sudopassword>'])
             elif word == "{Space}":
                 cmd = 'echo %s|sudo -S xdotool key space' % (
                     command['<sudopassword>'])
             else:
                 cmd = 'echo %s|sudo -S xdotool type %s' % (
                     command['<sudopassword>'], word)
             e.Log(cmd)
             e.Execute(cmd)
             time.sleep(2)
             e.Log(e.r.output)
     else:
         cmd = "xdotool key ctrl+alt+Delete"
         e.Execute(cmd)
         time.sleep(2)
         e.Execute("sleep 30 && xdotool key Return &")
         e.setExecCodes("Reboot", "Going out in 1/2 minute", "Reboot")
         e.Log(e.r.output)
Esempio n. 41
0
 def do_Http(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Http")
     try:
         if command["download"]:
             e.Log("Http downloading")
             urllib.urlretrieve(command["<url>"], command["<localfile>"])
             e.setExecCodes("Http", "File downloaded", "Pass")
         else:
             e.Log("Http uploading")
             toUpload = UploadFile(command["<localfile>"], 'r')
             theHeaders = {'Content-Type': 'text/xml'}
             theRequest = urllib2.Request(command["<url>"], toUpload,
                                          theHeaders)
             response = urllib2.urlopen(theRequest)
             toUpload.close()
         e.Log("Http command passed")
     except Exception as e:
         print str(e)
         e.Log("Http failed " + str(e))
         e.setExecCodes("", str(e), "Fail")
Esempio n. 42
0
 def do_Desktop(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Desktop")
     if command["logout"]:
         e.EvalRetVal("/usr/bin/gnome-session-quit --no-prompt")
     elif command["resolution"]:
         cmd = "xrandr -d :0 --output LVDS --mode " + command["<resolution>"]
         e.Log("Desktop Resolution: " + cmd)
         e.EvalRetVal(cmd)
     elif command["screenshot"]:
         scrot = MSSLinux()
         for filename in scrot.save(output="scrot.png", screen=-1):
             shutil.move("scrot.png", command['<filename>'])
             e.Log('File: "{}" created.'.format(filename))
     elif command["legacyScreenshot"]:
         os.system("gnome-screenshot -b -f " + command['<filename>'])
     elif command["windowimg"]:
         e.Log("Executing commands for windowimg")
         cmd = 'xte "mousemove 0 0"'
         e.Log(cmd)
         e.Execute(cmd)
         cmd = "./agent/cli/bin/windowimg.sh %s %s" % (
             command['<filename>'], command['<windowid>'])
         e.Log(cmd)
         e.EvalRetVal(cmd)
     elif command["windowid"]:
         e.Log("Executing commands for windowid")
         cmd = "./agent/cli/bin/windowid.sh %s" % (command['<process>'])
         e.Log(cmd)
         e.EvalRetVal(cmd)
     elif command["windowfocus"]:
         e.Log("Executing commands for windowfocus")
         cmd = 'xdotool windowactivate %s' % (command['<windowid>'])
         e.Log(cmd)
         e.EvalRetVal(cmd)
     elif command["windowclose"]:
         cmd = 'wmctrl -i -c %s' % (command['<windowid>'])
         e.Log("Executing windowclose: " + cmd)
         e.EvalRetVal(cmd)
     elif command["keydown"]:
         cmd = "xte keydown %s" % (command['<key>'])
         e.Log(cmd)
         e.EvalRetVal(cmd)
     elif command["keyup"]:
         cmd = "xte keyup %s" % (command['<key>'])
         e.Log(cmd)
         e.EvalRetVal(cmd)
     elif command["keypress"]:
         cmd = 'xte "sleep 1" "key %s"' % (command['<key>'])
         e.Log(cmd)
         e.EvalRetVal(cmd)
     elif command["type"]:
         e.Log("Desktop Typing keys")
         special = ["Alt", "Control", "Shift", "Super"]
         press = []
         release = []
         l = 0
         for k in command['KEYS']:
             if k in special:
                 press.append('"keydown ' + k + '_R"')
                 release.append('"keyup ' + k + '_R"')
             elif len(release) > 0:
                 press.append('"key ' + k + '"')
                 release.reverse()
                 press.extend(release)
                 release = []
             else:
                 for char in k:
                     press.append('"usleep 30000" "str ' + char + '"')
                 #press.append('"str ' + k + '"')
             cmd = "xte " + ' '.join(press)
         e.EvalRetVal(cmd)
     elif command["mouseclick"]:
         e.Log("Desktop mouseclick")
         cmd = "./agent/cli/bin/mouseclick.sh %s %s %s" % (
             command['<windowid>'], command['<windowimg>'], ' '.join(
                 command['PATTERN']))
         e.Log(cmd)
         e.EvalRetVal(cmd)
         #move the mouse out before it pollutes next screenshot
         e.Execute('xte "sleep 1" "mousemove 0 0"')
Esempio n. 43
0
 def do_Ping(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Ping")
     e.EvalRetVal("ping -c 1 " + command['<host>'])
     e.Log(e.r.getOutput())
Esempio n. 44
0
 def do_Xenapp(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Xenapp")
     if command["application"] or command["desktop"]:
         citrixuser = command['<username>']
         citrixpass = command['<password>']
         citrixurl = command['<url>']
         citrixapp = " ".join(command['APPNAME'])
         citrixappmod = citrixapp.replace(" ", "_0020")
         #driver = webdriver.Firefox()
         profpath = os.path.join(os.getenv('HOME'), ".mozilla", "firefox",
                                 "wyse_default")
         if os.path.exists(profpath):
             e.Log("using existing profile")
             profile = FirefoxProfile(profpath)
         else:
             e.Log("using a temporary profile")
             profile = FirefoxProfile()
             driver = webdriver.Firefox(profile)
             driver.implicitly_wait(60)
             driver.get(citrixurl)
             #driver.find_element_by_id("skipWizardLink").click()
             driver.find_element_by_id("user").clear()
             driver.find_element_by_id("user").send_keys(citrixuser)
             driver.find_element_by_id("password").clear()
             driver.find_element_by_id("password").send_keys(citrixpass)
             driver.find_element_by_css_selector("span.rightDoor").click()
         if command["desktop"]:
             e.Log("finding ")
             driver.find_element_by_css_selector(
                 "#Desktops_Text > span").click()
         try:
             appid = "a[id*='%s']" % citrixappmod
             element = driver.find_element_by_css_selector(appid)
             element.click()
             #e.setExecCodes(args, "Check app launch using Process alive wfica.orig","Pass")
         except Exception as e:
             print str(e)
             e.Log(str(e))
             print "Oops app not found!!", citrixapp
             e.setExecCodes(args, "Could not locate app", "Fail")
         #The app takes its own sweet time coming up. Should sleep time be a parameter?
         print "Waiting for 90 secs before checking for window creation"
         time.sleep(90)
         chkcmd = "./agent/cli/bin/windowinfo.sh '%s'" % citrixapp
         e.RetOutput(chkcmd)
         e.Log(e.r.getOutput())
Esempio n. 45
0
    def do_Selenium(self, args):
        command = docopt(str(self.doc), args)
        e = ExecHelper()
        e.reset("Selenium")
        if command["start"]:
            e.Spawn("python ./agent/cli/bin/SeleniumWorker.py %s" %
                    (command['<which>']))
            time.sleep(5)
            retval, output = self.ReadWorkerResult()
        elif command["stop"]:
            self.SendWorkerCommand("stop")
            retval, output = self.ReadWorkerResult()
        elif command["clickcss"]:
            self.SendWorkerCommand("clickcss " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clickname"]:
            self.SendWorkerCommand("clickname " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clickid"]:
            self.SendWorkerCommand("clickid " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clickxpath"]:
            self.SendWorkerCommand("clickxpath " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clickmenuitem"]:
            self.SendWorkerCommand("clickmenuitem " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clearcss"]:
            self.SendWorkerCommand("clearcss " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clearname"]:
            self.SendWorkerCommand("clearname " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clearid"]:
            self.SendWorkerCommand("clearid " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["clearxpath"]:
            self.SendWorkerCommand("clearxpath " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["open"]:
            self.SendWorkerCommand("open " + command['<which>'] + "")
            retval, output = self.ReadWorkerResult()
        elif command["fillcss"]:
            self.SendWorkerCommand("fillcss " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["fillname"]:
            self.SendWorkerCommand("fillname " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["fillid"]:
            self.SendWorkerCommand("fillid " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["fillxpath"]:
            self.SendWorkerCommand("fillxpath " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["counttags"]:
            self.SendWorkerCommand("counttags " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["namecontains"]:
            self.SendWorkerCommand("namecontains " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["idcontains"]:
            self.SendWorkerCommand("idcontains " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["csscontains"]:
            self.SendWorkerCommand("csscontains " + command['<which>'] + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["xpathcontains"]:
            self.SendWorkerCommand("xpathcontains " + command['<which>'] +
                                   " " + ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        elif command["pagecontains"]:
            self.SendWorkerCommand("pagecontains " + "null" + " " +
                                   ' '.join(command['WHAT']) + "")
            retval, output = self.ReadWorkerResult()
        else:
            retval, output = "Fail", "Invalid command"

        e.Log(output)
        e.setExecCodes(args, output, retval)
Esempio n. 46
0
 def process_default(self, event):
     e = ExecHelper()
     e.setExecCodes("File wait", event.pathname, "Pass")
     raise KeyboardInterrupt
Esempio n. 47
0
    def do_IP(self, args):
        command = docopt(str(self.doc), args)
        e = ExecHelper()
        e.reset("IP")
        interface = command["<interface>"]

        myIp = self.myIP(interface)
        e.Log("Found client ip: " + myIp)
        if command["equals"]:
            if command["<address>"] == myIp:
                e.Log("ip addresss equal")
                e.setExecCodes("", "ip addresses equal", "Pass")
                retVal = "Pass"
            else:
                e.Log("IP address not equal")
                e.setExecCodes("", "ip addresses inequal", "Fail")
                retVal = "Fail"
        elif command["contains"]:
            if myIp.startswith(command["<address>"]):
                e.Log("ip addresses contains")
                e.setExecCodes("", "ip addresses contains", "Pass")
                retVal = "Pass"
            else:
                e.Log("ip addresses does not contain")
                e.setExecCodes("", "ip addresses does not contain", "Fail")
                retVal = "Fail"
        print retVal
 def ExecServerCommand(self):
     if self.command == "QuitAgent":
         if os.path.exists(self.logFile):
             self.sendFile(self.logFile, "/fileupload/runlog.txt")
         self.tee("Server asked us to quit")
         return None
     elif self.command == "Associated":
         self.tee("Server acknowleged us")
         return False
     elif self.command == "OK" :
         self.tee("Result posted")
         return False
     elif self.command == "WAITON" :
         return False
     elif self.command == "UPLOADED" :
         self.tee("file uploaded")
         return False
     else:
         self.currentTest = json.loads(self.command)
         e = ExecHelper()
         e.resetTestcase(self.currentTest['desc'])
         e.r.resetLog()
         e.Log("Starting " + self.currentTest['name'])
         qstore = ResultStore.getResultStore()
         for c in self.currentTest['commands']:
             try:
                 self.tee ("Executing: " + c)
                 varstring = False
                 if c.startswith('Capability add'):
                     c = c.strip()
                     upgradeurl = c.split(' ')[2]
                     plugins = c.split(' ')[3:]
                     retVal = self.installPlugins(upgradeurl, plugins, e)
                 elif c.startswith('Capability remove'):
                     retVal = self.uninstallPlugins(e)
                 elif c.startswith('Timeout set'):
                     self.tee("setting timeout with command " + c);
                     self.timeout = int(c.split(' ')[2])
                 else:
                     #handle all ${}substitution here
                     if c.startswith('${'):
                         varstring = True
                         split = c.split("=",1)
                         if len(split) == 2:
                             varname = c.split("=",1)[0]
                             c = c.split("=",1)[1]
                         else:
                             self.tee("command '" + c +"' syntax error")
                             break
                     c = self.clientInfo.preProcessCli(c)
                     #Write it to history file
                     self.hist.write(c + "\n")
                     #Execute in sandbox so that agent doesnt get killed on plugin exception
                     self.SandboxExec(c)
                     retVal = qstore.getRetVal()
                     if varstring:
                         varvalue = qstore.getOutput().strip()
                         if len(varvalue) == 0:
                             varvalue="null"
                         self.clientInfo.addInfo(varname, varvalue)
                 # Break on first failure in a testcase
                 # continue on to the next testcase
                 if retVal == "Fail" or retVal == "Wait":
                     # This should be logged
                     self.tee("command '" + c +"' caused abort")
                     break
             except Exception as ex:
                 e.setExecCodes(c, str(ex), "Fail")
                 self.tee(str(ex))
                 self.tee("command '" + c +"' caused abort. Probably syntax error.")
                 break
         return True
Esempio n. 49
0
 def do_Reboot(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("Reboot")
     e.setExecCodes("Reboot", "Unknown error", "Fail")
     prepare = 'echo %s|sudo -S shutdown -k +1' % (
         command['<sudopassword>'])
     e.Log("Checking our permissions")
     e.Log(prepare)
     if e.Execute(prepare) == 0:
         cmd = 'shutdown -r +1 &'
         e.Log(cmd)
         e.Log(
             "Alert: This will wipe out all the variables created before.")
         p = e.Execute('echo %s|sudo -S %s' %
                       (command['<sudopassword>'], cmd))
         e.setExecCodes("Reboot", "Going down in 1 minute", "Reboot")
Esempio n. 50
0
    def do_IP(self, args):
        command = docopt(str(self.doc), args)
        e = ExecHelper()
        e.reset("IP")
        interface = command["<interface>"]

        myIp = self.myIP(interface)
        e.Log("Found client ip: " + myIp)
        if command["equals"]:
            if command["<address>"] == myIp:
                e.Log("ip addresss equal")
                e.setExecCodes("", "ip addresses equal", "Pass")
                retVal = "Pass"
            else:
                e.Log("IP address not equal")
                e.setExecCodes("", "ip addresses inequal", "Fail")
                retVal = "Fail"
        elif command["contains"]:
            if myIp.startswith(command["<address>"]):
                e.Log("ip addresses contains")
                e.setExecCodes("", "ip addresses contains", "Pass")
                retVal = "Pass"
            else:
                e.Log("ip addresses does not contain")
                e.setExecCodes("", "ip addresses does not contain", "Fail")
                retVal = "Fail"
        print retVal
Esempio n. 51
0
 def do_HTTPCounter(self, args):
     command = docopt(str(self.doc), args)
     e = ExecHelper()
     e.reset("HTTPCounter")
     sudopassword = command['<sudopassword>']
     if command["initialize"]:
         e.Log("HTTPCounter initalizing")
         self.initialize(sudopassword)
         e.setExecCodes(args, "Warning: Does not verify execution", "Pass")
     elif command["resetCounter"]:
         cmd = "echo %s|sudo -S iptables -Z AF" % (sudopassword)
         e.Log("HTTPCounter resetCounter")
         e.Execute(cmd)
         e.setExecCodes(args, "Warning: Does not verify execution", "Pass")
     elif command["getCount"]:
         cmd = "sh -c 'echo %s|sudo -S iptables -vL AF'" % (sudopassword)
         lines = e.RetOutput(cmd).split(os.linesep)
         output = " GET  " + lines[2].split()[0]
         output += " POST " + lines[3].split()[0]
         output += " PUT " + lines[4].split()[0]
         e.r.setOutput(output)
         print output