本文整理汇总了Python中pexpect.pxssh.ExceptionPxssh方法的典型用法代码示例。如果您正苦于以下问题:Python pxssh.ExceptionPxssh方法的具体用法?Python pxssh.ExceptionPxssh怎么用?Python pxssh.ExceptionPxssh使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pexpect.pxssh
的用法示例。
在下文中一共展示了pxssh.ExceptionPxssh方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_wait_for_onie_rescue_pxsshexception
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def test_wait_for_onie_rescue_pxsshexception(mock_pxssh, mock_post_dev, mock_exit_results, mock_time):
mock_pxssh.return_value.login.side_effect = ExceptionPxssh('Could not establish connection to host')
countdown = 1
poll_delay = 1
user = 'root'
mock_post_dev_calls = [mock.call(message='Cumulus installation in progress. Waiting for boot to ONIE rescue mode. '
'Timeout remaining: 1 seconds',
state='AWAIT-ONLINE'),
mock.call(message='Cumulus installation in progress. Waiting for boot to ONIE rescue mode. '
'Timeout remaining: 0 seconds',
state='AWAIT-ONLINE')
]
local_cb = cumulus_bootstrap.CumulusBootstrap(args['server'], cli_args())
with pytest.raises(SystemExit):
local_cb.wait_for_onie_rescue(countdown, poll_delay, user=user)
mock_post_dev.assert_has_calls(mock_post_dev_calls)
mock_exit_results.assert_called_with(results={'message': 'Device 1.1.1.1 not reachable in ONIE rescue mode within reload countdown.',
'error_type': 'login',
'ok': False})
示例2: OPDemoFunc
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def OPDemoFunc(self, op_dictionary):
'''Process a command table
'''
xresults = {}
try:
for xkey, xcommand in sorted(op_dictionary.items()):
xresults[xkey] = list(
[_f for _f in self.my_console.run_command(xcommand) if _f])
for xkey, xvalue in sorted(xresults.items()):
log.debug('\nCommand Run: "{}"\n{}'.format(
op_dictionary[xkey], '\n'.join(xresults[xkey])), extra=xresults)
except pxssh.ExceptionPxssh as op_pxssh:
self.fail(str(op_pxssh))
except CommandFailed as xe:
my_x = {x: xe.output[x] for x in range(len(xe.output))}
log.debug('\n******************************\nCommand Failed: \n{}\n******************************'.format(
'\n'.join(my_x[y] for y, z in list(my_x.items()))), extra=my_x)
log.debug('\nExitcode {}'.format(xe))
except Exception as func_e:
self.fail('OPDemoFunc Exception handler {}'.format(func_e))
示例3: get_remote_shell
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def get_remote_shell(target_host, sshkey_file=None, user_name=None, wait=True):
log.info("Getting remote shell for target host [%s]", target_host)
horton = Horton()
log.debug("Checking cache for existing Shell session to host")
shell = horton.shells[target_host] if target_host in horton.shells else None
if shell:
if not shell.isalive():
log.debug("Cached shell is not live, recreating")
shell = None
else:
return shell
if not shell:
log.debug("Creating new session")
sshkey_file = sshkey_file if sshkey_file else config.profile['sshkey_file']
user_name = user_name if user_name else 'centos'
while not shell:
try:
shell = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
shell.login(target_host, user_name, ssh_key=sshkey_file, check_local_ip=False)
except (ExceptionPxssh, EOF):
if not wait:
log.info("Target host is not accepting the connection, Wait is not set, returning False...")
return False
else:
log.info("Retrying until target host accepts the connection request...")
sleep(5)
horton.shells[target_host] = shell
log.info("Returning Shell session...")
return shell
示例4: test_onie_install_pxssh_exception
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def test_onie_install_pxssh_exception(mock_pxssh, mock_exit_results, cb_obj, device):
cb_obj.dev = device
exc = ExceptionPxssh('Could not establish connection to host')
mock_pxssh.return_value.login.side_effect = exc
with pytest.raises(SystemExit):
cb_obj.do_onie_install()
mock_exit_results.assert_called_with(results={'ok': False,
'error_type': 'install',
'message': exc})
示例5: rotate
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def rotate(record, newpassword):
""" Grab any required fields from the record """
user = record.login
oldpassword = record.password
result = False
host = record.get('cmdr:host')
try:
s = pxssh.pxssh()
s.login(host, user, oldpassword, sync_multiplier=3)
s.sendline('passwd')
i = s.expect(['[Oo]ld.*[Pp]assword', '[Cc]urrent.*[Pp]assword', '[Nn]ew.*[Pp]assword'])
if i == 0 or i == 1:
s.sendline(oldpassword)
i = s.expect(['[Nn]ew.*[Pp]assword', 'password unchanged'])
if i != 0:
return False
s.sendline(newpassword)
s.expect("Retype [Nn]ew.*[Pp]assword:")
s.sendline(newpassword)
s.prompt()
pass_result = s.before
if "success" in str(pass_result):
logging.info("Password changed successfully")
record.password = newpassword
result = True
else:
logging.error("Password change failed: ", pass_result)
s.logout()
except exceptions.TIMEOUT as t:
logging.error("Timed out waiting for response.")
except pxssh.ExceptionPxssh as e:
logging.error("Failed to login with ssh.")
return result
示例6: wait_for_onie_rescue
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def wait_for_onie_rescue(self, countdown, poll_delay, user='root'):
"""Polls for SSH access to OPX device in ONIE rescue mode.
Args:
countdown (int): Countdown in seconds to wait for device to become reachable.
poll_delay (int): Countdown in seconds between poll attempts.
user (str): SSH username to use. Defaults to 'root'.
"""
while countdown >= 0:
try:
msg = 'OPX installation in progress. Waiting for ONIE rescue mode. Timeout remaining: {} seconds'.format(
countdown)
self.post_device_status(message=msg, state='AWAIT-ONLINE')
self.log.info(msg)
ssh = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
ssh.login(self.target, user, auto_prompt_reset=False)
ssh.PROMPT = 'ONIE:.*#'
ssh.sendline('\n')
ssh.prompt()
return True
except (pexpect.pxssh.ExceptionPxssh, pexpect.exceptions.EOF) as e:
if (str(e) == 'Could not establish connection to host') or isinstance(e, pexpect.exceptions.EOF):
countdown -= poll_delay
time.sleep(poll_delay)
else:
self.log.error('Error accessing {} in ONIE rescue mode: {}.'.format(self.target, str(e)))
self.exit_results(results=dict(
ok=False,
error_type='login',
message='Error accessing {} in ONIE rescue mode: {}.'.format(self.target, str(e))))
else:
self.log.error('Device {} not reachable in ONIE rescue mode within reload countdown.'.format(self.target))
self.exit_results(results=dict(
ok=False,
error_type='login',
message='Device {} not reachable in ONIE rescue mode within reload countdown.'.format(self.target)))
# ##### -----------------------------------------------------------------------
# #####
# ##### OS install process
# #####
# ##### -----------------------------------------------------------------------
示例7: install_os
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def install_os(self):
vendor_dir = os.path.join(self.cli_args.topdir, 'vendor_images', self.os_name)
image_fpath = os.path.join(vendor_dir, self.image_name)
if not os.path.exists(image_fpath):
errmsg = 'Image file does not exist: %s' % image_fpath
self.log.error(errmsg)
self.exit_results(results=dict(
ok=False, error_type='install',
message=errmsg))
msg = 'Installing OPX image=[%s] ... this can take up to 30 min.' % self.image_name
self.log.info(msg)
self.post_device_status(message=msg, state='OS-INSTALL')
try:
ssh = self.get_ssh_session(user=self.user, password=self.passwd, sudo=True)
ssh.sendline('grub-reboot --boot-directory=/mnt/boot ONIE')
ssh.prompt()
ssh.sendline('/mnt/onie-boot/onie/tools/bin/onie-boot-mode -o rescue')
ssh.prompt()
ssh.sendline('reboot')
except pxssh.ExceptionPxssh as e:
self.log.info(str(e))
self.exit_results(results=dict(ok=False, error_type='install', message=str(e)))
msg = 'Booting into ONIE rescue mode to install OS: %s' % self.image_name
self.log.info(msg)
self.post_device_status(message=msg, state='OS-INSTALL')
time.sleep(60)
# Wait for ONIE rescue mode
self.wait_for_onie_rescue(countdown=300, poll_delay=10, user='root')
# Download and verify OS
self.onie_install()
# Wait for onie-rescue shell to terminate
time.sleep(60)
# Wait for device to come back online after OS install
self.wait_for_device(countdown=10 * 60, poll_delay=30)
示例8: wait_for_onie_rescue
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def wait_for_onie_rescue(self, countdown, poll_delay, user='root'):
"""Polls for SSH access to cumulus device in ONIE rescue mode.
The poll functionality was necessary in addition to the current wait_for_device function
because of incompatibilities with the dropbear_2013 OS that is on the cumulus switches and
paramiko in the existing function.
Args:
countdown (int): Countdown in seconds to wait for device to become reachable.
poll_delay (int): Countdown in seconds between poll attempts.
user (str): SSH username to use. Defaults to 'root'.
"""
while countdown >= 0:
try:
msg = 'Cumulus installation in progress. Waiting for boot to ONIE rescue mode. Timeout remaining: {} seconds'.format(countdown)
self.post_device_status(message=msg, state='AWAIT-ONLINE')
self.log.info(msg)
ssh = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
ssh.login(self.target, user, auto_prompt_reset=False)
ssh.PROMPT = 'ONIE:.*#'
ssh.sendline('\n')
ssh.prompt()
return True
except (ExceptionPxssh, EOF) as e:
if (str(e) == 'Could not establish connection to host') or isinstance(e, EOF):
ssh.close()
countdown -= poll_delay
time.sleep(poll_delay)
else:
self.log.error('Error accessing {} in ONIE rescue mode: {}.'.format(self.target, str(e)))
self.exit_results(results=dict(
ok=False,
error_type='login',
message='Error accessing {} in ONIE rescue mode: {}.'.format(self.target, str(e))))
else:
self.log.error('Device {} not reachable in ONIE rescue mode within reload countdown.'.format(self.target))
self.exit_results(results=dict(
ok=False,
error_type='login',
message='Device {} not reachable in ONIE rescue mode within reload countdown.'.format(self.target)))
# ##### -----------------------------------------------------------------------
# #####
# ##### OS install process
# #####
# ##### -----------------------------------------------------------------------
示例9: do_onie_install
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def do_onie_install(self, user='root'):
"""Initiates install in ONIE-RESCUE mode.
Args:
dev (Device object): Cumulus device object
user (str): ONIE rescue mode user
"""
msg = 'Cumulus download and verification in progress.'
self.post_device_status(message=msg, state='ONIE-RESCUE')
self.log.info(msg)
try:
ssh = pxssh.pxssh(options={"StrictHostKeyChecking": "no", "UserKnownHostsFile": "/dev/null"})
ssh.login(self.dev.target, user, auto_prompt_reset=False)
ssh.PROMPT = 'ONIE:.*#'
ssh.sendline('\n')
ssh.prompt()
# Start installation process
ssh.sendline('onie-nos-install http://{server}/images/{os_name}/{image_name}'
.format(server=self.cli_args.server, os_name=self.os_name, image_name=self.image_name))
# 'installer' means that the download has started
ssh.expect('installer', timeout=15)
# Indicates that the image has been downloaded and verified
ssh.expect('Please reboot to start installing OS.', timeout=240)
ssh.prompt()
ssh.sendline('reboot')
time.sleep(2)
msg = 'Cumulus download completed and verified, reboot initiated.'
self.log.info(msg)
self.post_device_status(message=msg, state='OS-INSTALL')
return True
except pxssh.ExceptionPxssh as e:
self.log.info(str(e))
self.exit_results(results=dict(ok=False, error_type='install', message=e))
finally:
ssh.close()
示例10: bringup_vagrant
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def bringup_vagrant():
'''
Bring up a vagrant box and test the ssh connection.
'''
# Clean up Vagrantfile
try:
os.remove('Vagrantfile')
except OSError:
pass
global iosxr_port
global linux_port
# Use vagrant to init, add and bring up the inputted Vagrant VirtualBox
logger.debug("Bringing up '%s'..." % input_box)
logger.debug('vagrant init XRv64-test')
output = run(['vagrant', 'init', 'XRv64-test'])
logger.debug(output)
logger.debug('vagrant box add --name XRv64-test %s --force' % input_box)
output = run(['vagrant', 'box', 'add', '--name', 'XRv64-test', input_box, '--force'])
logger.debug(output)
logger.debug('vagrant up')
output = run(['vagrant', 'up'])
logger.debug(output)
# Find the ports to connect to linux and xr
linux_port = subprocess.check_output('vagrant port --guest 57722', shell=True)
iosxr_port = subprocess.check_output('vagrant port --guest 22', shell=True)
logger.debug('Connecting to port %s' % linux_port)
try:
s = pxssh.pxssh(options={
"StrictHostKeyChecking": "no",
"UserKnownHostsFile": "/dev/null"})
s.login(hostname, username, password, terminal_type, linux_prompt, login_timeout, linux_port)
logger.debug('Sucessfully brought up VM and logged in')
s.logout()
except pxssh.ExceptionPxssh, e:
logger.error("pxssh failed on login")
logger.error(e)
示例11: test_linux
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def test_linux():
'''
Verify logging into IOS XR Linux.
Verify user is 'vagrant'.
Verify can ping 'google.com'.
Verify resolv.conf is populated.
'''
logger.debug('Testing XR Linux...')
logger.debug('Connecting to port %s' % linux_port)
try:
s = pxssh.pxssh(options={
"StrictHostKeyChecking": "no",
"UserKnownHostsFile": "/dev/null"})
s.login(hostname, username, password, terminal_type, linux_prompt, login_timeout, linux_port, auto_prompt_reset=False)
s.prompt()
logger.debug('Successfully logged into XR Linux')
logger.debug('Check user:')
s.sendline('whoami')
output = s.expect(['vagrant', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'Correct user found'):
return False
s.prompt()
logger.debug('Check pinging the internet:')
s.sendline("ping -c 4 google.com | grep '64 bytes' | wc -l")
output = s.expect(['4', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'Successfully pinged'):
return False
s.prompt()
logger.debug('Check resolv.conf is correctly populated:')
s.sendline("cat /etc/resolv.conf | grep 220")
output = s.expect(['nameserver 208.67.220.220', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'nameserver 208.67.220.220 is successfully populated'):
return False
s.prompt()
s.sendline("cat /etc/resolv.conf | grep 222")
output = s.expect(['nameserver 208.67.222.222', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'nameserver 208.67.222.222 is successfully populated'):
return False
s.prompt()
logger.debug('Check vagrant public key has been replaced by private:')
s.sendline('grep "public" ~/.ssh/authorized_keys -c')
output = s.expect(['0', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'SSH public key successfully replaced'):
return False
s.prompt()
s.logout()
except pxssh.ExceptionPxssh as e:
logger.error("pxssh failed on login.")
logger.error(e)
return False
else:
logger.debug("Vagrant SSH to XR Linux is sane")
return True
示例12: test_xr
# 需要导入模块: from pexpect import pxssh [as 别名]
# 或者: from pexpect.pxssh import ExceptionPxssh [as 别名]
def test_xr():
'''
Log into IOS XR Console and run some basic sanity tests.
Verify logging into IOS XR Console directly.
Verify show version.
Verify show run.
'''
if 'k9' not in input_box:
logger.warning('Not a crypto image, will not test XR as no SSH to access.')
return True
logger.debug('Testing XR Console...')
logger.debug('Connecting to port %s' % iosxr_port)
try:
s = pxssh.pxssh(options={
"StrictHostKeyChecking": "no",
"UserKnownHostsFile": "/dev/null"})
s.force_password = True
s.PROMPT = 'RP/0/RP0/CPU0:ios# '
s.login(hostname, username, password, terminal_type, xr_prompt, login_timeout, iosxr_port, auto_prompt_reset=False)
s.prompt()
s.sendline('term length 0')
s.prompt()
logger.debug('Successfully logged into XR Console')
logger.debug('Check show version:')
s.sendline('show version | i cisco IOS XRv x64')
output = s.expect(['XRv x64', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'XRv x64 correctly found in show version'):
return False
s.prompt()
logger.debug('Check show run for username vagrant:')
s.sendline('show run | i username')
output = s.expect(['username vagrant', pexpect.EOF, pexpect.TIMEOUT])
if not check_result(output, 'Username vagrant found'):
return False
s.prompt()
# gRPC is no longer enabled by default due to increasing memory
# requirements. If we decide to re-enable it, here:
# if 'full' in input_box:
# logger.debug('Check show run for grpc:')
# s.sendline('show run grpc')
# output = s.expect(['port 57777', pexpect.EOF, pexpect.TIMEOUT])
# if not check_result(output, 'grpc is configured'):
# return False
# s.prompt()
s.logout()
except pxssh.ExceptionPxssh as e:
logger.error("pxssh failed on login.")
logger.debug(e)
else:
logger.debug("Vagrant SSH to XR Console is sane")
return True