def getVersion(mac): try: clnt = CvpClient() clnt.connect(['{}'.format(host)], user, password) serialNumber = clnt.api.get_device_by_mac(mac)['serialNumber'] version = clnt.get('/api/v1/rest/{}/Eos/image'.format(serialNumber))['notifications'][0]['updates']['version']['value'] except: if trace: sys.stderr.write('cvprac api call to {} unsuccessful.\n'.format(mac)) return None else: if trace: sys.stderr.write('cvprac api call to {} successful.\n'.format(mac)) return version
class TestCvpClient(DutSystemTest): ''' Test cases for the CvpClient class. ''' # pylint: disable=too-many-public-methods NEW_PASSWORD = '******' def setUp(self): ''' Instantiate the CvpClient class. Log messages to the /tmp/TestCvpClient.log ''' super(TestCvpClient, self).setUp() self.clnt = CvpClient(filename='/tmp/TestCvpClient.log') self.assertIsNotNone(self.clnt) def tearDown(self): ''' Destroy the CvpClient class. ''' super(TestCvpClient, self).tearDown() self.clnt = None def _change_passwd(self, nodes, username, old_password, new_password): ''' Helper method to change the user password on CVP. ''' # Create a new connection to handle the request. clnt = CvpClient(filename='/tmp/TestCvpClient.log') clnt.connect(nodes, username, old_password) data = { 'user': { 'userId': username, 'password': new_password, 'email': '*****@*****.**', 'userStatus': 'Enabled', }, 'roles': ['network-admin'] } result = clnt.post("/user/updateUser.do?userId=%s" % username, data) self.assertEqual('success', result['data']) def test_clnt_init(self): ''' Verify CvpClient init ''' clnt = CvpClient() self.assertIsNotNone(clnt) self.assertEqual(clnt.log.getEffectiveLevel(), logging.INFO) def test_clnt_init_syslog(self): ''' Verify CvpClient init with syslog argument ''' clnt = CvpClient(syslog=True) self.assertIsNotNone(clnt) def test_clnt_init_syslog_filename(self): ''' Verify CvpClient init with syslog and filename argument ''' logfile = '/tmp/foo' clnt = CvpClient(syslog=True, logger='cvpracTmp', filename=logfile) self.assertIsNotNone(clnt) os.remove(logfile) def test_clnt_init_log_level(self): ''' Verify CvpClient init with setting log level ''' clnt = CvpClient(log_level='DEBUG') self.assertIsNotNone(clnt) self.assertEqual(clnt.log.getEffectiveLevel(), logging.DEBUG) def test_set_log_level(self): self.clnt.set_log_level('DEBUG') self.assertEqual(self.clnt.log.getEffectiveLevel(), logging.DEBUG) self.clnt.set_log_level('INFO') self.assertEqual(self.clnt.log.getEffectiveLevel(), logging.INFO) def test_set_log_level_invalid_value(self): self.clnt.set_log_level('blahblah') self.assertEqual(self.clnt.log.getEffectiveLevel(), logging.INFO) def test_connect_http_good(self): ''' Verify http connection succeeds to a single CVP node Uses default protocol and port. ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) def test_connect_https_good(self): ''' Verify https connection succeeds to a single CVP node Uses https protocol and port. ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password'], protocol='https') def test_connect_username_bad(self): ''' Verify connect fails with bad username. ''' dut = self.duts[0] with self.assertRaises(CvpLoginError): self.clnt.connect([dut['node']], 'username', dut['password']) def test_connect_password_bad(self): ''' Verify connect fails with bad password. ''' dut = self.duts[0] with self.assertRaises(CvpLoginError): self.clnt.connect([dut['node']], dut['username'], 'password') def test_connect_node_bad(self): ''' Verify connection fails to a single bogus CVP node ''' with self.assertRaises(CvpLoginError): self.clnt.connect(['bogus'], 'username', 'password', connect_timeout=1) def test_connect_non_cvp_node(self): ''' Verify connection fails to a non-CVP node ''' with self.assertRaises(CvpLoginError): self.clnt.connect(['localhost'], 'username', 'password') def test_connect_all_nodes_bad(self): ''' Verify connection fails to a single bogus CVP node ''' with self.assertRaises(CvpLoginError): self.clnt.connect(['bogus1', 'bogus2', 'bogus3'], 'username', 'password', connect_timeout=1) def test_connect_n1_bad_n2_good(self): ''' Verify connect succeeds even if one node is bad ''' dut = self.duts[0] self.clnt.connect(['bogus', dut['node']], dut['username'], dut['password'], connect_timeout=2) def test_connect_nodes_arg_bad(self): ''' Verify non-list nodes argument raises a TypeError ''' with self.assertRaises(TypeError): self.clnt.connect('bogus', 'username', 'password') def test_connect_port_bad(self): ''' Verify non-http protocol with default port raises a TypeError ''' dut = self.duts[0] with self.assertRaises(ValueError): self.clnt.connect([dut['node']], dut['username'], dut['password'], protocol='bogus') def test_get_not_connected(self): ''' Verify get with no connection raises a ValueError ''' with self.assertRaises(ValueError): self.clnt.get('/bogus') def test_get(self): ''' Verify get of CVP info ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.get('/cvpInfo/getCvpInfo.do') self.assertIn('version', result) def test_get_recover_session(self): ''' Verify client(get) recovers session after logout ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.get('/cvpInfo/getCvpInfo.do') self.assertIn('version', result) def test_get_recover_session_bg(self): ''' Verify client(get) recovers session after logout for bad/good node ''' dut = self.duts[0] self.clnt.connect(['bogus', dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.get('/cvpInfo/getCvpInfo.do') self.assertIn('version', result) def test_get_cvp_error(self): ''' Verify get of bad CVP request returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpRequestError): self.clnt.get('/aaa/getServerById.do') def test_get_cvp_url_bad(self): ''' Verify get with bad URL returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpApiError): self.clnt.get('/aaa/bogus.do') def test_get_handle_timeout(self): ''' Verify get with bad URL returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(Timeout): self.clnt.get('/tasks/getTasks.do', timeout=0.0001) def test_get_except_fail_reconnect(self): ''' Verify exception raised if session fails and cannot be re-established. ''' dut = self.duts[0] nodes = ['bogus', dut['node']] self.clnt.connect(nodes, dut['username'], dut['password']) # Change the password for the CVP user so that a session reconnect # to any node will fail self._change_passwd(nodes, dut['username'], dut['password'], self.NEW_PASSWORD) try: # Logout to end the current session and force a reconnect for the # next request. result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) except Exception as error: # Should not have had an exception. Restore the CVP password # and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error try: # Try a get request and expect a CvpSessionLogOutError result = self.clnt.get('/cvpInfo/getCvpInfo.do') except CvpSessionLogOutError as error: pass except Exception as error: # Unexpected error, restore password and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error # Restore password self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) def test_post_not_connected(self): ''' Verify post with no connection raises a ValueError ''' with self.assertRaises(ValueError): self.clnt.post('/bogus', None) def test_post(self): ''' Verify post of CVP info ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) def test_post_recover_session(self): ''' Verify client(post) recovers session after logout ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.post('/login/logout.do', None) self.assertEqual('success', result['data']) def test_post_recover_session_bg(self): ''' Verify client(post) recovers session after logout for bad/good node ''' dut = self.duts[0] self.clnt.connect(['bogus', dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.post('/login/logout.do', None) self.assertEqual('success', result['data']) def test_post_cvp_bad_schema(self): ''' Verify post with bad schema returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpApiError): self.clnt.post('/aaa/saveAAADetails.do', None) def test_post_cvp_url_bad(self): ''' Verify post with bad URL returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpApiError): self.clnt.post('/aaa/bogus.do', None) def test_post_except_fail_reconn(self): ''' Verify exception raised if session fails and cannot be re-established. ''' dut = self.duts[0] nodes = ['bogus', dut['node']] self.clnt.connect(nodes, dut['username'], dut['password']) # Change the password for the CVP user so that a session reconnect # to any node will fail self._change_passwd(nodes, dut['username'], dut['password'], self.NEW_PASSWORD) try: # Logout to end the current session and force a reconnect for the # next request. result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) except Exception as error: # Should not have had an exception. Restore the CVP password # and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error try: # Try a post request and expect a CvpSessionLogOutError result = self.clnt.post('/login/logout.do', None) except CvpSessionLogOutError as error: pass except Exception as error: # Unexpected error, restore password and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error # Restore password self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password'])
from pprint import pprint from cvprac.cvp_client import CvpClient from cvprac.cvp_api import CvpApi import urllib3 import requests urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning ) # This will disable invalid cert warnings clnt = CvpClient() clnt.connect(['cvp.lab.local'], 'jpatterson', 'P3pp3r101!') result = clnt.get('/cvpInfo/getCvpInfo.do') test1 = clnt.get( '/cvpservice/snapshot/getSnapshots.do?startIndex=0&endIndex=0') pprint(result)
class TestCvpClient(DutSystemTest): ''' Test cases for the CvpClient class. ''' # pylint: disable=too-many-public-methods NEW_PASSWORD = '******' def setUp(self): ''' Instantiate the CvpClient class. Log messages to the /tmp/TestCvpClient.log ''' super(TestCvpClient, self).setUp() self.clnt = CvpClient(filename='/tmp/TestCvpClient.log') self.assertIsNotNone(self.clnt) def tearDown(self): ''' Destroy the CvpClient class. ''' super(TestCvpClient, self).tearDown() self.clnt = None def _change_passwd(self, nodes, username, old_password, new_password): ''' Helper method to change the user password on CVP. ''' # Create a new connection to handle the request. clnt = CvpClient(filename='/tmp/TestCvpClient.log') clnt.connect(nodes, username, old_password) data = { 'user': { 'userId': username, 'password': new_password, 'email': '*****@*****.**', 'userStatus': 'Enabled', }, 'roles': [ 'network-admin' ] } result = clnt.post("/user/updateUser.do?userId=%s" % username, data) self.assertEqual('success', result['data']) def test_clnt_init(self): ''' Verify CvpClient init ''' clnt = CvpClient() self.assertIsNotNone(clnt) def test_clnt_init_syslog(self): ''' Verify CvpClient init with syslog argument ''' clnt = CvpClient(syslog=True) self.assertIsNotNone(clnt) def test_clnt_init_syslog_filename(self): ''' Verify CvpClient init with syslog and filename argument ''' logfile = '/tmp/foo' clnt = CvpClient(syslog=True, logger='cvpracTmp', filename=logfile) self.assertIsNotNone(clnt) os.remove(logfile) def test_connect_http_good(self): ''' Verify http connection succeeds to a single CVP node Uses default protocol and port. ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) def test_connect_https_good(self): ''' Verify https connection succeeds to a single CVP node Uses https protocol and port. ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password'], protocol='https') def test_connect_username_bad(self): ''' Verify connect fails with bad username. ''' dut = self.duts[0] with self.assertRaises(CvpLoginError): self.clnt.connect([dut['node']], 'username', dut['password']) def test_connect_password_bad(self): ''' Verify connect fails with bad password. ''' dut = self.duts[0] with self.assertRaises(CvpLoginError): self.clnt.connect([dut['node']], dut['username'], 'password') def test_connect_node_bad(self): ''' Verify connection fails to a single bogus CVP node ''' with self.assertRaises(CvpLoginError): self.clnt.connect(['bogus'], 'username', 'password', connect_timeout=1) def test_connect_non_cvp_node(self): ''' Verify connection fails to a non-CVP node ''' with self.assertRaises(CvpLoginError): self.clnt.connect(['localhost'], 'username', 'password') def test_connect_all_nodes_bad(self): ''' Verify connection fails to a single bogus CVP node ''' with self.assertRaises(CvpLoginError): self.clnt.connect(['bogus1', 'bogus2', 'bogus3'], 'username', 'password', connect_timeout=1) def test_connect_n1_bad_n2_good(self): ''' Verify connect succeeds even if one node is bad ''' dut = self.duts[0] self.clnt.connect(['bogus', dut['node']], dut['username'], dut['password'], connect_timeout=2) def test_connect_nodes_arg_bad(self): ''' Verify non-list nodes argument raises a TypeError ''' with self.assertRaises(TypeError): self.clnt.connect('bogus', 'username', 'password') def test_connect_port_bad(self): ''' Verify non-http protocol with default port raises a TypeError ''' dut = self.duts[0] with self.assertRaises(ValueError): self.clnt.connect([dut['node']], dut['username'], dut['password'], protocol='bogus') def test_get_not_connected(self): ''' Verify get with no connection raises a ValueError ''' with self.assertRaises(ValueError): self.clnt.get('/bogus') def test_get(self): ''' Verify get of CVP info ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.get('/cvpInfo/getCvpInfo.do') self.assertIn('version', result) def test_get_recover_session(self): ''' Verify client(get) recovers session after logout ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.get('/cvpInfo/getCvpInfo.do') self.assertIn('version', result) def test_get_recover_session_bg(self): ''' Verify client(get) recovers session after logout for bad/good node ''' dut = self.duts[0] self.clnt.connect(['bogus', dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.get('/cvpInfo/getCvpInfo.do') self.assertIn('version', result) def test_get_cvp_error(self): ''' Verify get of bad CVP request returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpRequestError): self.clnt.get('/aaa/getServerById.do') def test_get_cvp_url_bad(self): ''' Verify get with bad URL returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpApiError): self.clnt.get('/aaa/bogus.do') def test_get_handle_timeout(self): ''' Verify get with bad URL returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(Timeout): self.clnt.get('/tasks/getTasks.do', timeout=0.0001) def test_get_except_fail_reconnect(self): ''' Verify exception raised if session fails and cannot be re-established. ''' dut = self.duts[0] nodes = ['bogus', dut['node']] self.clnt.connect(nodes, dut['username'], dut['password']) # Change the password for the CVP user so that a session reconnect # to any node will fail self._change_passwd(nodes, dut['username'], dut['password'], self.NEW_PASSWORD) try: # Logout to end the current session and force a reconnect for the # next request. result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) except Exception as error: # Should not have had an exception. Restore the CVP password # and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error try: # Try a get request and expect a CvpSessionLogOutError result = self.clnt.get('/cvpInfo/getCvpInfo.do') except CvpSessionLogOutError as error: pass except Exception as error: # Unexpected error, restore password and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error # Restore password self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) def test_post_not_connected(self): ''' Verify post with no connection raises a ValueError ''' with self.assertRaises(ValueError): self.clnt.post('/bogus', None) def test_post(self): ''' Verify post of CVP info ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) def test_post_recover_session(self): ''' Verify client(post) recovers session after logout ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.post('/login/logout.do', None) self.assertEqual('success', result['data']) def test_post_recover_session_bg(self): ''' Verify client(post) recovers session after logout for bad/good node ''' dut = self.duts[0] self.clnt.connect(['bogus', dut['node']], dut['username'], dut['password']) result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) result = self.clnt.post('/login/logout.do', None) self.assertEqual('success', result['data']) def test_post_cvp_bad_schema(self): ''' Verify post with bad schema returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpApiError): self.clnt.post('/aaa/saveAAADetails.do', None) def test_post_cvp_url_bad(self): ''' Verify post with bad URL returns an error ''' dut = self.duts[0] self.clnt.connect([dut['node']], dut['username'], dut['password']) with self.assertRaises(CvpApiError): self.clnt.post('/aaa/bogus.do', None) def test_post_except_fail_reconn(self): ''' Verify exception raised if session fails and cannot be re-established. ''' dut = self.duts[0] nodes = ['bogus', dut['node']] self.clnt.connect(nodes, dut['username'], dut['password']) # Change the password for the CVP user so that a session reconnect # to any node will fail self._change_passwd(nodes, dut['username'], dut['password'], self.NEW_PASSWORD) try: # Logout to end the current session and force a reconnect for the # next request. result = self.clnt.post('/login/logout.do', None) self.assertIn('data', result) self.assertEqual('success', result['data']) except Exception as error: # Should not have had an exception. Restore the CVP password # and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error try: # Try a post request and expect a CvpSessionLogOutError result = self.clnt.post('/login/logout.do', None) except CvpSessionLogOutError as error: pass except Exception as error: # Unexpected error, restore password and re-raise the error. self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password']) raise error # Restore password self._change_passwd(nodes, dut['username'], self.NEW_PASSWORD, dut['password'])
sheet.column_dimensions['E'].width = 14 sheet.column_dimensions['F'].width = 16 thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin')) ws.cell(row=1, column=1).border = thin_border ws.cell(row=1, column=2).border = thin_border ws.cell(row=1, column=3).border = thin_border ws.cell(row=1, column=4).border = thin_border ws.cell(row=1, column=5).border = thin_border ws.cell(row=1, column=6).border = thin_border cvp_info = client.get('/cvpInfo/getCvpInfo.do') print "################################################################################" print "CVP Version is %s" % (cvp_info['version']) cvp_inventory = client.get('/inventory/devices') no_of_devices = len(cvp_inventory) x = 2 y = 2 z = 1 print "Total Number of Devices in CVP: " + str(no_of_devices) for i in range(no_of_devices): sheet['A' + str(x)].value = cvp_inventory[i]["hostname"]
from pprint import pprint from cvprac.cvp_client import CvpClient from cvprac.cvp_api import CvpApi import urllib3 import requests urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning ) # This will disable invalid cert warnings client = CvpClient() api = CvpApi(client) client.connect(['cvp.lab.local'], 'jpatterson', 'P3pp3r101!') result = client.get('/cvpInfo/getCvpInfo.do') newresult = client.get( 'https://cvp.lab.local/cvpservice/image/getImages.do?startIndex=0&endIndex=0' ) print newresult # test1 = clnt.get('/cvpservice/snapshot/getSnapshots.do?startIndex=0&endIndex=0') print result
#!/usr/bin/env python ''' This program uses cvprac, the CloudVision Portal API to first get a template-ID for snapshot template: SnapshotOfConfig1 and container-ID for container: mlane1, then POST a request for CVP to capture snapshot configs for every switch in the cotainer. ''' from cvprac.cvp_client import CvpClient # Import CvpClient class module clnt = CvpClient() # create clnt object from CvpClient class clnt.connect(['192.168.1.143'], 'cvpadmin', 'cvpadmin1') # Connect to CVP # Next get Container information for mlane1 result = clnt.get( '/inventory/add/searchContainers.do?queryparam=mlane1&startIndex=0&endIndex=0' ) # And, extract the container key or container-ID. contnr = result['data'][0]['key'] # Get information for snapshot template: SnapshotOfConfig1 result2 = clnt.get( '/snapshot/getSnapshotTemplates.do?startIndex=0&endIndex=0&queryparam=SnapshotOfConfig1' ) # And, extract it's key or template-ID snapTemplt = result2['data'][0]['key'] # Build a dictionary which includes: "templateid" and "containerid" parms2 = {"templateId": snapTemplt, "containerId": contnr} # Execute a POST to the Container Snapshot module and pass the parameter dictionary: parms2 snapResult = clnt.post('/snapshot/captureContainerLevelSnapshot.do', parms2)