本文整理汇总了Python中pexpect.spawn方法的典型用法代码示例。如果您正苦于以下问题:Python pexpect.spawn方法的具体用法?Python pexpect.spawn怎么用?Python pexpect.spawn使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pexpect
的用法示例。
在下文中一共展示了pexpect.spawn方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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)
示例2: __init__
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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()
示例3: main
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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')
示例4: _prepare_smartcard
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
示例5: output_filter
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
示例6: connect
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
示例7: debug_experiment
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
示例8: test_debug_bots
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
示例9: _try_passwordless_openssh
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
示例10: main
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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'
示例11: change_password2
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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)
示例12: show_version
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
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
开发者ID:PacktPublishing,项目名称:Mastering-Python-Networking-Second-Edition,代码行数:15,代码来源:chapter9_pexpect_1.py
示例13: __init__
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
def __init__(self, netns, port):
self._netns = netns
self._port = port
log_file_name = "config_generator_check.log"
if "RIFT_TEST_RESULTS_DIR" in os.environ:
log_file_name = os.environ["RIFT_TEST_RESULTS_DIR"] + '/' + log_file_name
self._log_file = open(log_file_name, 'ab')
cmd = "ip netns exec {} telnet localhost {}".format(netns, port)
self._expect_session = pexpect.spawn(cmd, logfile=self._log_file)
self.connected = self.expect("Connected")
示例14: main
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
def main():
"""
Use Pexpect to change the logging buffer size (logging buffered <size>).
Verify this change by examining the output of 'show run'.
"""
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)
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.decode('utf-8', 'ignore'))
print('>>>>\n')
示例15: scptransfer
# 需要导入模块: import pexpect [as 别名]
# 或者: from pexpect import spawn [as 别名]
def scptransfer(src,dest,passwd,**kwargs):
"""
DEFINITION:
copy file by scp
PARAMETERS:
Variables:
- src: (string) e.g. /path/to/local/file or user@remotehost:/path/to/remote/file
- dest: (string) e.g. /path/to/local/file or user@remotehost:/path/to/remote/file
- passwd: (string) users password
Kwargs:
- timeout: (int) define timeout - default is 30
REQUIRES:
Requires package pexpect
USED BY:
cleanup
"""
timeout = kwargs.get('timeout')
COMMAND="scp -oPubKeyAuthentication=no %s %s" % (src, dest)
child = pexpect.spawn(COMMAND)
if timeout:
child.timeout=timeout
child.expect('assword:') # please not "assword" is correct as it supports both "password" and "Password"
child.sendline(passwd)
child.expect(pexpect.EOF)
print(child.before)