Python pexpect.spawn() Examples

The following are 30 code examples of pexpect.spawn(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pexpect , or try the search function .
Example #1
Source File: tunnel.py    From Computable with MIT License 8 votes vote down vote up
def _try_passwordless_openssh(server, keyfile):
    """Try passwordless login with shell ssh command."""
    if pexpect is None:
        raise ImportError("pexpect unavailable, use paramiko")
    cmd = 'ssh -f '+ server
    if keyfile:
        cmd += ' -i ' + keyfile
    cmd += ' exit'
    p = pexpect.spawn(cmd)
    while True:
        try:
            p.expect('[Pp]assword:', timeout=.1)
        except pexpect.TIMEOUT:
            continue
        except pexpect.EOF:
            return True
        else:
            return False 
Example #2
Source File: ssh_connection.py    From python-hacker with Apache License 2.0 7 votes vote down vote up
def connect(user, host, password):
    ssh_newkey = 'Are you sure you want to continue connecting'
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)
    ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])

    #超时,返回0
    if ret == 0:
        print '[-] Error Connecting'
        return

    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT, '[P|p]assword:'])

    if ret == 0:
        print '[-] Error Connecting'
        return

    child.sendline(password)
    child.expect(PROMPT)
    return child 
Example #3
Source File: base.py    From omniduct with MIT License 7 votes vote down vote up
def _prepare_smartcard(self, name, filename):
        import pexpect

        remover = pexpect.spawn('ssh-add -e "{}"'.format(filename))
        i = remover.expect(["Card removed:", "Could not remove card", pexpect.TIMEOUT])
        if i == 2:
            raise RuntimeError("Unable to reset card using ssh-agent. Output of ssh-agent was: \n{}\n\n"
                               "Please report this error!".format(remover.before))

        adder = pexpect.spawn('ssh-add -s "{}" -t 14400'.format(filename))
        i = adder.expect(['Enter passphrase for PKCS#11:', pexpect.TIMEOUT])
        if i == 0:
            adder.sendline(getpass.getpass('Please enter your passcode to unlock your "{}" smartcard: '.format(name)))
        else:
            raise RuntimeError("Unable to add card using ssh-agent. Output of ssh-agent was: \n{}\n\n"
                               "Please report this error!".format(remover.before))
        i = adder.expect(['Card added:', pexpect.TIMEOUT])
        if i != 0:
            raise RuntimeError("Unexpected error while adding card. Check your passcode and try again.")

        return True 
Example #4
Source File: rift_expect_session.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def __init__(self, topology_file=None, start_converge_secs=DEFAULT_START_CONVERGE_SECS,
                 reconverge_secs=DEFAULT_RECONVERGE_SECS, log_debug=True):
        rift_cmd = "rift --interactive --non-passive"
        if log_debug:
            rift_cmd += " --log-level debug"
        self._topology_file = topology_file
        if topology_file is not None:
            rift_cmd += " topology/{}.yaml".format(topology_file)
        cmd = "coverage run --parallel-mode {}".format(rift_cmd)
        results_file_name = "rift_expect.log"
        if "RIFT_TEST_RESULTS_DIR" in os.environ:
            results_file_name = os.environ["RIFT_TEST_RESULTS_DIR"] + "/" + results_file_name
        self._results_file = open(results_file_name, 'ab')
        self.write_result("\n\n*** Start session: {}\n\n".format(topology_file))
        self.write_result("TRAVIS : {}\n".format(TRAVIS))
        self.write_result("IPV6   : {}\n\n".format(IPV6))
        self.reconverge_secs = reconverge_secs
        self._expect_session = pexpect.spawn(cmd, logfile=self._results_file, maxread=100000)
        time.sleep(start_converge_secs)
        self.wait_prompt()
        self.check_engine() 
Example #5
Source File: test_telnet.py    From rift-python with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        rift_cmd = ("rift --log-level debug topology/one.yaml")
        cmd = "coverage run --parallel-mode {}".format(rift_cmd)
        results_file_name = "rift_expect.log"
        cli_results_file_name = "rift_telnet_expect.log"
        if "RIFT_TEST_RESULTS_DIR" in os.environ:
            path = os.environ["RIFT_TEST_RESULTS_DIR"] + "/"
            results_file_name = path + results_file_name
            cli_results_file_name = path + cli_results_file_name
        self._results_file = open(results_file_name, 'ab')
        self._cli_results_file = open(cli_results_file_name, 'ab')
        self._expect_session = pexpect.spawn(cmd, logfile=self._results_file)
        self._expect_session.expect("available on port ([0-9]+)", 5.0)
        self._cli_port = int(self._expect_session.match.group(1))
        self._cli_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._cli_socket.connect(("127.0.0.1", self._cli_port))
        self._cli_fd = self._cli_socket.fileno()
        self._cli_expect_session = pexpect.fdpexpect.fdspawn(self._cli_fd,
                                                             logfile=self._cli_results_file) 
Example #6
Source File: ex3_pexpect.py    From python_course with Apache License 2.0 6 votes vote down vote up
def main():
    """Use Pexpect to retrieve the output of 'show ip int brief'."""
    try:
        ip_addr = raw_input("Enter IP address: ")
    except NameError:
        ip_addr = input("Enter IP address: ")
    username = 'pyclass'
    port = 22

    ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
    ssh_conn.timeout = 3

    login(ssh_conn)
    prompt = find_prompt(ssh_conn)

    ssh_conn.sendline('terminal length 0')
    ssh_conn.expect(prompt)

    ssh_conn.sendline('show ip int brief')
    ssh_conn.expect(prompt)

    print('\n>>>>')
    print(ssh_conn.before.decode('utf-8', 'ignore'))
    print('>>>>\n') 
Example #7
Source File: change_passwd.py    From learning-python with MIT License 6 votes vote down vote up
def change_password2(old_passwd, new_passwd):
    child = pexpect.spawn('passwd')
    i = child.expect(['[Oo]ld [Pp]assword', '.current.*password', '[Nn]ew [Pp]assword'])

    # Root does not require old password, so it gets to bypass the next step.
    if i == 0 or i == 1:
        child.sendline(old_passwd)
        child.expect('[Nn]ew [Pp]assword')

    child.sendline(new_passwd)
    i = child.expect(['[Nn]ew [Pp]assword', '[Rr]etype', '[Rr]e-enter'])

    if i == 0:
        print('Host did not like new password. Here is what it said...')
        print(child.before)
        child.send(chr(3)) # Ctrl-C
        child.sendline('') # This should tell remote passwd command to quit.
        return
    child.sendline(new_passwd)
    child.expect(pexpect.EOF) 
Example #8
Source File: ex3_pexpect.py    From pynet with Apache License 2.0 6 votes vote down vote up
def main():
    '''
    Use Pexpect to retrieve the output of 'show ip int brief'
    '''
    ip_addr = raw_input("Enter IP address: ")
    username = 'pyclass'
    port = 22

    ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
    ssh_conn.timeout = 3

    login(ssh_conn)
    prompt = find_prompt(ssh_conn)

    ssh_conn.sendline('terminal length 0')
    ssh_conn.expect(prompt)

    ssh_conn.sendline('show ip int brief')
    ssh_conn.expect(prompt)

    print '\n>>>>'
    print ssh_conn.before
    print '>>>>\n' 
Example #9
Source File: vim-matlab-server.py    From vim-matlab with Mozilla Public License 2.0 6 votes vote down vote up
def output_filter(output_string):
    """
    If the global variable `hide_until_newline` is True, this function will
    return an empty string until it sees a string that contains a newline.
    Used with `pexpect.spawn.interact` and `pexpect.spawn.send` to hide the
    raw command from being shown.

    :param output_string: String forwarded from MATLAB's stdout. Provided
    by `pexpect.spawn.interact`.
    :return: The filtered string.
    """
    global hide_until_newline
    if hide_until_newline:
        if '\n' in output_string:
            hide_until_newline = False
            return output_string[output_string.find('\n'):]
        else:
            return ''
    else:
        return output_string 
Example #10
Source File: test_deployment.py    From Dallinger with MIT License 6 votes vote down vote up
def test_debug_bots(self, env):
        # Make sure debug server runs to completion with bots
        p = pexpect.spawn(
            "dallinger", ["debug", "--verbose", "--bot"], env=env, encoding="utf-8"
        )
        p.logfile = sys.stdout
        try:
            p.expect_exact("Server is running", timeout=300)
            p.expect_exact("Recruitment is complete", timeout=600)
            p.expect_exact("Experiment completed", timeout=60)
            p.expect_exact("Local Heroku process terminated", timeout=10)
        finally:
            try:
                p.sendcontrol("c")
                p.read()
            except IOError:
                pass 
Example #11
Source File: pytest_dallinger.py    From Dallinger with MIT License 6 votes vote down vote up
def debug_experiment(request, env, clear_workers):
    timeout = pytest.config.getvalue("recruiter_timeout", 30)
    # Make sure debug server runs to completion with bots
    p = pexpect.spawn(
        "dallinger", ["debug", "--no-browsers"], env=env, encoding="utf-8"
    )
    p.logfile = sys.stdout

    try:
        p.expect_exact(u"Server is running", timeout=timeout)
        yield p
        if request.node.rep_setup.passed and request.node.rep_call.passed:
            p.expect_exact(u"Experiment completed", timeout=timeout)
            p.expect_exact(u"Local Heroku process terminated", timeout=timeout)
    finally:
        try:
            p.sendcontrol("c")
            p.read()
        except IOError:
            pass 
Example #12
Source File: ex4_pexpect.py    From pynet with Apache License 2.0 5 votes vote down vote up
def main():
    '''
    Use Pexpect to change the logging buffer size (logging buffered <size>).

    Verify this change by examining the output of 'show run'.
    '''
    ip_addr = raw_input("Enter IP address: ")
    username = 'pyclass'
    port = 22

    ssh_conn = pexpect.spawn('ssh -l {} {} -p {}'.format(username, ip_addr, port))
    ssh_conn.timeout = 3

    login(ssh_conn)
    prompt = find_prompt(ssh_conn)
    disable_paging(ssh_conn, prompt)

    ssh_conn.sendline('conf t')
    ssh_conn.expect('#')

    ssh_conn.sendline('logging buffer 9000')
    ssh_conn.expect('#')

    ssh_conn.sendline('end')
    ssh_conn.expect(prompt)

    ssh_conn.sendline('show run | inc logging buffer')
    ssh_conn.expect(prompt)

    print '\n>>>>'
    print ssh_conn.before
    print '>>>>\n' 
Example #13
Source File: pxssh.py    From NoJlede with MIT License 5 votes vote down vote up
def __init__ (self, timeout=30, maxread=2000, searchwindowsize=None, logfile=None, cwd=None, env=None):
        spawn.__init__(self, None, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, logfile=logfile, cwd=cwd, env=env)

        self.name = '<pxssh>'
        
        #SUBTLE HACK ALERT! Note that the command to set the prompt uses a
        #slightly different string than the regular expression to match it. This
        #is because when you set the prompt the command will echo back, but we
        #don't want to match the echoed command. So if we make the set command
        #slightly different than the regex we eliminate the problem. To make the
        #set command different we add a backslash in front of $. The $ doesn't
        #need to be escaped, but it doesn't hurt and serves to make the set
        #prompt command different than the regex.

        # used to match the command-line prompt
        self.UNIQUE_PROMPT = "\[PEXPECT\][\$\#] "
        self.PROMPT = self.UNIQUE_PROMPT

        # used to set shell command-line prompt to UNIQUE_PROMPT.
        self.PROMPT_SET_SH = "PS1='[PEXPECT]\$ '"
        self.PROMPT_SET_CSH = "set prompt='[PEXPECT]\$ '"
        self.SSH_OPTS = "-o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
        # Disabling X11 forwarding gets rid of the annoying SSH_ASKPASS from
        # displaying a GUI password dialog. I have not figured out how to
        # disable only SSH_ASKPASS without also disabling X11 forwarding.
        # Unsetting SSH_ASKPASS on the remote side doesn't disable it! Annoying!
        #self.SSH_OPTS = "-x -o'RSAAuthentication=no' -o 'PubkeyAuthentication=no'"
        self.force_password = False
        self.auto_prompt_reset = True 
Example #14
Source File: plugin.py    From limnoria-plugins with Do What The F*ck You Want To Public License 5 votes vote down vote up
def adventure(self, irc, msg, args, input):
        """<game_name>
        Open <game_name.z*>.
        """
        channel = msg.args[0]
        if not self.registryValue("allowPrivate") and not irc.isChannel(channel):
            irc.reply("Sorry, this game must be played in channel")
            return
        elif self.registryValue("allowPrivate") and not irc.isChannel(channel):
            channel = msg.nick
        game_name = input
        self.game.setdefault(channel, None)
        if self.game[channel]:
            irc.reply(
                "There is a game already in progress on {0}. Please stop that game"
                " first.".format(channel)
            )
        else:
            irc.reply("Starting {0} on {1}. Please wait...".format(game_name, channel))
            game_file = "{0}{1}".format(self.game_path, game_name)
            self.game[channel] = pexpect.spawn(
                "{0} -m -S 0 {1}".format(self.binary, game_file)
            )
            response = self.output(self.game[channel])
            for line in response:
                if line.strip() and line.strip() != ".":
                    irc.reply(line, prefixNick=False) 
Example #15
Source File: shutit_pexpect.py    From shutit with MIT License 5 votes vote down vote up
def _spawn_child(self,
	                 command,
	                 args=None,
	                 timeout=shutit_global.shutit_global_object.default_timeout,
	                 maxread=2000,
	                 searchwindowsize=None,
	                 env=None,
	                 ignore_sighup=False,
	                 echo=True,
	                 preexec_fn=None,
	                 encoding=None,
	                 codec_errors='strict',
	                 dimensions=None,
	                 delaybeforesend=shutit_global.shutit_global_object.delaybeforesend):
		"""spawn a child, and manage the delaybefore send setting to 0
		"""
		shutit = self.shutit
		args = args or []
		pexpect_child = pexpect.spawn(command,
		                              args=args,
		                              timeout=timeout,
		                              maxread=maxread,
		                              searchwindowsize=searchwindowsize,
		                              env=env,
		                              ignore_sighup=ignore_sighup,
		                              echo=echo,
		                              preexec_fn=preexec_fn,
		                              encoding=encoding,
		                              codec_errors=codec_errors,
		                              dimensions=dimensions)
		# Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps.
		# Other things have been attempted, eg tput rmam/smam without success.
		pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1])
		pexpect_child.delaybeforesend=delaybeforesend
		shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG)
		shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self})
		shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG)
		return pexpect_child 
Example #16
Source File: integration_test.py    From aactivator with MIT License 5 votes vote down vote up
def get_proc(shell, homedir):
    return pexpect.spawn(
        shell[0], list(shell[1:]),
        timeout=5,
        env={
            'COVERAGE_PROCESS_START': os.environ.get(
                'COVERAGE_PROCESS_START', '',
            ),
            'PS1': PS1,
            'TOP': os.environ.get('TOP', ''),
            'HOME': str(homedir),
            'PATH': os.path.dirname(sys.executable) + os.defpath
        },
    ) 
Example #17
Source File: corenlp_tokenizer.py    From justcopy-backend with MIT License 5 votes vote down vote up
def _launch(self):
        """Start the CoreNLP jar with pexpect."""
        annotators = ['tokenize', 'ssplit']
        if 'ner' in self.annotators:
            annotators.extend(['pos', 'lemma', 'ner'])
        elif 'lemma' in self.annotators:
            annotators.extend(['pos', 'lemma'])
        elif 'pos' in self.annotators:
            annotators.extend(['pos'])
        annotators = ','.join(annotators)
        options = ','.join(['untokenizable=noneDelete',
                            'invertible=true'])
        cmd = ['java', '-mx' + self.mem, '-cp', '"%s"' % self.classpath,
               'edu.stanford.nlp.pipeline.StanfordCoreNLP', '-annotators',
               annotators, '-tokenize.options', options,
               '-outputFormat', 'json', '-prettyPrint', 'false']

        # We use pexpect to keep the subprocess alive and feed it commands.
        # Because we don't want to get hit by the max terminal buffer size,
        # we turn off canonical input processing to have unlimited bytes.
        self.corenlp = pexpect.spawn('/bin/bash', maxread=100000, timeout=60)
        self.corenlp.setecho(False)
        self.corenlp.sendline('stty -icanon')
        self.corenlp.sendline(' '.join(cmd))
        self.corenlp.delaybeforesend = 0
        self.corenlp.delayafterread = 0
        self.corenlp.expect_exact('NLP>', searchwindowsize=100) 
Example #18
Source File: shell.py    From poetry with MIT License 5 votes vote down vote up
def activate(self, env):  # type: (VirtualEnv) -> None
        if WINDOWS:
            return env.execute(self.path)

        terminal = Terminal()
        with env.temp_environ():
            c = pexpect.spawn(
                self._path, ["-i"], dimensions=(terminal.height, terminal.width)
            )

        if self._name == "zsh":
            c.setecho(False)

        activate_script = self._get_activate_script()
        bin_dir = "Scripts" if WINDOWS else "bin"
        activate_path = env.path / bin_dir / activate_script
        c.sendline("{} {}".format(self._get_source_command(), activate_path))

        def resize(sig, data):
            terminal = Terminal()
            c.setwinsize(terminal.height, terminal.width)

        signal.signal(signal.SIGWINCH, resize)

        # Interact with the new shell.
        c.interact(escape_character=None)
        c.close()

        sys.exit(c.exitstatus) 
Example #19
Source File: _pexpect.py    From Computable with MIT License 5 votes vote down vote up
def search(self, buffer, freshlen, searchwindowsize=None):

        """This searches 'buffer' for the first occurence of one of the regular
        expressions. 'freshlen' must indicate the number of bytes at the end of
        'buffer' which have not been searched before.

        See class spawn for the 'searchwindowsize' argument.

        If there is a match this returns the index of that string, and sets
        'start', 'end' and 'match'. Otherwise, returns -1."""

        absurd_match = len(buffer)
        first_match = absurd_match
        # 'freshlen' doesn't help here -- we cannot predict the
        # length of a match, and the re module provides no help.
        if searchwindowsize is None:
            searchstart = 0
        else:
            searchstart = max(0, len(buffer)-searchwindowsize)
        for index, s in self._searches:
            match = s.search(buffer, searchstart)
            if match is None:
                continue
            n = match.start()
            if n < first_match:
                first_match = n
                the_match = match
                best_index = index
        if first_match == absurd_match:
            return -1
        self.start = first_match
        self.match = the_match
        self.end = self.match.end()
        return best_index 
Example #20
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #21
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #22
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #23
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #24
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #25
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #26
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #27
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #28
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True) 
Example #29
Source File: chapter9_pexpect_1.py    From Mastering-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def show_version(device, prompt, ip, username, password):
    device_prompt = prompt
    child = pexpect.spawn('telnet ' + ip)
    child.expect('Username:')
    child.sendline(username)
    child.expect('Password:')
    child.sendline(password)
    child.expect(device_prompt)
    child.sendline('show version | i V')
    child.expect(device_prompt)
    result = child.before
    child.sendline('exit')
    return device, result 
Example #30
Source File: generate_vars_test.py    From ovirt-ansible-disaster-recovery with Apache License 2.0 5 votes vote down vote up
def generator(tmpdir):
    env = dict(os.environ)
    env["PYTHONUNBUFFERED"] = "x"
    env["GENERATE_VARS_CONF_DIR"] = str(tmpdir)
    env["GENERATE_VARS_OUT_DIR"] = str(tmpdir)
    gen = pexpect.spawn('./generate-vars', env=env)
    try:
        yield gen
    finally:
        gen.terminate(force=True)