本文整理汇总了Python中jnpr.junos.utils.sw.SW类的典型用法代码示例。如果您正苦于以下问题:Python SW类的具体用法?Python SW怎么用?Python SW使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SW类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: shutdown
def shutdown(time=0):
'''
Shuts down the device after the given time.
Usage:
.. code-block:: bash
salt 'device_name' junos.shutdown 10
Options:
* time: Time in seconds after which the device should shutdown (default=0)
'''
conn = __proxy__['junos.conn']()
ret = dict()
sw = SW(conn)
try:
shut = sw.poweroff()
shut(time)
ret['message'] = 'Successfully powered off.'
ret['out'] = False
except Exception as exception:
ret['message'] = 'Could not poweroff'
ret['out'] = False
return ret
示例2: main
def main():
#iterate over csv
for row in devList:
#Make Device Connection
dev = Device(host=row[1], user=userName, password=userPassword)
try:
#Print Opening Header for Status
now1 = datetime.datetime.now()
pprint("Work starts on " + row[0] + " | " + row[1] + " at " + now1.strftime("%Y-%m-%d %H:%M"))
#Open Device with Custom Timer
dev.open()
dev.timeout = 900
except Exception as err:
sys.stderr.write('Cannot connect to device: {0}\n'.format(err))
#Do RPC/Work
try:
#Start Work here
#Create an instance of SW
sw = SW(dev)
try:
ok = sw.install(package=package, remote_path=remote_path, progress=myprogress, validate=validate, no_copy=noCopy, timeout=1800)
except Exception as err:
msg = 'Unable to install software, {0}'.format(err)
print(msg)
ok = False
if ok is True:
print('Software installation complete. Rebooting')
rsp = sw.reboot()
print('Upgrade pending reboot cycle, please be patient.')
print(rsp)
else:
msg = 'Unable to install software, {0}'.format(ok)
print(msg)
#Write Element Seperator
print("+++++++++++++++++++++++++++++++++++++++++++++++++")
#Close Device
dev.close()
except Exception as err:
sys.stderr.write('Cannot perform RPC on device: ' + row[1] + '\n'.format(err))
print("+++++++++++++++++++++++++++++++++++++++++++++++++")
示例3: main
def main():
print("\nWelcome to Junos Upgrade Tool \n")
# Request which code to upgrade with
fileList = getFileList(code_path)
package = getOptionAnswer("Choose a junos package", fileList)
package = code_path + package
# Request IP for the system to upgrade
host = getInputAnswer("IP Address of the host")
# Get username and password parameters
username=getInputAnswer("\nEnter your device username")
password=getpass(prompt="\nEnter your device password: ")
# initialize logging
logging.basicConfig(filename=logfile, level=logging.INFO, format='%(asctime)s:%(name)s: %(message)s')
logging.getLogger().name = host
sys.stdout.write('Information logged in {0}\n'.format(logfile))
# verify package exists
if (os.path.isfile(package)):
found = True
else:
msg = 'Software package does not exist: {0}. '.format(package)
sys.exit(msg + '\nExiting program')
dev = Device(host,user=username,password=password)
try:
dev.open()
except Exception as err:
sys.stderr.write('Cannot connect to device: {0}\n'.format(err))
return
# Increase the default RPC timeout to accommodate install operations
dev.timeout = 300
# Create an instance of SW
sw = SW(dev)
try:
do_log('Starting the software upgrade process: {0}'.format(package))
ok = sw.install(package=package, remote_path=remote_path, progress=update_progress, validate=validate)
except Exception as err:
msg = 'Unable to install software, {0}'.format(err)
do_log(msg, level='error')
else:
if ok is True:
do_log('Software installation complete. Rebooting')
rsp = sw.reboot()
do_log('Upgrade pending reboot cycle, please be patient.')
do_log(rsp)
# End the NETCONF session and close the connection
dev.close()
示例4: main
def main():
# iterate over csv
for row in devList:
# Make Device Connection
dev = Device(host=row[1], user=userName, password=userPassword)
try:
# Print Opening Header for Status
now1 = datetime.datetime.now()
pprint("Work starts on " + row[0] + " | " + row[1] + " at " + now1.strftime("%Y-%m-%d %H:%M"))
# Open Device with Custom Timer
dev.open()
dev.timeout = 900
except Exception as err:
sys.stderr.write("Cannot connect to device: {0}\n".format(err))
# Do RPC/Work
try:
# Start Work here
# Create an instance of SW
sw = SW(dev)
try:
ok = sw.safe_copy(
package=package, remote_path=remote_path, progress=myprogress, clean_fs=freeSpace, timeout=1800
)
except Exception as err:
msg = "Unable to copy software, {0}".format(err)
print (msg)
ok = False
if ok is True:
print ("Software copy complete.")
else:
msg = "Unable to copy software, {0}".format(ok)
print (msg)
# Write Element Seperator
print ("+++++++++++++++++++++++++++++++++++++++++++++++++")
# Close Device
dev.close()
except Exception as err:
sys.stderr.write("Cannot perform RPC on device: " + row[1] + "\n".format(err))
print ("+++++++++++++++++++++++++++++++++++++++++++++++++")
示例5: install_package
def install_package(module, device):
junos = SW(device)
package = module.params['src']
no_copy = module.params['no_copy']
def progress_log(dev, report):
module.log(report)
module.log('installing package')
result = junos.install(package, progress=progress_log, no_copy=no_copy)
if not result:
module.fail_json(msg='Unable to install package on device')
if module.params['reboot']:
module.log('rebooting system')
junos.reboot()
示例6: main
def main():
# initialize logging
logging.basicConfig(filename=logfile, level=logging.INFO,
format='%(asctime)s:%(name)s: %(message)s')
logging.getLogger().name = host
logging.getLogger().addHandler(logging.StreamHandler())
logging.info('Information logged in {0}'.format(logfile))
# verify package exists
if not (os.path.isfile(package)):
msg = 'Software package does not exist: {0}. '.format(package)
logging.error(msg)
sys.exit()
try:
dev = Device(host=host)
dev.open()
except ConnectError as err:
logging.error('Cannot connect to device: {0}\n'.format(err))
return
# Create an instance of SW
sw = SW(dev)
try:
logging.info('Starting the software upgrade process: {0}'.format(package))
ok = sw.install(package=package, remote_path=remote_path,
progress=update_progress, validate=validate)
except Exception as err:
msg = 'Unable to install software, {0}'.format(err)
logging.error(msg)
ok = False
if ok is True:
logging.info('Software installation complete. Rebooting')
# rsp = sw.reboot()
logging.info('Upgrade pending reboot cycle, please be patient.')
logging.info(rsp)
else:
msg = 'Unable to install software, {0}'.format(ok)
logging.error(msg)
# End the NETCONF session and close the connection
dev.close()
示例7: __init__
def __init__(self, host, username, password, *args, **kwargs):
super(JunosDevice, self).__init__(host,
username,
password,
*args,
vendor='juniper',
device_type=JNPR_DEVICE_TYPE,
**kwargs)
self.native = JunosNativeDevice(*args, host=host, user=username, passwd=password, **kwargs)
self.open()
self.cu = JunosNativeConfig(self.native)
self.fs = JunosNativeFS(self.native)
self.sw = JunosNativdSW(self.native)
示例8: InstallOnHost
def InstallOnHost(hostname, username, password, softwareFilePath, rebootTime):
dev = Device(host=hostname, user=username, password=password)
softw = SW(dev)
hash = SW.local_md5(softwareFilePath)
softw.install(softwareFilePath, remote_path='/var/tmp', progress=dev, validate=False, checksum=hash, cleanfs=False, no_copy=False, timeout=1800)
if rebootTime != 0:
softw.reboot(rebootTime)
dev.close()
示例9: TestSW
class TestSW(unittest.TestCase):
@patch('ncclient.manager.connect')
def setUp(self, mock_connect):
mock_connect.side_effect = self._mock_manager
self.dev = Device(host='1.1.1.1', user='rick', password='password123',
gather_facts=False)
self.dev.open()
self.dev._facts = facts
self.sw = self.get_sw()
@patch('jnpr.junos.Device.execute')
def get_sw(self, mock_execute):
mock_execute.side_effect = self._mock_manager
return SW(self.dev)
@patch('ncclient.operations.session.CloseSession.request')
def tearDown(self, mock_session):
self.dev.close()
def test_sw_hashfile(self):
with patch('__builtin__.open', mock_open(), create=True):
import jnpr.junos.utils.sw
with open('foo') as h:
h.read.side_effect = ('abc', 'a', '')
jnpr.junos.utils.sw._hashfile(h, MagicMock())
self.assertEqual(h.read.call_count, 3)
@patch('jnpr.junos.Device.execute')
def test_sw_constructor_multi_re(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertFalse(self.sw._multi_RE)
@patch('jnpr.junos.Device.execute')
def test_sw_constructor_multi_vc(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertFalse(self.sw._multi_VC)
@patch('__builtin__.open')
def test_sw_local_sha256(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_sha256(package),
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934'
'ca495991b7852b855')
@patch('__builtin__.open')
def test_sw_local_md5(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_md5(package),
'd41d8cd98f00b204e9800998ecf8427e')
@patch('__builtin__.open')
def test_sw_local_sha1(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_sha1(package),
'da39a3ee5e6b4b0d3255bfef95601890afd80709')
def test_sw_progress(self):
with self.capture(SW.progress, self.dev, 'running') as output:
self.assertEqual('1.1.1.1: running\n', output)
@patch('paramiko.SSHClient')
@patch('scp.SCPClient.put')
def test_sw_put(self, mock_scp_put, mock_scp):
# mock_scp_put.side_effect = self.mock_put
package = 'test.tgz'
self.sw.put(package)
self.assertTrue(call('test.tgz', '/var/tmp') in mock_scp_put.mock_calls)
@patch('jnpr.junos.utils.scp.SCP.__exit__')
@patch('jnpr.junos.utils.scp.SCP.__init__')
@patch('jnpr.junos.utils.scp.SCP.__enter__')
def test_sw_put_progress(self, mock_enter, mock_scp, mock_exit):
package = 'test.tgz'
mock_scp.side_effect = self._fake_scp
self.sw.put(package, progress=self._myprogress)
self.assertEqual(mock_scp.call_args_list[0][1]['progress'].by10pct, 50)
def _fake_scp(self, *args, **kwargs):
progress = kwargs['progress']
progress('test.tgz', 100, 50)
@patch('jnpr.junos.Device.execute')
def test_sw_pkgadd(self, mock_execute):
mock_execute.side_effect = self._mock_manager
package = 'test.tgz'
self.assertTrue(self.sw.pkgadd(package))
@patch('jnpr.junos.Device.execute')
def test_sw_validate(self, mock_execute):
mock_execute.side_effect = self._mock_manager
package = 'package.tgz'
self.assertTrue(self.sw.validate(package))
@patch('jnpr.junos.Device.execute')
def test_sw_safe_copy(self, mock_execute):
mock_execute.side_effect = self._mock_manager
package = 'safecopy.tgz'
#.........这里部分代码省略.........
示例10: test_sw_local_sha256
def test_sw_local_sha256(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_sha256(package),
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934'
'ca495991b7852b855')
示例11: test_sw_constructor_multi_vc
def test_sw_constructor_multi_vc(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertFalse(self.sw._multi_VC)
示例12: TestSW
class TestSW(unittest.TestCase):
@patch('ncclient.manager.connect')
def setUp(self, mock_connect):
mock_connect.side_effect = self._mock_manager
self.dev = Device(host='1.1.1.1', user='rick', password='password123',
gather_facts=False)
self.dev.open()
self.dev._facts = facts
self.sw = self.get_sw()
@patch('jnpr.junos.Device.execute')
def get_sw(self, mock_execute):
mock_execute.side_effect = self._mock_manager
return SW(self.dev)
@patch('ncclient.operations.session.CloseSession.request')
def tearDown(self, mock_session):
self.dev.close()
def test_sw_hashfile(self):
with patch(builtin_string + '.open', mock_open(), create=True):
import jnpr.junos.utils.sw
with open('foo') as h:
h.read.side_effect = ('abc', 'a', '')
jnpr.junos.utils.sw._hashfile(h, MagicMock())
self.assertEqual(h.read.call_count, 3)
@patch('jnpr.junos.Device.execute')
def test_sw_constructor_multi_re(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertTrue(self.sw._multi_RE)
@patch('jnpr.junos.Device.execute')
def test_sw_constructor_multi_vc(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertFalse(self.sw._multi_VC)
@patch(builtin_string + '.open')
def test_sw_local_sha256(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_sha256(package),
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934'
'ca495991b7852b855')
@patch(builtin_string + '.open')
def test_sw_local_md5(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(self.sw.local_md5(package),
'd41d8cd98f00b204e9800998ecf8427e')
@patch(builtin_string + '.open')
def test_sw_local_sha1(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_sha1(package),
'da39a3ee5e6b4b0d3255bfef95601890afd80709')
def test_sw_progress(self):
with self.capture(SW.progress, self.dev, 'running') as output:
self.assertEqual('1.1.1.1: running\n', output)
def test_sw_progress(self):
with self.capture(SW.progress, self.dev, 'running') as output:
self.assertEqual('1.1.1.1: running\n', output)
@patch('jnpr.junos.Device.execute')
@patch('paramiko.SSHClient')
@patch('scp.SCPClient.put')
def test_sw_progress_true(self, scp_put, mock_paramiko, mock_execute):
mock_execute.side_effect = self._mock_manager
with self.capture(SW.progress, self.dev, 'testing') as output:
self.sw.install('test.tgz', progress=True, checksum=345,
cleanfs=False)
self.assertEqual('1.1.1.1: testing\n', output)
@patch('paramiko.SSHClient')
@patch('scp.SCPClient.put')
def test_sw_put(self, mock_scp_put, mock_scp):
package = 'test.tgz'
self.sw.put(package)
self.assertTrue(
call(
'test.tgz',
'/var/tmp') in mock_scp_put.mock_calls)
@patch('jnpr.junos.utils.sw.FTP')
def test_sw_put_ftp(self, mock_ftp_put):
dev = Device(host='1.1.1.1', user='rick', password='password123',
mode='telnet', port=23, gather_facts=False)
sw = SW(dev)
sw.put(package='test.tgz')
self.assertTrue(
call(
'test.tgz',
'/var/tmp') in mock_ftp_put.mock_calls)
@patch('jnpr.junos.utils.scp.SCP.__exit__')
@patch('jnpr.junos.utils.scp.SCP.__init__')
#.........这里部分代码省略.........
示例13: test_sw_local_sha1
def test_sw_local_sha1(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_sha1(package),
'da39a3ee5e6b4b0d3255bfef95601890afd80709')
示例14: TestSW
class TestSW(unittest.TestCase):
@patch('ncclient.manager.connect')
def setUp(self, mock_connect):
mock_connect.side_effect = self._mock_manager
self.dev = Device(host='1.1.1.1', user='rick', password='password123',
gather_facts=False)
self.dev.open()
self.dev.facts = facts
self.sw = self.get_sw()
@patch('jnpr.junos.Device.execute')
def get_sw(self, mock_execute):
mock_execute.side_effect = self._mock_manager
return SW(self.dev)
@patch('ncclient.operations.session.CloseSession.request')
def tearDown(self, mock_session):
self.dev.close()
def test_sw_hashfile(self):
with patch(builtin_string + '.open', mock_open(), create=True):
import jnpr.junos.utils.sw
with open('foo') as h:
h.read.side_effect = ('abc', 'a', '')
jnpr.junos.utils.sw._hashfile(h, MagicMock())
self.assertEqual(h.read.call_count, 3)
@patch('jnpr.junos.Device.execute')
def test_sw_constructor_multi_re(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertTrue(self.sw._multi_RE)
@patch('jnpr.junos.Device.execute')
def test_sw_constructor_multi_vc(self, mock_execute):
mock_execute.side_effect = self._mock_manager
self.sw = SW(self.dev)
self.assertFalse(self.sw._multi_VC)
@patch(builtin_string + '.open')
def test_sw_local_sha256(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_checksum(package, algorithm='sha256'),
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934'
'ca495991b7852b855')
@patch(builtin_string + '.open')
def test_sw_local_md5(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(self.sw.local_checksum(package, algorithm='md5'),
'd41d8cd98f00b204e9800998ecf8427e')
@patch(builtin_string + '.open')
def test_sw_local_sha1(self, mock_built_open):
package = 'test.tgz'
self.assertEqual(SW.local_checksum(package, algorithm='sha1'),
'da39a3ee5e6b4b0d3255bfef95601890afd80709')
def test_sw_local_checksum_unknown_alg(self):
self.assertRaises(ValueError, SW.local_checksum, 'foo.tgz', algorithm='foo')
def test_sw_progress(self):
with self.capture(SW.progress, self.dev, 'running') as output:
self.assertEqual('1.1.1.1: running\n', output)
@patch('jnpr.junos.Device.execute')
@patch('paramiko.SSHClient')
@patch('scp.SCPClient.put')
def test_sw_progress_true(self, scp_put, mock_paramiko, mock_execute):
mock_execute.side_effect = self._mock_manager
with self.capture(SW.progress, self.dev, 'testing') as output:
self.sw.install('test.tgz', progress=True, checksum=345,
cleanfs=False)
self.assertEqual('1.1.1.1: testing\n', output)
@patch('paramiko.SSHClient')
@patch('scp.SCPClient.put')
def test_sw_put(self, mock_scp_put, mock_scp):
package = 'test.tgz'
self.sw.put(package)
self.assertTrue(
call(
'test.tgz',
'/var/tmp') in mock_scp_put.mock_calls)
@patch('jnpr.junos.utils.sw.FTP')
def test_sw_put_ftp(self, mock_ftp_put):
dev = Device(host='1.1.1.1', user='rick', password='password123',
mode='telnet', port=23, gather_facts=False)
sw = SW(dev)
sw.put(package='test.tgz')
self.assertTrue(
call(
'test.tgz',
'/var/tmp') in mock_ftp_put.mock_calls)
@patch('jnpr.junos.utils.scp.SCP.__exit__')
@patch('jnpr.junos.utils.scp.SCP.__init__')
@patch('jnpr.junos.utils.scp.SCP.__enter__')
#.........这里部分代码省略.........
示例15: JunosDevice
class JunosDevice(BaseDevice):
def __init__(self, host, username, password, *args, **kwargs):
super(JunosDevice, self).__init__(host,
username,
password,
*args,
vendor='juniper',
device_type=JNPR_DEVICE_TYPE,
**kwargs)
self.native = JunosNativeDevice(*args, host=host, user=username, passwd=password, **kwargs)
self.connected = False
self.open()
self.cu = JunosNativeConfig(self.native)
self.fs = JunosNativeFS(self.native)
self.sw = JunosNativdSW(self.native)
def open(self):
if not self.connected:
self.native.open()
self.connected = True
def close(self):
if self.connected:
self.native.close()
self.connected = False
def show(self, command, raw_text=True):
if not raw_text:
raise ValueError('Juniper only supports raw text output. \
Append " | display xml" to your commands for a structured string.')
if not command.startswith('show'):
raise CommandError(command, 'Juniper "show" commands must begin with "show".')
return self.native.cli(command, warning=False)
def show_list(self, commands, raw_text=True):
responses = []
for command in commands:
responses.append(self.show(command, raw_text=raw_text))
return responses
def backup_running_config(self, filename):
with open(filename, 'w') as f:
f.write(self.running_config)
def config(self, command, format='set'):
try:
self.cu.load(command, format=format)
self.cu.commit()
except ConfigLoadError as e:
raise CommandError(command, e.message)
def config_list(self, commands, format='set'):
try:
for command in commands:
self.cu.load(command, format=format)
self.cu.commit()
except ConfigLoadError as e:
raise CommandListError(commands, command, e.message)
def _uptime_components(self, uptime_full_string):
match_days = re.search(r'(\d+) days?', uptime_full_string)
match_hours = re.search(r'(\d+) hours?', uptime_full_string)
match_minutes = re.search(r'(\d+) minutes?', uptime_full_string)
match_seconds = re.search(r'(\d+) seconds?', uptime_full_string)
days = int(match_days.group(1)) if match_days else 0
hours = int(match_hours.group(1)) if match_hours else 0
minutes = int(match_minutes.group(1)) if match_minutes else 0
seconds = int(match_seconds.group(1)) if match_seconds else 0
return days, hours, minutes, seconds
def _uptime_to_string(self, uptime_full_string):
days, hours, minutes, seconds = self._uptime_components(uptime_full_string)
return '%02d:%02d:%02d:%02d' % (days, hours, minutes, seconds)
def _uptime_to_seconds(self, uptime_full_string):
days, hours, minutes, seconds = self._uptime_components(uptime_full_string)
seconds += days * 24 * 60 * 60
seconds += hours * 60 * 60
seconds += minutes * 60
return seconds
def _get_interfaces(self):
eth_ifaces = EthPortTable(self.native)
eth_ifaces.get()
loop_ifaces = LoopbackTable(self.native)
#.........这里部分代码省略.........