def login(self,sshhostname): # Try to ping the host if not sshhostname: logging.critical("login: Hostname empty!") sys.exit(1) else: response = os.system("ping -c 1 " + sshhostname + ' > /dev/null') if response != 0: logging.critical("SSH: Host not reachable! " + sshhostname) sys.exit(1) if not argdictionary['spassword']: cmdstr = 'ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=40 root@' + sshhostname + ' -i ' + argdictionary['server-key'] self.__sshhandle = pexpect.spawn(cmdstr + '\r', timeout= 10) else: cmdstr = 'ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=40 root@' + sshhostname self.__sshhandle = pexpect.spawn('sshpass -p ' + argdictionary['spassword'] + ' ' + cmdstr + '\r', timeout= 10) # we log everything on ssh to a logfile when parameter is not empty if self.expectlogfile != '' : fout = file(self.expectlogfile, 'w') self.__sshhandle.logfile = fout self.__sshhandle.expect('root') self.__sshhandle.setecho(False) self.__sshhandle.setwinsize(30, 300) # Set new Prompt for all commands self.__sshhandle.sendline(self.PROMPT_SET_SH) self.__sshhandle.expect(self.COMMAND_PROMPT) self.cmdsend('export TERM=vt52', 2) # force exit of shell when command has exitcode != 0 self.cmdsend('set -e', 2)
def test_list(self): # list apps and get their names child = pexpect.spawn("{} apps".format(DEIS)) child.expect('=== Apps') child.expect(pexpect.EOF) apps_before = re.findall(r'([-_\w]+) {\w?}', child.before) # create a new app self.assertIsNotNone(self.formation) child = pexpect.spawn("{} apps:create --formation={}".format( DEIS, self.formation)) child.expect('done, created ([-_\w]+)') app = child.match.group(1) child.expect(pexpect.EOF) # list apps and get their names child = pexpect.spawn("{} apps".format(DEIS)) child.expect('=== Apps') child.expect(pexpect.EOF) apps = re.findall(r'([-_\w]+) {\w?}', child.before) # test that the set of names contains the previous set self.assertLess(set(apps_before), set(apps)) # delete the app child = pexpect.spawn("{} apps:destroy --app={} --confirm={}".format( DEIS, app, app)) child.expect('done in ', timeout=5 * 60) child.expect(pexpect.EOF) # list apps and get their names child = pexpect.spawn("{} apps:list".format(DEIS)) child.expect('=== Apps') child.expect(pexpect.EOF) apps = re.findall(r'([-_\w]+) {\w?}', child.before) # test that the set of names is equal to the original set self.assertEqual(set(apps_before), set(apps))
def test_insensitive_fuzzy_matching(): # insensitive fuzzy matching p = pexpect.spawn('pimento "a BLUE thing" "one GREEN thing" -I --fuzzy', timeout=1) p.expect_exact('Options:') p.expect_exact(' a BLUE thing') p.expect_exact(' one GREEN thing') p.expect_exact('Enter an option to continue: ') # send a word at the end of multiple options, but wrong case p.sendline('THING') p.expect_exact('[!] "THING" matches multiple choices:') p.expect_exact('[!] a BLUE thing') p.expect_exact('[!] one GREEN thing') p.expect_exact('[!] Please specify your choice further.') # send a partial word which, with the prior one, still matches multiple options p.sendline('thing e') p.expect_exact('[!] "thing e" matches multiple choices:') p.expect_exact('[!] a BLUE thing') p.expect_exact('[!] one GREEN thing') p.expect_exact('[!] Please specify your choice further.') # send another partial word with wrong case, which, with the prior two, limits to one option p.sendline('thing e e') p.expect_exact('one GREEN thing') # thest words out of order p = pexpect.spawn('pimento "a BLUE thing" "one GREEN thing" --fuzzy', timeout=1) p.expect_exact('Options:') p.expect_exact(' a BLUE thing') p.expect_exact(' one GREEN thing') p.expect_exact('Enter an option to continue: ') p.sendline('thing blue') p.expect_exact('a BLUE thing')
def run_experiments(site, node, iotlab_exp_id, stacktest=False): env = os.environ env.update({'STACKTEST': str(int(bool(stacktest)))}) if stacktest: log_name = "stackusage_%s-%d-%d-%d.txt" % (site, node, iotlab_exp_id, time.time()) else: log_name = "times_%s-%d-%d-%d.txt" % (site, node, iotlab_exp_id, time.time()) logger = pexpect.spawn("/bin/bash", ['-c', "ssh %s@%s.iot-lab.info " % (IOTLAB_USER, site) + "\"tmux -c 'serial_aggregator -i %d &> %s'\"" % (iotlab_exp_id, log_name)]) time.sleep(5) watcher = pexpect.spawn("ssh %s@%s.iot-lab.info 'tail -F %s'" % (IOTLAB_USER, site, log_name), timeout=MAX_EXP_TIME) for app in APPS: for stack in STACKS: if (app[-3:] == 'rpl') and (stack in NON_RPL_STACKS): continue flash("%s/%s" % (app, stack), iotlab_exp_id) start = time.time() watcher.expect("%s_%s stopped" % (stack, app)) duration = time.time() - start print("%s_%s%s ran for %.2f minutes" % (stack, app, " (stacktest)" if stacktest else "", duration / MINUTE)) watcher.terminate() watcher.wait() logger.terminate() logger.wait()
def test_info(self): # create a new app self.assertIsNotNone(self.formation) child = pexpect.spawn("{} create --formation={}".format( DEIS, self.formation)) child.expect('done, created (?P<name>[-_\w]+)') app = child.match.group('name') child.expect('Git remote deis added') child.expect(pexpect.EOF) # get app info child = pexpect.spawn("{} info".format(DEIS)) child.expect("=== {} Application".format(app)) child.expect("=== {} Containers".format(app)) response = json.loads(child.before) child.expect(pexpect.EOF) self.assertEqual(response['id'], app) self.assertEqual(response['formation'], self.formation) self.assertEqual(response['owner'], self.username) self.assertIn('uuid', response) self.assertIn('created', response) self.assertIn('containers', response) # delete the app child = pexpect.spawn("{} apps:destroy --app={} --confirm={}".format( DEIS, app, app)) child.expect('done in ', timeout=5 * 60) child.expect(pexpect.EOF)
def test_insensitive_matching(): # match caps to non-caps # first letter p = pexpect.spawn('pimento FOO BAR BAZ --insensitive', timeout=1) p.expect_exact('Options:') p.expect_exact(' FOO') p.expect_exact(' BAR') p.expect_exact(' BAZ') p.expect_exact('Enter an option to continue: ') p.sendline('Foo') p.expect_exact('FOO') # whole word p = pexpect.spawn('pimento FOO BAR BAZ --insensitive', timeout=1) p.expect_exact('Options:') p.expect_exact(' FOO') p.expect_exact(' BAR') p.expect_exact(' BAZ') p.expect_exact('Enter an option to continue: ') p.sendline('bar') p.expect_exact('BAR') # last letter p = pexpect.spawn('pimento FOO BAR BAZ --insensitive', timeout=1) p.expect_exact('Options:') p.expect_exact(' FOO') p.expect_exact(' BAR') p.expect_exact(' BAZ') p.expect_exact('Enter an option to continue: ') p.sendline('baZ') p.expect_exact('BAZ')
def test_fuzzy_matching(): # test fuzzy matching p = pexpect.spawn('pimento "a blue thing" "one green thing" --fuzzy', timeout=1) p.expect_exact('Options:') p.expect_exact(' a blue thing') p.expect_exact(' one green thing') p.expect_exact('Enter an option to continue: ') # send a word at the end of multiple options p.sendline('thing') p.expect_exact('[!] "thing" matches multiple choices:') p.expect_exact('[!] a blue thing') p.expect_exact('[!] one green thing') p.expect_exact('[!] Please specify your choice further.') # send a partial word which, with the prior one, still matches multiple options p.sendline('thing e') p.expect_exact('[!] "thing e" matches multiple choices:') p.expect_exact('[!] a blue thing') p.expect_exact('[!] one green thing') p.expect_exact('[!] Please specify your choice further.') # send another partial word, which, with the prior two, limits to one option p.sendline('thing e e') p.expect_exact('one green thing') # test words out of order p = pexpect.spawn('pimento "a blue thing" "one green thing" --fuzzy', timeout=1) p.expect_exact('Options:') p.expect_exact(' a blue thing') p.expect_exact(' one green thing') p.expect_exact('Enter an option to continue: ') p.sendline('thing blue') p.expect_exact('a blue thing')
def checks(): if not opts.overwrite: # check if file and/or directory exist already if os.path.exists(opts.backfile): print(" [X] Restore file of the same name: %s already exists\n") % opts.backfile sys.exit(1) if not os.path.exists(opts.directory): print(" [X] Source directory: %s does not exist\n") % opts.directory sys.exit(1) # check openssl zlib support child = pexpect.spawn ('openssl -help') i = child.expect ('zlib') if i==1: print(" [X] Openssl Version does not support zlib") sys.exit(1) # check for star child = pexpect.spawn ('star --version') i = child.expect ('[Oo]ptions') if i==1: print(" [X] Star does not appear to be installed") print(" [X] The star commandline tool is needed as tar does not support removal of trailing slashes") print(" [X] Please install star and try again") sys.exit(1)
def test_iterable_items(): # with a tuple p = pexpect.spawn('python test_pimento.py --tuple', timeout=1) p.expect_exact('Select one of the following:') p.expect_exact(' 100') p.expect_exact(' 200') p.expect_exact(' 300') p.expect_exact('Please select: ') # a string p = pexpect.spawn('python test_pimento.py --string', timeout=1) p.expect_exact('Select one of the following:') p.expect_exact(' a') p.expect_exact(' b') p.expect_exact(' c') p.expect_exact('Please select: ') # a dict p = pexpect.spawn('python test_pimento.py --dictionary', timeout=1) p.expect_exact('Select one of the following:') i = p.expect_exact([' key1', ' key2']) if i == 0: p.expect_exact(' key2') else: p.expect_exact(' key1') p.expect_exact('Please select: ') # a set p = pexpect.spawn('python test_pimento.py --set', timeout=1) p.expect_exact('Select one of the following:') p.expect_exact(' 1') p.expect_exact(' 2') p.expect_exact('Please select: ')
def test04_usersmgmt_removeuser(self): cli = pexpect.spawn('telnet 127.0.0.1 8022', timeout=2) cli.logfile_read = sys.stdout try: cli.expect('Username:'******'admin') cli.expect('Password:'******'test123') cli.expect(PROMT) TestMgmtCLI.CLI = cli self._cmd('help remove-user', 'rmuser') self._cmd('remove-user', 'Usage: REMOVE-USER <user name>') self._cmd('remove-user someuser', 'Error! [50]') self._cmd('remove-user newuser', 'removed') finally: cli.sendline('exit') cli.expect(pexpect.EOF) cli.close(force=True) TestMgmtCLI.CLI = None cli = pexpect.spawn('telnet 127.0.0.1 8022', timeout=2) cli.logfile_read = sys.stdout try: cli.expect('Username:'******'newuser') cli.expect('Password:'******'test') cli.expect('ERROR!') finally: cli.expect(pexpect.EOF) cli.close(force=True)
def testStartupOptions(self): cmd = "python {0} ".format(resource_file("ravel.py")) p = pexpect.spawn(cmd + "--help") p.expect("Usage") p.sendeof() time.sleep(1) p = pexpect.spawn(cmd + "--topo=single,3") p.expect("ravel>") p.sendeof() time.sleep(1) p = pexpect.spawn(cmd + "--topo=single,3 --onlydb") p.expect("ravel>") p.sendline("m") p.sendline("net") p.expect("no CLI available") p.sendline("exit") p.sendeof() time.sleep(1) p = pexpect.spawn(cmd + "--topo single,3 --noctl") p.expect("Unable to contact the remote controller") p.expect("ravel>") p.sendline("exit") p.sendeof()
def esxi_trans_file(usr, host, pwd, filename, newfile): if newfile is not None: cmd = "scp %s %s@%s:%s" % (newfile, usr, host, filename) scp = pexpect.spawn(cmd) else: cmd = "scp %s@%s:%s ./" % (usr, host, filename) scp = pexpect.spawn(cmd) try: i = scp.expect(['[Pp]assword:',r'Are you sure you want to continue connecting \(yes/no\)\?',pexpect.EOF,pexpect.TIMEOUT]) if i == 0: scp.sendline(pwd) elif i == 1: scp.sendline('yes\n') scp.expect('[Pp]assword:') scp.sendline(pwd) except pexpect.EOF: print "pexpect.EOF" scp.close() return -1 except pexpect.TIMEOUT: print "pexpect.timeout" scp.close() return -2 scp.expect(pexpect.EOF, timeout=300) scp.close()
def test_list(self): # list formations and get their names child = pexpect.spawn("{} formations".format(DEIS)) child.expect('=== Formations') child.expect(pexpect.EOF) formations_before = re.findall(r'([-_\w]+) {\w?}', child.before) # create a new formation formation = "{}-test-formation-{}".format(self.username, uuid4().hex[:4]) child = pexpect.spawn("{} formations:create {} --flavor={}".format( DEIS, formation, DEIS_TEST_FLAVOR)) child.expect("created {}.*to scale a basic formation".format(formation)) child.expect(pexpect.EOF) # list formations and get their names child = pexpect.spawn("{} formations".format(DEIS)) child.expect('=== Formations') child.expect(pexpect.EOF) formations = re.findall(r'([-_\w]+) {\w?}', child.before) # test that the set of names contains the previous set self.assertLess(set(formations_before), set(formations)) # delete the formation child = pexpect.spawn("{} formations:destroy {} --confirm={}".format( DEIS, formation, formation)) child.expect('done in ', timeout=5*60) child.expect(pexpect.EOF) # list formations and get their names child = pexpect.spawn("{} formations:list".format(DEIS)) child.expect('=== Formations') child.expect(pexpect.EOF) formations = re.findall(r'([-_\w]+) {\w?}', child.before) # test that the set of names is equal to the original set self.assertEqual(set(formations_before), set(formations))
def test_acquire_keytab(self): self.require(ad_user=True) domain = self.domain() creds = ADCreds(domain) principal = self.ad_user_account() password = self.ad_user_password() creds.acquire(principal, password) os.environ['PATH'] = '/usr/kerberos/sbin:/usr/kerberos/bin:%s' % \ os.environ['PATH'] fullprinc = creds.principal() child = pexpect.spawn('kvno %s' % fullprinc) child.expect('kvno =') kvno = int(child.readline()) child.expect(pexpect.EOF) child = pexpect.spawn('ktutil') child.expect('ktutil:') child.sendline('addent -password -p %s -k %d -e rc4-hmac' % (fullprinc, kvno)) child.expect('Password for.*:') child.sendline(password) child.expect('ktutil:') keytab = self.tempfile(remove=True) child.sendline('wkt %s' % keytab) child.expect('ktutil:') child.sendline('quit') child.expect(pexpect.EOF) creds.release() creds.acquire(principal, keytab=keytab) child = pexpect.spawn('klist') pattern = '.*krbtgt/%s@%s' % (domain.upper(), domain.upper()) assert child.expect([pattern]) == 0
def after_commands(command): # if there is more than one command iterate through if "," in command: command = command.split(",") child = pexpect.spawn("/bin/sh") print "[!] Note that this will drop into a bash shell to execute commands. You will need to type exit once completed." for commands in command: try: child.sendline(commands) except: pass # need to pass an exception here if the install has more things like psexec installer, etc. try: child.interact() except: pass #subprocess.Popen(commands, shell=True).wait() else: child = pexpect.spawn("/bin/sh") print "[!] Note that this will drop into a bash shell to execute commands. You will need to type exit once completed." try: child.sendline(command) except: pass # need to pass an exception here if the install has more things like psexec installer, etc. try: child.interact() except: pass
def main (): t = TunnelThread() while True: try: ps = pexpect.spawn ('nmap -p your_port your_domain.com') time.sleep(1) net_status = ps.expect (['closed','open']) ps = pexpect.spawn ('pgrep -f "%s"' % tunnel_command) time.sleep (0.5) ppid = ps.read() ps.close() if not ppid: time.sleep(3) t.start() elif net_status == 0 and ppid: ps = pexpect.spawn ('pkill -9 -f "%s"' % tunnel_command) time.sleep(3) t = TunnelThread() t.start() time.sleep(3) except pexpect.EOF: pass if __name__ == '__main__': main ()
def get_dataRate(testConf,hostname,devName,startTime,endTime): dataAmount = 0 #login to vpn,dp ssh_dp_proc = pexpect.spawn("ssh deployer@%s"%hostname) wait_server(testConf,ssh_dp_proc,'dp') ssh_dp_proc.sendline("if [ ! -d 'TestBench' ];then mkdir TestBench;fi;cd TestBench") wait_server(testConf,ssh_dp_proc,'dp') ssh_data_proc = pexpect.spawn('sh') wait_server(testConf,ssh_data_proc,'vpn') ssh_data_proc.sendline("scp get_data_amount.py deployer@%s:~/TestBench/"%hostname) wait_server(testConf,ssh_data_proc,'vpn') ssh_data_proc.sendline("scp config_test.json deployer@%s:~/TestBench/"%hostname) wait_server(testConf,ssh_data_proc,'vpn') ssh_data_proc.sendline("scp interact.py deployer@%s:~/TestBench/"%hostname) wait_server(testConf,ssh_data_proc,'vpn') ssh_data_proc.close(force=True) ssh_dp_proc.sendline(r"python ~/TestBench/get_data_amount.py %s wifi %s %s"%\ (os.path.join(testConf['svr_wifi_dir'],devName),str(startTime),str(endTime))) wait_server(testConf,ssh_dp_proc,'dp') tmpList = ssh_dp_proc.before.split('##') dataAmount += int(tmpList[tmpList.index('dataAmount')+1]) ssh_dp_proc.sendline(r"python ~/TestBench/get_data_amount.py %s video %s %s"%\ (os.path.join(testConf['svr_video_dir'],devName),str(startTime),str(endTime))) wait_server(testConf,ssh_dp_proc,'dp') tmpList = ssh_dp_proc.before.split('##') dataAmount += int(tmpList[tmpList.index('dataAmount')+1]) ssh_dp_proc.close(force=True) return (dataAmount/(endTime - startTime))
def main(): user = getpass.getuser() pwd = getpass.getpass() log = open('temp.log','bw+') # Get current running jobs carbon carbon_name = user + '@carbon.science.uva.nl' carbon = pexpect.spawn('ssh ' + carbon_name) carbon.logfile_read = log carbon.expect('Password:'******'\n') carbon.expect('$') carbon.send('qstat | grep -B 1 '+user+'\n') carbon.expect('$') carbon.send('logout\n') carbon.expect(pexpect.EOF) carbon.close() log.seek(0, 0) for line in log: if (user.encode() in line or 'compute'.encode() in line) and \ ('grep'.encode() not in line): print(line.decode()) log.truncate(0) log.close child = pexpect.spawn('rm temp.log') child.expect(pexpect.EOF)
def __init__( self, bluetooth_adr , mode ): if mode == "non-verbose": self.con = pexpect.spawn('gatttool -b ' + bluetooth_adr + ' --interactive') self.con.expect('\[LE\]>', timeout=6000) self.con.sendline('connect') self.con.expect('Connection successful.*\[LE\]>') self.cb = {} return self.con.expect('\[CON\].*>') self.cb = {} return else: self.con = pexpect.spawn('gatttool -b ' + bluetooth_adr + ' --interactive') self.con.expect('\[LE\]>', timeout=600) print "Preparing to connect. You might need to press the side button..." self.con.sendline('connect') # test for success of connect self.con.expect('Connection successful.*\[LE\]>') # Earlier versions of gatttool returned a different message. Use this pattern - #self.con.expect('\[CON\].*>') self.cb = {} return self.con.expect('\[CON\].*>') self.cb = {} return
def WPA_attack(bssid,channel,iface_mon): #Delete old files: if os.path.exists(OS_PATH+'/cr0z0n0_attack-01.csv'): os.remove(OS_PATH+'/cr0z0n0_attack-01.csv') os.remove(OS_PATH+'/cr0z0n0_attack-01.cap') os.remove(OS_PATH+'/cr0z0n0_attack-01.kismet.csv') os.remove(OS_PATH+'/cr0z0n0_attack-01.kismet.netxml') cmd_airodump = pexpect.spawn('airodump-ng --bssid {0} -c {1} -w cr0z0n0_attack {2}'.format(bssid,channel,iface_mon)) time.sleep(5) cmd_aireplay = pexpect.spawn('aireplay-ng -0 10 -a {0} {1}'.format(bssid,iface_mon)) time.sleep(10) cmd_aireplay.close() cmd_airodump.expect(['handshake:',pexpect.TIMEOUT,pexpect.EOF],180) #change time cmd_airodump.close() cmd_crack = pexpect.spawn('aircrack-ng -w dic cr0z0n0_attack-01.cap') cmd_crack.logfile = file(LOG_FILE,'w') cmd_crack.expect(['KEY FOUND!','Failed',pexpect.TIMEOUT,pexpect.EOF],20) #change time cmd_crack.close() key_found = False parse_log_crack = open(LOG_FILE,'r') for line in parse_log_crack: where = line.find('KEY FOUND!') if where > -1: key_end = line.find(']') key_found = line[where+13:key_end] parse_log_crack.close() os.remove(LOG_FILE) return key_found
def test_shell_prompt(self): proc = pexpect.spawn(SHELL_CMD) proc.expect(":21000] default>") self._expect_with_cmd(proc, "use foo", (), 'default') self._expect_with_cmd(proc, "use functional", (), 'functional') self._expect_with_cmd(proc, "use foo", (), 'functional') self._expect_with_cmd(proc, 'use `tpch`', (), 'tpch') self._expect_with_cmd(proc, 'use ` tpch `', (), 'tpch') proc = pexpect.spawn(SHELL_CMD, ['-d', 'functional']) proc.expect(":21000] functional>") self._expect_with_cmd(proc, "use foo", (), 'functional') self._expect_with_cmd(proc, "use tpch", (), 'tpch') self._expect_with_cmd(proc, "use foo", (), 'tpch') proc = pexpect.spawn(SHELL_CMD, ['-d', ' functional ']) proc.expect(":21000] functional>") proc = pexpect.spawn(SHELL_CMD, ['-d', '` functional `']) proc.expect(":21000] functional>") # Start an Impala shell with an invalid DB. proc = pexpect.spawn(SHELL_CMD, ['-d', 'foo']) proc.expect(":21000] default>") self._expect_with_cmd(proc, "use foo", (), 'default') self._expect_with_cmd(proc, "use functional", (), 'functional') self._expect_with_cmd(proc, "use foo", (), 'functional')
def test_sighup(self): # If a parent process sets an Ignore handler for SIGHUP (as on Fedora's # build machines), this test breaks. We temporarily restore the default # handler, so the child process will quit. However, we can't simply # replace any installed handler, because getsignal returns None for # handlers not set in Python code, so we wouldn't be able to restore # them. if signal.getsignal(signal.SIGHUP) == signal.SIG_IGN: signal.signal(signal.SIGHUP, signal.SIG_DFL) restore_sig_ign = True else: restore_sig_ign = False try: child = pexpect.spawn(sys.executable + ' getch.py', ignore_sighup=True) child.expect('READY') child.kill(signal.SIGHUP) for _ in range(10): if not child.isalive(): raise AssertionError('Child should not have exited.') time.sleep(0.1) child = pexpect.spawn(sys.executable + ' getch.py', ignore_sighup=False) child.expect('READY') child.kill(signal.SIGHUP) for _ in range(10): if not child.isalive(): break time.sleep(0.1) else: raise AssertionError('Child should have exited.') finally: if restore_sig_ign: signal.signal(signal.SIGHUP, signal.SIG_IGN)
def ssh_cmd(ip,port,user,keyfile,passwd,cmd): if keyfile <> '': ssh = pexpect.spawn('ssh -p%s -i %s %s@%s "%s"' % (port,keyfile, user, ip, cmd)) #ssh = pexpect.spawn('ssh -p22 -i /home/ruzuojun/.ssh/id_rsa [email protected] uptime') try: i = ssh.expect(["Enter passphrase for key '"+keyfile+"': ", 'continue connecting (yes/no)?']) if i == 0 : ssh.sendline(passwd) r = ssh.read() elif i == 1: ssh.sendline('yes\n') ssh.expect("Enter passphrase for key '"+keyfile+"': ") ssh.sendline(passwd) r = ssh.read() except pexpect.EOF: ssh.close() return r else: ssh = pexpect.spawn('ssh -p%s %s@%s "%s"' % (port, user, ip, cmd)) try: i = ssh.expect(['password: '******'continue connecting (yes/no)?']) if i == 0 : ssh.sendline(passwd) r = ssh.read() elif i == 1: ssh.sendline('yes\n') ssh.expect('password: ') ssh.sendline(passwd) r = ssh.read() except pexpect.EOF: ssh.close() return r
def test_dual_send(board_group, application, env=None): env_sender = os.environ.copy() if env != None: env_sender.update(env) env_sender.update(board_group.boards[0].to_env()) env_receiver = os.environ.copy() if env != None: env_receiver.update(env) env_receiver.update(board_group.boards[1].to_env()) with pexpect.spawn("make", ["-C", application, "term"], env=env_sender, timeout=DEFAULT_TIMEOUT) as sender, \ pexpect.spawn("make", ["-C", application, "term"], env=env_receiver, timeout=DEFAULT_TIMEOUT) as receiver: port = random.randint(0x0000, 0xffff) ipprot = random.randint(0x00, 0xff) receiver_ip = get_ipv6_address(receiver) receiver.sendline(u"ip server start %d" % ipprot) receiver.sendline(u"udp server start %d" % port) # wait for neighbor discovery to be done time.sleep(5) sender.sendline(u"udp send %s %d 01:23" % (receiver_ip, port)) sender.expect_exact(u"Success: send 2 byte to [%s]:%d" % (receiver_ip, port)) receiver.expect(u"000000 01 23") sender.sendline(u"ip send %s %d 01:02:03:04" % (receiver_ip, ipprot)) sender.expect_exact(u"Success: send 4 byte to %s (next header: %d)" % (receiver_ip, ipprot)) receiver.expect(u"000000 60 00 00 00 00 04 %s ff fe 80 00 00 00 00 00 00" % hex(ipprot)[2:]) receiver.expect(u"000010( [0-9a-f]{2}){8} fe 80 00 00 00 00 00 00") receiver.expect(u"000020( [0-9a-f]{2}){8} 01 02 03 04")
def remoteChanged(self,directory): retval = False cwd = os.getcwd() if self.preflight(): return(self.preflight()) if not os.path.isdir(directory): os.makedirs(directory) os.chdir(directory) cmd = 'git rev-parse @{u}' exp = pexpect.spawn(cmd) try: exp.expect('Username.*', timeout=5) exp.sendline(self.username) except: pass exp.expect('Password.*') exp.sendline(self.password) exp.expect('.*') remote = exp.before exp.expect(pexpect.EOF) cmd = 'git rev-parse @' exp = pexpect.spawn(cmd) exp.expect('.*') local = exp.before exp.expect(pexpect.EOF) os.chdir(cwd) if not local == remote: retval = True return(retval)
def osCmd(self): ret = -1 ssh = pexpect.spawn('ssh %s@%s "%s"' % (self.username, self.ip, self.cmd)) try: i = ssh.expect(['password','continue connecting (yes/no)?'],timeout=5) if i == 0 : ssh.sendline(passwd) elif i ==1: ssh.sendline('yes\n') ssh.expect('password:'******'ssh %s@%s "%s"' % (self.username, self.ip, self.cmd)) r = ssh.read() print r #print "EOF" ssh.close() ret = -1 except pexpect.TIMEOUT: ssh.close() ret = -2 return ret
def testOwnNamespace(self): "Test running user ap in its own namespace" pexpect.spawn('mn -c') p = pexpect.spawn('mn --wifi --innamespace --ap user') sleep(3) p.expect(self.prompt) interfaces = [ 'sta1-wlan0', 'ap1-wlan1', '[^-]eth0', 'lo', self.prompt ] p.sendline('ap1 ip addr show') ifcount = 0 while True: index = p.expect(interfaces) if index == 1 or index == 3: ifcount += 1 elif index == 0: self.fail('sta1 interface displayed in "ap1 ip addr show"') elif index == 2: self.fail('wlan0 displayed in "ap1 ip addr show"') else: break # self.assertEqual( ifcount, 2, 'Missing interfaces on ap1' ) # verify that all stations a reachable p.sendline('pingall') p.expect(r'(\d+)% dropped') dropped = int(p.match.group(1)) self.assertEqual(dropped, 0, 'pingall failed') p.expect(self.prompt) p.sendline('exit') p.wait()
def _test_example(self, repo_name): # `git clone` the example app repository repo_type, repo_url = EXAMPLES[repo_name] # print repo_name, repo_type, repo_url clone(repo_url, repo_name) # create an App child = pexpect.spawn("{} create --formation={}".format( DEIS, self.formation)) child.expect('done, created (?P<name>[-_\w]+)') app = child.match.group('name') try: child.expect('Git remote deis added') child.expect(pexpect.EOF) child = pexpect.spawn('git push deis master') # check git output for repo_type, e.g. "Clojure app detected" child.expect("{} app detected".format(repo_type), timeout=2*60) child.expect(' -> master', timeout=10*60) child.expect(pexpect.EOF, timeout=2*60) # TODO: scale up runtime nodes in setUpClass, then # actually fetch the URL with curl and check the output # TODO: `deis config:set POWERED_BY="Automated Testing"` # then re-fetch the URL with curl and recheck the output finally: # destroy the app child = pexpect.spawn( "{} apps:destroy --app={} --confirm={}".format(DEIS, app, app), timeout=5*60) child.expect('Git remote deis removed') child.expect(pexpect.EOF)
def callGit(path, message): os.system("git add -A .") os.system("git commit -m '" + message + "'") try: child = pexpect.spawn("git push origin master") i = child.expect("Username for 'https://github.com': ", 7) if i == 0: child.kill(0) raise Exception("Github seems to want your user and pw...") else: child.wait() except Exception, e: print(e) print("Going to try configure your remote so that I won't require usr/pw in the future...") child = pexpect.spawn("git config --get remote.origin.url") child.expect("\r\n") url = child.before child.kill(0) print("URL") pprint(url) repo = url.rsplit('/',1)[1] print("Repo") pprint(repo) usr = raw_input("Gimme yo github user name = ") pwd = getpass("Now your password = "******"git config remote.origin.url https://"+usr+":"+pwd+"@github.com/mitchmindtree/"+repo) #call("git config remote.origin.url https://"+usr+":"+pwd+"@github.com/mitchmindtree/JenAI.git") os.system("git push origin master")
def calculate_organism(opponent_name, organism_number): p1=pexpect.spawn(opponent_name) p1.setecho(False) p1.delaybeforesend=0 #we can't afford the default delay of 0.2 seconds, which is unnecessary anyway p2=pexpect.spawn("../../vm/vm " + ("%0*d" % (3, organism_number) + ".dna")) p2.setecho(False) p2.delaybeforesend=0 g=game.Game() while not g.finished: if g.next_player==1: process=p1 else: process=p2 process.sendline(g.get_player_string(g.next_player)) process.expect("\d*\r\n") move=int(process.after)%9 if g._board[move]!=0: move=-1 g.play(move) return score(g)
import pexpect import time username = '' password = '' email = '' child = pexpect.spawn('ssh [email protected]') child.expect('new'.encode('big5')) time.sleep(5) print('sending username...') child.sendline(str(username + '\r\n').encode('big5')) child.expect(':') time.sleep(5) print('sending password...') child.sendline(str(password + '\r\n').encode('big5')) time.sleep(5) print('checking password...') log = child.read(128).decode('utf-8', errors='ignore') if '密碼不對' in log: os.system("echo 'PTT login failed!' | mail -s 'Ptt login warning!' " + email) print('Login failed!!') else: print('Login succeed!!') child.close() print('done')
#!/usr/bin/python3 import pexpect devices = { 'iosv-1': { 'prompt': 'iosv-1#', 'ip': '172.16.1.20' }, 'iosv-2': { 'prompt': 'iosv-2#', 'ip': '172.16.1.21' } } username = '******' password = '******' for device in devices.keys(): device_prompt = devices[device]['prompt'] child = pexpect.spawn('telnet ' + devices[device]['ip']) child.expect('Username:'******'Password:'******'show version | i V') child.expect(device_prompt) print(child.before) child.sendline('exit')
import pexpect import getpass import sys command = sys.argv[1] user = input('Username: '******'Enter enable password: '******'192.168.100.1', '192.168.100.2', '192.168.100.3'] for ip in devices_ip: print('Connection to device {}'.format(ip)) with pexpect.spawn('ssh {}@{}'.format(user, ip)) as ssh: ssh.expect('Password:'******'[#>]') ssh.sendline('enable') ssh.expect('Password:'******'#') ssh.sendline('terminal length 0') ssh.expect('#') ssh.sendline(command) ssh.expect('#') print(ssh.before.decode('ascii'))
except Exception,e: print("Exception for operator %s!" %operator) print(e) finally: foo5.close() #case 2 yet to test if sg_un_two=='NA': #sg_port_one=sg_ip_one.split('.')[3]+'22' sg_port_one=get_port_num() #kill any active ports if any os.system("/sbin/fuser -k %s/tcp" %(sg_port_one)) try : print("/usr/bin/ssh -o HostKeyAlias=%s -f -N -l %s -L %s:%s:22 %s" %(sg_ip_one,sg_un_one,sg_port_one,server_ip,sg_ip_one)) foo9=pexpect.spawn("/usr/bin/ssh -o HostKeyAlias=%s -f -N -l %s -L %s:%s:22 %s" %(sg_ip_one,sg_un_one,sg_port_one,server_ip,sg_ip_one)) foo9.expect('.ssword:*') print("Sending password %s" %sg_pw_one) foo9.sendline("%s" %sg_pw_one) #foo1.interact() foo9.close() print("Connection made to SG1 %s" %sg_ip_one) except Exception,e: print("Exception for operator %s first connection!" %operator) print (e) pass for filename in filenames: try : print("spawning") print("/usr/bin/scp -o HostKeyAlias=%s -P %s %s@localhost:%s/%s %s" %(server_ip,sg_port_one,user_name,src,filename,dest))
def login(username, password): child = pexpect.spawn(CLIENT_DIR + '/client', cwd = CLIENT_DIR) child.sendline(username) child.sendline(password) return child
def setUp(self): #print('\n'+ self._testMethodName + ' ', end='') self.server = pexpect.spawn(SERVER_DIR + '/server', cwd = SERVER_DIR)
import pexpect, os f = open("iplist.txt", "r") str = f.readline() os.system("cat /dev/null>/mnt/mylog.txt") while str: ip = 'ssh' + ' ' + str.split()[0] child = pexpect.spawn(ip) fout = file('mylog.txt', 'a+') child.logfile = fout child.expect("password:"******"#") child.sendline("ifconfig") child.expect("#") str = f.readline() f.close()
def __init_ncp_sim(self, nodeid, mode): """ Initialize an NCP simulation node. """ # Default command if no match below, will be overridden if below conditions are met. cmd = 'spinel-cli.py -p ./ot-ncp-%s -n' % mode # If Thread version of node matches the testing environment version. if self.version == self.env_version: if 'RADIO_DEVICE' in os.environ: args = ' %s' % os.environ['RADIO_DEVICE'] else: args = '' # Load Thread 1.2 BBR device when testing Thread 1.2 scenarios # which requires device with Backbone functionality. if self.version == '1.2' and self.is_bbr: if 'OT_NCP_PATH_1_2_BBR' in os.environ: cmd = 'spinel-cli.py -p "%s%s" -n' % ( os.environ['OT_NCP_PATH_1_2_BBR'], args, ) elif 'top_builddir_1_2_bbr' in os.environ: srcdir = os.environ['top_builddir_1_2_bbr'] cmd = '%s/examples/apps/ncp/ot-ncp-%s' % (srcdir, mode) cmd = 'spinel-cli.py -p "%s%s" -n' % ( cmd, args, ) # Load Thread device of the testing environment version (may be 1.1 or 1.2). else: if 'OT_NCP_PATH' in os.environ: cmd = 'spinel-cli.py -p "%s%s" -n' % ( os.environ['OT_NCP_PATH'], args, ) elif 'top_builddir' in os.environ: srcdir = os.environ['top_builddir'] cmd = '%s/examples/apps/ncp/ot-ncp-%s' % (srcdir, mode) cmd = 'spinel-cli.py -p "%s%s" -n' % ( cmd, args, ) # Load Thread 1.1 node when testing Thread 1.2 scenarios for interoperability. elif self.version == '1.1': if 'RADIO_DEVICE_1_1' in os.environ: args = ' %s' % os.environ['RADIO_DEVICE_1_1'] else: args = '' if 'OT_NCP_PATH_1_1' in os.environ: cmd = 'spinel-cli.py -p "%s%s" -n' % ( os.environ['OT_NCP_PATH_1_1'], args, ) elif 'top_builddir_1_1' in os.environ: srcdir = os.environ['top_builddir_1_1'] cmd = '%s/examples/apps/ncp/ot-ncp-%s' % (srcdir, mode) cmd = 'spinel-cli.py -p "%s%s" -n' % ( cmd, args, ) cmd += ' %d' % nodeid print("%s" % cmd) self.pexpect = pexpect.spawn(cmd, timeout=4) # Add delay to ensure that the process is ready to receive commands. time.sleep(0.2) self._expect('spinel-cli >') self.debug(int(os.getenv('DEBUG', '0')))
def __init__(self): self.child = pexpect.spawn("bluetoothctl", echo=False)
print '' print 'Interfaces, routes list, routes details' print '---------------------------------------' # Create regular expressions to match interfaces and OSPF OSPF_pattern = re.compile('^O') intf_pattern = re.compile('(GigabitEthernet)([0-9]\/[0-9])') # Create regular expressions to match prefix and routes prefix_pattern = re.compile('^O.{8}([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[0-9]{1,2})') route_pattern = re.compile('via ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})') # Connect to device and run 'show ip route' command print '--- connecting telnet 10.30.30.1 with cisco/cisco' session = pexpect.spawn('telnet 10.30.30.1', timeout=20) result = session.expect(['Username:'******'Timeout or unexpected reply from device' exit() # Successfully got username prompt, enter username session.sendline('cisco') result = session.expect('Password:'******'cisco') result = session.expect('>')
def run_script(command, script, defs=None, g_timeout=None): """Run a command and check whether it follows a script. :sig: (str, List[Action], Optional[Mapping], Optional[int]) -> Tuple[int, int, List[str]] :param command: Command to run. :param script: Script to check against. :param defs: Variable substitutions. :param g_timeout: Global timeout value for the spawn class :return: Exit status, signal status, and errors. """ defs = defs if defs is not None else {} g_timeout = g_timeout if g_timeout is not None else GLOBAL_TIMEOUT process = pexpect.spawn(command, timeout=g_timeout) process.setecho(False) errors = [] last = script[-1] if len(script) > 0 else None if (last is None) or ((last.type_ != ActionType.EXPECT) and (last.data != "_EOF_")): script.append(Action(ActionType.EXPECT, "_EOF_")) for action in script: if action.data is not pexpect.EOF: action.data = action.data % defs if action.type_ == ActionType.EXPECT: try: expecting = ( "_EOF_" if action.data is pexpect.EOF else ('"%(a)s"' % {"a": action.data}) ) timeout = action.timeout if action.timeout != -1 else g_timeout _logger.debug(" expecting (%ds): %s", timeout, expecting) process.expect(action.data, timeout=action.timeout) output = process.after received = ( "_EOF_" if ".EOF" in repr(output) else ('"%(o)s"' % {"o": output.decode()}) ) _logger.debug(" received: %s", received) except pexpect.EOF: output = process.before received = ( "_EOF_" if ".EOF" in repr(output) else ('"%(o)s"' % {"o": output.decode()}) ) _logger.debug(' received: "%s"', received) process.close(force=True) _logger.debug("FAILED: Expected output not received.") errors.append("Expected output not received.") break except pexpect.TIMEOUT: output = process.before received = ( "_EOF_" if ".EOF" in repr(output) else ('"%(o)s"' % {"o": output.decode()}) ) _logger.debug(' received: "%s"', received) process.close(force=True) _logger.debug("FAILED: Timeout exceeded.") errors.append("Timeout exceeded.") break elif action.type_ == ActionType.SEND: _logger.debug(' sending: "%s"', action.data) process.sendline(action.data) else: process.close(force=True) return process.exitstatus, process.signalstatus, errors
def faultMain(path, trigger, trial, pc, kernel, iteration): global CUDA_GDB_PATH, BREAKPOINT, BREAK_LOCATION, CURRENT_INSTRUCTION, SETPI, MODIFY_REGISTER, REGISTER, THREAD, DELETE_BREAKPOINT, KILL, DELETE_BREAKPOINT2, BREAK_LOCATION2, DELETE_BREAKPOINT3 global CUDA_GDB_EXPECT, BREAKPOINT_EXPECT, EOL_EXPECT, RUN_EXPECT, CONTINUE_EXPECT, CURRENT_INSTRUCTION_EXPECT, THREAD_EXPECT, DELETE_BREAKPOINT_EXPECT, PRINT_PC, ARGUMENT, NEXT_INSTRUCTION, SIGTRAP global logger assert_flag = 0 cuda_gdb_p = pexpect.spawn(CUDA_GDB_PATH + " " + path) cuda_gdb_p.expect(CUDA_GDB_EXPECT) #--------------- # set breakpoint #--------------- cuda_gdb_p.sendline(BREAKPOINT + " " + BREAK_LOCATION) cuda_gdb_p.expect(CUDA_GDB_EXPECT) # cuda_gdb_p.sendline(BREAKPOINT+" "+BREAK_LOCATION2) # cuda_gdb_p.expect(CUDA_GDB_EXPECT) #--------------- # run the program #--------------- cuda_gdb_p.sendline(RUN + ARGUMENT) j = cuda_gdb_p.expect([pexpect.TIMEOUT, CUDA_GDB_EXPECT], timeout=60) if j == 0: logger.info("Error happened! Terminated! 1") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return #--------------------- # reset the breakpoint #--------------------- #logger.info(trigger) rawstr = cuda_gdb_p.before print rawstr while "Kernel " + kernel not in rawstr: cuda_gdb_p.sendline(CONTINUE) cuda_gdb_p.expect(CUDA_GDB_EXPECT, timeout=60) rawstr = cuda_gdb_p.before #logger.info(rawstr) # if the breakpoint is the same as initial breakpoint, do not delete time.sleep(2) #cuda_gdb_p.sendline(BREAKPOINT+" "+BREAK_LOCATION2) #cuda_gdb_p.expect(CUDA_GDB_EXPECT) #print (cuda_gdb_p.before) #cuda_gdb_p.sendline(CONTINUE) #cuda_gdb_p.expect(CUDA_GDB_EXPECT) #print (cuda_gdb_p.before) if BREAK_LOCATION in trigger: pass elif BREAK_LOCATION2 in trigger: cuda_gdb_p.sendline(DELETE_BREAKPOINT) cuda_gdb_p.expect(CUDA_GDB_EXPECT) else: cuda_gdb_p.sendline(DELETE_BREAKPOINT) cuda_gdb_p.expect(CUDA_GDB_EXPECT) #cuda_gdb_p.sendline(DELETE_BREAKPOINT2) #cuda_gdb_p.expect(CUDA_GDB_EXPECT) print trigger cuda_gdb_p.sendline(BREAKPOINT + " " + trigger) cuda_gdb_p.expect(CUDA_GDB_EXPECT) logger.info(cuda_gdb_p.before) #cuda_gdb_p.delaybeforesend = 0 cuda_gdb_p.sendline(CONTINUE) j = cuda_gdb_p.expect([pexpect.TIMEOUT, CUDA_GDB_EXPECT], timeout=60) if j == 0: logger.info("Error happened ! Terminated! 2") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return else: res_continue = cuda_gdb_p.before if "Program exited" in res_continue: logger.info("Cannot hit the breakpoint!") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return # need to see if it is in the loop and jump over iterations logger.info("begin to see how many iterations we need to jump " + str(iteration)) for iter in range(0, iteration - 1): cuda_gdb_p.sendline(CONTINUE) j = cuda_gdb_p.expect([pexpect.TIMEOUT, CUDA_GDB_EXPECT], timeout=60) res = cuda_gdb_p.before logger.info(res) if j == 0: logger.info("Error happened ! Terminated! 5") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return else: res_continue = cuda_gdb_p.before if "Program exited" in res_continue or "Switching " in res_continue: logger.info("Cannot hit the breakpoint!i 5") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return i = 0 counter_i = 0 rand_counter = random.randint(0, configure.instruction_random) while i == 0: cuda_gdb_p.sendline(PRINT_PC) cuda_gdb_p.expect(CUDA_GDB_EXPECT, timeout=600) pcline = cuda_gdb_p.before logger.info(pcline) pcline = pcline.lstrip(" ").rstrip("\r\n") pcline_list = pcline.split(" ") pc_c = pcline_list[len(pcline_list) - 1] logger.info("pc is " + str(pc)) logger.info("new pc is " + str(pc_c)) if "registers" in pc_c or is_number( pc_c) == False or "executing" in pc_c: logger.info("Cannot hit pc in stepi") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() return if int(pc_c) != pc: cuda_gdb_p.sendline(STEPI) k = cuda_gdb_p.expect([pexpect.TIMEOUT, CUDA_GDB_EXPECT], timeout=120) if k == 0: logger.info("Cannot hit pc in stepi") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() return res_pc = cuda_gdb_p.before logger.info(res_pc) if "Termination" in res_pc or "focus" in res_pc or "Focus" in res_pc or "Executing" in res_pc: logger.info("Cannot hit pc!") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() return else: i = 1 counter_i = counter_i + 1 logger.info("counter is " + str(counter_i)) if counter_i >= rand_counter + configure.instruction_counter: logger.info("Cannot hit pc! Pick next random instrcution!") i = 1 #------------------------------ # check the current instruction #------------------------------ cuda_gdb_p.sendline(CURRENT_INSTRUCTION) cuda_gdb_p.expect(CUDA_GDB_EXPECT) curr = cuda_gdb_p.before #logger.info(curr) #------------------------ # get the target register #------------------------ target = curr.split(CURRENT_INSTRUCTION_EXPECT) tar_insn = target[len(target) - 1].lstrip().rstrip("\r\n") reg = getTargetRegister(target[len(target) - 1]) logger.info("Inject into " + reg) if "R" not in reg and "SR" not in reg: logger.info("It is a invalid target! Exit") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() return # if the instruction is memory instruction, the fault is considered activated immediatley. symbol = getRegisterSymbols(target[len(target) - 1]) # dealing with predicate instuctions preDest = "" preDestValue = "" if "@P" in symbol.opcode or "@!P" in symbol.opcode: preDest = symbol.operand[0] cuda_gdb_p.sendline(MODIFY_REGISTER + "$" + preDest) cuda_gdb_p.expect(CUDA_GDB_EXPECT) preDestVList = cuda_gdb_p.before.lstrip().rstrip("\r\n").split("\t") preDestValue = preDestVList[len(preDestVList) - 1] flag = 0 mem_insn = "" mem_value_before = "" if "ST" in symbol.opcode or "LD" in symbol.opcode: flag = 1 mem_insn = tar_insn cuda_gdb_p.sendline(REGISTER + reg) cuda_gdb_p.expect(CUDA_GDB_EXPECT) mem_value_before = cuda_gdb_p.before.lstrip().rstrip("\r\n").split( "\t") logger.info(mem_value_before) #----------------- #inject the fault #----------------- fault = generateFaults(mem_value_before[len(mem_value_before) - 1]) if fault == "Non-numeric": killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return cuda_gdb_p.sendline(MODIFY_REGISTER + "$" + reg + " = " + str(fault)) cuda_gdb_p.expect(CUDA_GDB_EXPECT) #need to obtain next instruction to make the last one get executed cuda_gdb_p.sendline(STEPI) cuda_gdb_p.expect(CUDA_GDB_EXPECT) res = cuda_gdb_p.before if CUDA_EXCEPTION in res: logger.info(res) logger.info("At trial " + str(trial) + " fault in register " + reg + " is activated") logger.info("At trial " + str(trial) + " fault in register " + reg + " crashed" + " latency is 0") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() logger.info("Trail " + str(trial) + " finishes!") return if flag == 1 and symbol.isRepetitive != 1: cuda_gdb_p.sendline(MODIFY_REGISTER + "$" + reg + " = " + mem_value_before[len(mem_value_before) - 1]) cuda_gdb_p.expect(CUDA_GDB_EXPECT) logger.info("Memory instruction change reg " + reg + " back to " + mem_value_before[len(mem_value_before) - 1]) else: instructions = res.split(CURRENT_INSTRUCTION_EXPECT) instruction = instructions[len(instructions) - 1].lstrip().rstrip("\r\n") #get the value of the register cuda_gdb_p.sendline(REGISTER + reg) cuda_gdb_p.expect(CUDA_GDB_EXPECT) value_before = cuda_gdb_p.before.lstrip().rstrip("\r\n").split("\t") logger.info(value_before) if value_before == preDestValue: logger.info("Predicated instruction is not executed!") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return #----------------- #inject the fault #----------------- fault = generateFaults(value_before[len(value_before) - 1]) if fault == "Non-numeric": killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return cuda_gdb_p.sendline(MODIFY_REGISTER + "$" + reg + " = " + str(fault)) cuda_gdb_p.expect(CUDA_GDB_EXPECT) #------------------------------- #check if the fault is activated #------------------------------- isActivated = 0 # 0: not activated 1: activated 2: overwritten if flag == 1: isActivated = 1 logger.info("At trial " + str(trial) + " fault in register " + reg + "is activated at instruction " + mem_insn) else: isActivated = checkActivated(reg, instruction) if isActivated == 1: logger.info("At trial " + str(trial) + " fault in register " + reg + "is activated at instruction " + instruction) if isActivated == 2: logger.info("At trial " + str(trial) + " fault in register " + reg + "is overwritten at instruction " + instruction) res = "" counter = 0 last_inst = "" isPredicated = 0 while isActivated == 0: if CUDA_EXCEPTION in res: logger.info(res) logger.info("At trial " + str(trial) + " fault in register " + reg + " is activated") logger.info("At trial " + str(trial) + " fault in register " + reg + " crashed" + " latency is 0") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() logger.info("Trail " + str(trial) + " finishes!") return if SIGTRAP in res: logger.info(res) logger.info("At trial " + str(trial) + " fault in register " + reg + " is activated") logger.info("At trial " + str(trial) + " fault in register " + reg + " trapped") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() logger.info("Trail " + str(trial) + " finishes!") return if "Focus" not in res: cuda_gdb_p.sendline(STEPI) k = cuda_gdb_p.expect([pexpect.TIMEOUT, CUDA_GDB_EXPECT], timeout=300) if k == 0: logger.info("Error happened ! Terminated! 3") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return res = cuda_gdb_p.before instructions = res.split(CURRENT_INSTRUCTION_EXPECT) instruction = instructions[len(instructions) - 1].lstrip().rstrip("\r\n") symbol_check = getRegisterSymbols(instruction) if "@P" in symbol_check.opcode or "@!P" in symbol_check.opcode: preDest = symbol_check.operand[0] cuda_gdb_p.sendline(MODIFY_REGISTER + "$" + preDest) cuda_gdb_p.expect(CUDA_GDB_EXPECT) preDestVList = cuda_gdb_p.before.lstrip().rstrip("\r\n").split( "\t") preDestValue = preDestVList[len(preDestVList) - 1] isPredicated = 1 last_inst = instruction else: if isPredicated == 1: cuda_gdb_p.sendline(MODIFY_REGISTER + "$" + preDest) cuda_gdb_p.expect(CUDA_GDB_EXPECT) preDestVList = cuda_gdb_p.before.lstrip().rstrip( "\r\n").split("\t") preDestValue_new = preDestVList[len(preDestVList) - 1] if preDestValue != preDestValue: logger.info("Predicate inst is executed! Check") isActivated = checkActivated(reg, last_inst) if isActivated == 0: isActivated = checkActivated(reg, instruction) else: logger.info("Predicate inst is not executed! Skip!") isActivated = checkActivated(reg, instruction) isPredicated = 0 else: isActivated = checkActivated(reg, instruction) if isActivated == 2: logger.info("At trial " + str(trial) + " fault in register " + reg + " is overwritten at instruction " + instruction) if isActivated == 1: logger.info("At trial " + str(trial) + " fault in register " + reg + " is activated at instruction " + instruction) else: logger.info("At trial " + str(trial) + " fault in register " + reg + " is not observed at instruction " + instruction) isActivated = 3 counter = counter + 1 if counter >= 800: logger.info("At trial " + str(trial) + " fault in register " + reg + " is not observed") break cuda_gdb_p.sendline(DELETE_BREAKPOINT) cuda_gdb_p.expect(CUDA_GDB_EXPECT) cuda_gdb_p.sendline(DELETE_BREAKPOINT2) cuda_gdb_p.expect(CUDA_GDB_EXPECT) cuda_gdb_p.sendline(DELETE_BREAKPOINT3) cuda_gdb_p.expect(CUDA_GDB_EXPECT) start = datetime.now() cuda_gdb_p.sendline(CONTINUE) # 1 timeout 2 pass 3 exception try: i = cuda_gdb_p.expect([pexpect.TIMEOUT, CUDA_GDB_EXPECT], timeout=120) if i == 0: logger.info("At trial " + str(trial) + " fault in register " + reg + " is hang ") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() return elif i == 1: logs = cuda_gdb_p.before logger.info(logs) buf = StringIO.StringIO(logs) log = buf.readlines() for item in log: if "Caught" in item: assert_flag = 1 #logger.info(logs) if CUDA_EXCEPTION in logs: logger.info(logs) end = datetime.now() latency = end - start logger.info("At trial " + str(trial) + " fault in register " + reg + " crashed" + " latency is " + str(latency.seconds) + "s " + str(latency.microseconds) + "micros") if assert_flag == 1: logger.info("crash_and_asserted") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) #cuda_gdb_p.close() return elif SIGTRAP in logs: logger.info(logs) end = datetime.now() latency = end - start logger.info("At trial " + str(trial) + " fault in register " + reg + " trapped") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return else: #compare the results ret = checkFile(configure.outputfile) #ret = runChecker(configure.comparestring,configure.checkstring) if ret > 0: logger.info("At trial " + str(trial) + " fault in register " + reg + " executed correctly") if assert_flag == 1: logger.info("correct_and_asserted") else: logger.info("At trial " + str(trial) + " fault in register " + reg + " executed incorrectly") if assert_flag == 1: logger.info("incorrect_and_asserted") except pexpect.TIMEOUT: logger.info("At trial " + str(trial) + " fault in register " + reg + " is hang ") if assert_flag == 1: logger.info("hang_and_asserted") killProcess(configure.benchmark) cuda_gdb_p.terminate(force=True) cuda_gdb_p.close() return logger.info("Trail " + str(trial) + " finishes!") logger.info("\n")
def __init__(self, port=4444): self.child = pexpect.spawn( "sh -c 'telnet localhost %d | tee openocd-cli.log'" % port) self.child.expect("> ")
import pexpect, sys # child = pexpect.spawn('qemu-system-arm -M realview-eb-mpcore -kernel openwrt-realview-vmlinux-initramfs.elf -nographic') # Obsolete child = pexpect.spawn( 'qemu-system-arm -net nic,vlan=0 -net nic,vlan=1 -net user,vlan=1 -nographic -M virt -m 64 -kernel openwrt-armvirt-32-zImage-initramfs' ) child = pexpect.spawn( 'qemu-system-arm -nographic -M virt -m 64 -kernel openwrt-armvirt-32-zImage-initramfs' ) child.logfile = sys.stdout child.expect('Please press Enter to activate this console.') child.sendline('') # child.expect('root@(none):/#') child.expect('root@') child.sendline('uname -a') child.expect('root@') child.sendline('cat /proc/cmdline') child.expect('root@') child.sendline('opkg') child.expect('root@') child.sendline( 'opkg update') # Internet connection not working! should work now... child.expect('root@') child.sendline('halt') child.expect('root@') # child.expect(pexpect.EOF) print child.before
#! /usr/bin/env python3 import pexpect import sys print('npm login') child = pexpect.spawn('npm login', timeout=15) child.logfile_read = sys.stdout.buffer child.expect('Username:'******'qiulang2000') child.expect('Password:'******'tongtongjiajia') child.expect('Email:') child.sendline('*****@*****.**') child.expect('Logged in as') # If a logfile is specified, then the data sent and received from the child process in interact mode is duplicated to the given log. # child.interact()
def setUp(self): #print('\n'+ self._testMethodName + ' ', end='') #result = False self.server = pexpect.spawn(SERVER_DIR + '/server', cwd=SERVER_DIR) test_id = 'CBA' test_capacity = '10'
def run(port): ## Create the config file if secure: if not os.path.exists(private_pem) or not os.path.exists( public_pem): print "In order to use an SECURE encrypted notebook, you must first run notebook.setup()." print "Now running notebook.setup()" notebook_setup() if not os.path.exists(private_pem) or not os.path.exists( public_pem): print "Failed to setup notebook. Please try notebook.setup() again manually." strport = 'tls:%s:interface=%s:privateKey=%s:certKey=%s' % ( port, address, private_pem, public_pem) else: strport = 'tcp:%s:interface=%s' % (port, address) notebook_opts = '"%s",address="%s",port=%s,secure=%s' % ( os.path.abspath(directory), address, port, secure) if open_viewer: if require_login: start_path = "'/?startup_token=%s' % startup_token" else: start_path = "'/'" open_page = "from sage.server.misc import open_page; open_page('%s', %s, %s, %s)" % ( address, port, secure, start_path) else: open_page = '' config = open(conf, 'w') config.write(""" #################################################################### # WARNING -- Do not edit this file! It is autogenerated each time # the notebook(...) command is executed. #################################################################### # Now set things up and start the notebook import sage.server.notebook.notebook sage.server.notebook.notebook.JSMATH=True import sage.server.notebook.notebook as notebook twist.notebook = notebook.load_notebook(%s) twist.SAGETEX_PATH = "%s" twist.OPEN_MODE = %s twist.SID_COOKIE = str(hash("%s")) twist.init_updates() worksheet.init_sage_prestart(twist.notebook.get_server(), twist.notebook.get_ulimit()) def save_notebook(): from twisted.internet.error import ReactorNotRunning print "Saving notebook..." twist.notebook.save() try: reactor.stop() except ReactorNotRunning: pass print "Notebook cleanly saved." def my_sigint(x, n): save_notebook() signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGINT, my_sigint) ## Disable client-side certificate request for gnutls try: import gnutls.connection gnutls.connection.CERT_REQUEST = 0 except OSError: print "Note: GNUTLS not available." ## Authentication framework (ported from Knooboo) realm = avatars.LoginSystem() p = portal.Portal(realm) startup_token = '%%x' %% random.randint(0, 2**128) startup_checker = avatars.OneTimeTokenChecker() startup_checker.token = startup_token p.registerChecker(startup_checker) password_checker = avatars.PasswordChecker() p.registerChecker(password_checker) p.registerChecker(checkers.AllowAnonymousAccess()) rsrc = guard.MySessionWrapper(p) log.DefaultCommonAccessLoggingObserver().start() site = server.Site(rsrc) factory = channel.HTTPFactory(site) application = service.Application("SAGE Notebook") s = strports.service('%s', factory) %s s.setServiceParent(application) reactor.addSystemEventTrigger('before', 'shutdown', save_notebook) """ % (notebook_opts, sagetex_path, not require_login, os.path.abspath(directory), strport, open_page)) config.close() ## Start up twisted if not quiet: print_open_msg('localhost' if not address else address, port, secure=secure) if secure and not quiet: print "There is an admin account. If you do not remember the password," print "quit the notebook and type notebook(reset=True)." cmd = 'sage -twistd --pidfile="%s"/twistd.pid -ny "%s"/twistedconf.tac' % ( directory, directory) if fork: return pexpect.spawn(cmd) else: e = os.system(cmd) if e == 256: raise socket.error return True
def step_impl(context, command): context.child = pexpect.spawn(command, encoding='utf-8')
def test_bad_arguments_suggest_fdpsawn(self): " assert custom exception for spawn(int). " expect_errmsg = "maybe you want to use fdpexpect.fdspawn" with self.assertRaisesRegexp(pexpect.ExceptionPexpect, ".*" + expect_errmsg): pexpect.spawn(1)
(options, args) = parser.parse_args() if not options.username: usage("--username is required") if not options.current_password: usage("--current-password is required") if not options.new_password: usage("--new-password is required") if not options.host: usage("--host is required") base64_kcpassword = b64encode(kcpassword_xor(options.new_password)) print("base64'd kcpassword: %s" % base64_kcpassword) child = pexpect.spawn( "ssh -o PubkeyAuthentication=no -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null %s@%s" % (options.username, options.host)) child.expect('Password:'******'Last login:'******'Password:'******'passwd') child.expect('Old Password:'******'New Password:'******'Retype New Password:')
def test_eof(self): " call to expect() after EOF is received raises pexpect.EOF " child = pexpect.spawn('cat') child.sendeof() with self.assertRaises(pexpect.EOF): child.expect('the unexpected')
def test_bad_type_in_expect(self): " expect() does not accept dictionary arguments. " child = pexpect.spawn('cat') with self.assertRaises(TypeError): child.expect({})
import pexpect from getpass import getpass pwd = getpass("password: ") child = pexpect.spawn('sudo cat /etc/shadow') child.expect('.*ssword.*:') child.sendline(pwd) child.expect(pexpect.EOF, timeout=None) cmd_show_data = child.before cmd_output = cmd_show_data.split('\r\n') for data in cmd_output: print(data)
def test_terminate(self): " test force terminate always succeeds (SIGKILL). " child = pexpect.spawn('cat') child.terminate(force=1) assert child.terminated
def testBenchmark(self): "Run benchmark and verify that it takes less than 2 seconds" p = pexpect.spawn('mn --test none') p.expect('completed in ([\d\.]+) seconds') time = float(p.match.group(1)) self.assertTrue(time < 2, 'Benchmark takes more than 2 seconds')
def test_write(self): " write a character and return it in return. " child = pexpect.spawn('cat', echo=False) child.write('a') child.write('\r') self.assertEqual(child.readline(), b'a\r\n')
def launch(directory, cmd): return pexpect.spawn(cmd, cwd=directory, logfile=sys.stdout, timeout=120)
def test_read_poll_timeout(self): " Test use_poll properly times out " child = pexpect.spawn('sleep 5', use_poll=True) with self.assertRaises(pexpect.TIMEOUT): child.expect(pexpect.EOF, timeout=1)
def cus_exec(cmdline): child = pexpect.spawn(cmdline) return child.before
def testHelp(self): "Check the usage message" p = pexpect.spawn('mn -h') index = p.expect(['Usage: mn', pexpect.EOF]) self.assertEqual(index, 0)