def get_api(self): cloudshell_api_scheme = CloudShellSessionContext._get_api_scheme( self.context) if "https" in cloudshell_api_scheme.lower(): try: result = CloudShellAPISession( host=self.context.connectivity.server_address, token_id=self.context.connectivity.admin_auth_token, username=None, password=None, cloudshell_api_scheme=CloudShellSessionContext. _get_api_scheme(self.context), domain=CloudShellSessionContext._get_domain(self.context), ) except TypeError: raise Exception( self.__class__.__name__, "Current version of cloudshell api does not support https", ) else: result = CloudShellAPISession( host=self.context.connectivity.server_address, token_id=self.context.connectivity.admin_auth_token, username=None, password=None, domain=CloudShellSessionContext._get_domain(self.context), ) return result
def _get_api_from_context(self, context): token_id = context.connectivity.admin_auth_token host = context.connectivity.server_address domain = context.reservation.domain return CloudShellAPISession(host=host, domain=domain, token_id=token_id)
def run_parsed_config(self, context): self._get_logger_with_reservation_id(context) session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) Reservation_Description = session.GetReservationDetails( context.reservation.reservation_id).ReservationDescription parser = parse_config.parse_commands( session, res_id=context.reservation.reservation_id, logger=self.logger) parsed_commands = parser.replace_placeholders( file_name=COREVSRXFILENAME, file_type='txt', reservation_description=Reservation_Description) # for command in parsed_commands: # self._send_command(context, command=command) result = [] try: temp_result = self._send_command(context=context, command=parsed_commands) except Exception as e: self.logger.error(e) temp_result = e result.append(temp_result) return result
def send_any_cmd(self, context, sendcmd): """ :param InitCommandContext context : passed in by cloudshell :param str sendcmd: the command to send to the CLI """ cli = CLI() mode = CommandMode(r'#') # for example r'%\s*$' session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) address = context.resource.address user = context.resource.attributes['LinuxServerShell.User'] password = session.DecryptPassword( context.resource.attributes['LinuxServerShell.Password']).Value session_types = [ SSHSession(host=address, username=user, password=password) ] with cli.get_session(session_types, mode) as default_session: out = default_session.send_command(sendcmd) print(out) return out
def doing_stuff(self, num, statistics): self.random_sleep() api = CloudShellAPISession(self.host, self.username, self.password, self.domain) # self.random_sleep() self.reserve_topology(api, self.topology, num, statistics) # self.random_sleep() self.check_reservation_status(api, num, statistics)
def create_session_from_deployment() -> CloudShellAPISession: """ Create session from data in deployment yaml file. """ host, username, password, domain = get_credentials_from_deployment() session = CloudShellAPISession(host, username, password, domain) # session.domain is Domain ID so we save the domain name in session.domain_name session.domain_name = domain return session
def _infoblox_connector(self, context): logger = self._get_logger(context) cs_api = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain="Global") infoblox_address = context.resource.address infoblox_username = context.resource.attributes.get( f"{context.resource.model}.User") infoblox_password = cs_api.DecryptPassword( context.resource.attributes.get( f"{context.resource.model}.Password")).Value # infoblox version as attribute infoblox_config = { "host": infoblox_address, "username": infoblox_username, "password": infoblox_password, "ssl_verify": False, "wapi_version": "2.5" } try: cs_api.WriteMessageToReservationOutput( context.reservation.reservation_id, f"Connecting to InfoBlox: '{infoblox_address}'") logger.info(f"Connecting to InfoBlox: '{infoblox_address}'") connector.LOG = logger infoblox_connector = connector.Connector(infoblox_config) return infoblox_connector except Exception as e: msg = f"Error connecting to infoblox: '{e}'" logger.error(msg) raise Exception(msg)
def delete_all_records(self, context): """ :param ResourceCommandContext context: :return: """ DNS_ATTRIBUTE = "DNS Name" logger = self._get_logger(context) logger.info("Starting delete all records") cs_api = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain="Global") reservation_details = cs_api.GetReservationDetails( context.reservation.reservation_id).ReservationDescription for resource in reservation_details.Resources: attribute_name = "{}.{}".format(resource.ResourceModelName, DNS_ATTRIBUTE) try: result = cs_api.GetAttributeValue(resource.Name, attribute_name).Value if result: try: self.delete_host_record(context, result) except Exception as e: logger.error( f"Error deleting record for '{result}'. error: {e}" ) except Exception as e: logger.info( f"Error getting DNS Attribute '{DNS_ATTRIBUTE}' on resource '{resource.Name}'. Error: {e}" )
def use_cloudshell_api_session(self, context): """ A simple example function returning a string :param ResourceCommandContext context: the context the command runs on """ session = CloudShellAPISession(host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain)
def __init__(self, printOutput=False): creds = QSCreds() appWSHPort = creds.appWSHPort appMainPort = creds.appMainPort # Start the websocket hander appWSH = tornado.web.Application([ (r"/", WebSocketHandler), ]) appWSH.listen(appWSHPort) if printOutput: csapi = CloudShellAPISession(creds.Host, creds.Un, creds.Pw, creds.Dom) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, "Head to: http://" + socket.gethostbyname(socket.gethostname()) + ":" + str(appMainPort)) # start main app settings = { "static_path": os.path.join(os.path.dirname(__file__), "static") } appMain = tornado.web.Application([ (r"/", MainHandler), ], **settings) appMain.listen(appMainPort) tornado.ioloop.IOLoop.current().start()
def get_snmp(self, context, snmp_module_name, miboid): """ :param InitCommandContext context: this is the context passed by cloudshell automatically :param str snmp_module_name: MIB name :param str miboid: 'management information base object id' test two :return: """ session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) reservation_id = context.reservation.reservation_id logger = get_qs_logger() address = context.resource.address snmp_read_community = session.DecryptPassword( context.resource.attributes['LinuxServerShell.SNMP Read Community'] ).Value snmp_v2_parameters = SNMPV2ReadParameters( ip=address, snmp_read_community=snmp_read_community) snmp_service = QualiSnmp(snmp_v2_parameters, logger) for index, info in snmp_service.get_table(snmp_module_name, miboid).items(): session.WriteMessageToReservationOutput(reservation_id, "[{0}]".format(index)) for key, value in info.items(): session.WriteMessageToReservationOutput( reservation_id, " {0}: {1}".format(key, value)) return "\nEnd of execution"
def create_from_context(cls, context): """ Creates an instance of NXOS by given context :param context: cloudshell.shell.core.driver_context.ResourceCommandContext :type context: cloudshell.shell.core.driver_context.ResourceCommandContext :return: :rtype SentryPdu """ try: domain = context.reservation.domain except: domain = 'Global' api = CloudShellAPISession( context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, port=context.connectivity.cloudshell_api_port, domain=domain) result = SentryPdu(name=context.resource.name, api=api) for attr in context.resource.attributes: result.attributes[attr] = context.resource.attributes[attr] return result
def set_pxe_onetime_boot_device(self, context): csapi = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, username=None, password=None, domain=CloudShellSessionContext._get_domain(context)) url = 'https://%s/redfish/v1/Systems/System.Embedded.1' % self.idrac_ip payload = {"Boot": {"BootSourceOverrideTarget": "Pxe"}} headers = {'content-type': 'application/json'} response = requests.patch(url, data=json.dumps(payload), headers=headers, verify=False, auth=(self.idrac_username, self.idrac_password)) data = response.json() statusCode = response.status_code if statusCode == 200: msg = "%s set next boot onetime boot device to: Pxe" % self.resourcename self.logger.info(msg) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, msg) csapi.SetResourceLiveStatus(self.resourcename, 'PXE Set', 'Set to PXE boot') else: detail_message = str(response.__dict__) msg = "%s set boot command failed, errror code is %s, %s" % ( self.resourcename, statusCode, detail_message) self.logger.info(msg) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, msg)
def ping_check(self, context): try: csapi = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, username=None, password=None, domain=CloudShellSessionContext._get_domain(context)) ping_ret_code = subprocess.call( ['ping', '-n', '2', self.resourceaddress], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) tstamp = datetime.datetime.now().strftime("%I:%M%p") + " UTC" if ping_ret_code == 0: msg = "%s ping successful" % self.resourcename msg1 = "Ping successful at %s" % (tstamp) csapi.SetResourceLiveStatus(self.resourcename, 'Ping OK', msg1) else: msg = "%s did not answer ping. Still booting?" % ( self.resourcename) msg1 = "Ping unsuccessful at %s" % (tstamp) csapi.SetResourceLiveStatus(self.resourcename, 'Info', msg1) self.logger.info(msg) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, msg) except Exception as ex: msg = "Ping call failed, %s" % str(ex) self.logger.error(msg) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, msg) msg = "Ping call failed at %s" % (tstamp) csapi.SetResourceLiveStatus(self.resourcename, 'Error', msg)
def create_session_from_config() -> CloudShellAPISession: """ Create session from data in shellfoundry config. """ config = Configuration(CloudShellConfigReader()).read() session = CloudShellAPISession(config.host, config.username, config.password, config.domain) # session.domain is Domain ID so we save the domain name in session.domain_name session.domain_name = config.domain return session
def __initApiSession__(self, context): """ :param context: ResourceCommandContext :return: """ return CloudShellAPISession(host=context.connectivity.server_address, port=context.connectivity.cloudshell_api_port, token_id=context.connectivity.admin_auth_token, domain="Global")
def power_off(self, context): tstamp = datetime.datetime.now().strftime("%I:%M%p") + " UTC" csapi = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, username=None, password=None, domain=CloudShellSessionContext._get_domain(context)) url = 'https://%s/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset' % self.idrac_ip payload = {'ResetType': 'ForceOff'} headers = {'content-type': 'application/json'} response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False, auth=(self.idrac_username, self.idrac_password)) statusCode = response.status_code if statusCode == 204: msg = "%s powering OFF for reboot" % self.resourcename self.logger.info(msg) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, msg) msg = "Powering OFF for reboot at %s" % (tstamp) csapi.SetResourceLiveStatus(self.resourcename, 'Power OFF', msg) else: msg = "%s - failed to power OFF server, status code: %s, %s" % \ (self.resourcename, statusCode, str(response.json())) self.logger.error(msg) csapi.WriteMessageToReservationOutput( context.reservation.reservation_id, msg) msg = "Failed to power OFF at %s" % (tstamp) csapi.SetResourceLiveStatus(self.resourcename, 'Error', msg) sys.exit()
def pre_autoload_configuration_command(self, context): """ A simple example function :param cloudshell.shell.core.driver_context.ResourceCommandContext context: the context the command runs on """ self.api = CloudShellAPISession(host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain='Global') self.user_msg = get_sandbox_msg(self.api, context) self.user_msg('Checking port configuration on {0}'.format(self.name)) for attribute_name in REQUIRED_ATTRIBUTES: if attribute_name not in context.resource.attributes: raise Exception( EX_MISSING_ATTRIBUTE.format(self.model, attribute_name)) number_of_ports = int(context.resource.attributes[ATTR_NUMBER_OF_PORTS]) number_of_cpus = int(context.resource.attributes[ATTR_NUMBER_OF_CPUS]) memory_in_gbs = int(context.resource.attributes[ATTR_MEMORY_IN_GBS]) vm_changes = dict() vm_changes = self._get_nic_changes(number_of_ports, vm_changes) vm_changes = self._get_CPU_changes(number_of_cpus, vm_changes) vm_changes = self._get_memory_changes(memory_in_gbs, vm_changes) vm_changes_params = json.dumps(vm_changes) if vm_changes: self.api.ExecuteResourceConnectedCommand(context.reservation.reservation_id, context.resource.name, 'modify_vm_hardware', 'remote_app_management', [vm_changes_params]) pass
def connect(): """ Create Xena manager object and connect to chassis. """ global xm global chassis global port1 global port2 global session global sandbox_id session = CloudShellAPISession('localhost', 'admin', 'admin', 'Global') if 'SANDBOX_ID' in environ: sandbox_id = environ['SANDBOX_ID'] else: context = create_command_context(session, ['xena 2g/Module6/Port0', 'xena 2g/Module6/Port1'], 'Xena Controller', {}) sandbox_id = context.reservation.reservation_id reserved_port1, reserved_port2 = get_reservation_resources(session, sandbox_id, 'Xena Chassis Shell 2G.GenericTrafficGeneratorPort') port1 = get_address(reserved_port1) port2 = get_address(reserved_port2) chassis = port1.split('/')[0] logger = logging.getLogger('log') logger.setLevel('INFO') logger.addHandler(logging.StreamHandler(sys.stdout)) xm = init_xena(logger, owner) xm.session.add_chassis(chassis)
def _send_command(self, context, command): """ :param ResourceCommandContext context: :return: """ session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) username = context.resource.attributes.get( '{Model}.User'.format(Model=context.resource.model)) password_enc = context.resource.attributes.get( '{Model}.Password'.format(Model=context.resource.model)) password = session.DecryptPassword(password_enc).Value my_session = cloudshell_cli_handler.CreateSession( host=context.resource.address, username=username, password=password, logger=self.logger) if not isinstance(command, list): commands = [command] else: commands = command outp = my_session.send_terminal_command(commands, password=password) self.logger.info(outp) return outp
def get_inventory(self, context): """ Discovers the resource structure and attributes. :param AutoLoadCommandContext context: the context the command runs on :return Attribute and sub-resource information for the Shell resource :rtype: AutoLoadDetails """ session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain="Global") pw = session.DecryptPassword( context.resource.attributes['Password']).Value un = context.resource.attributes["User"] ip = context.resource.address port = str(context.resource.attributes["API Port"]) prefix = str(context.resource.attributes["API Access"]) url = prefix + "://" + ip + ":" + port + "/api" sub_resources = [] attributes = [ AutoLoadAttribute('', 'Model', 'Ixia 58xx'), AutoLoadAttribute('', 'Vendor', 'Ixia') ] # get all ports requests.packages.urllib3.disable_warnings(InsecureRequestWarning) portsRequest = requests.get(url + '/ports', auth=HTTPBasicAuth(un, pw), verify=False) portsObj = json.loads(portsRequest.text) # loop thru each port and learn more for port in portsObj: portRequest = requests.get(url + '/ports/' + str(port['id']), auth=HTTPBasicAuth(un, pw), verify=False) portObj = json.loads(portRequest.text) sub_resources.append( AutoLoadResource(model='NTO Port', name=portObj['default_name'], relative_address=str(port['id']))) attributes.append( AutoLoadAttribute(str(port['id']), 'Port Speed', portObj['media_type'])) attributes.append( AutoLoadAttribute(str(port['id']), 'Serial Number', portObj['uuid'])) attributes.append( AutoLoadAttribute( str(port['id']), 'Port Description', str(portObj['name']) + " " + str(portObj['description']))) return AutoLoadDetails(sub_resources, attributes) pass
def _get_api_session(self, context): try: domain = context.reservation.domain except: domain = 'Global' try: session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=domain) except: session = CloudShellAPISession(host='192.168.85.15', username='******', password='******', domain=domain) return session
def _get_api_from_context(context): """ :param ResourceCommandContext context: :return: cloudshell automation api session :rtype: CloudShellAPISession """ return CloudShellAPISession(host=context.connectivity.server_address, domain=context.reservation.domain, token_id=context.connectivity.admin_auth_token)
def _init_cs_api(self, context): """ :type context ResourceRemoteCommandContext """ return CloudShellAPISession( context.connectivity.server_address, domain="Global", token_id=context.connectivity.admin_auth_token, port=context.connectivity.cloudshell_api_port)
def __get_session(self, context): """ :param ResourceCommandContext context: the context the command runs on """ sess = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) return sess
def create_session_from_cloudshell_config() -> object: test_name = inspect.stack()[1][1] f = path.join(path.dirname(path.dirname(test_name)), 'cloudshell_config.yml') with open(f, 'r') as f: doc = yaml.load(f) username = doc['install']['username'] password = doc['install']['password'] domain = doc['install']['domain'] host = doc['install']['host'] return CloudShellAPISession(host, username, password, domain)
def run(self, resource, cmd): try: csapi = CloudShellAPISession(self._serveraddr, self._adminuser, self._adminpw, self._admindom) out = csapi.ExecuteCommand(self._resid, resource, "Resource", cmd) csapi.Logoff() self._cmdOut = out.Output return self._cmdOut except: raise CSWrapperError("Could not run command")
def _get_api_session(self, context): """ :param ResourceCommandContext context: :return: """ return CloudShellAPISession( context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain)
def get_api_session(): """ A shortcut to get an API session based on the built in env. variables :rtype: CloudShellAPISession """ con_details = get_connectivity_context_details_dict() env_details = get_reservation_context_details_dict() return CloudShellAPISession(con_details['serverAddress'], con_details['adminUser'], con_details['adminPass'], env_details['domain'])
def get_cloudshell_api(server, user, password) -> CloudShellAPISession: try: api = CloudShellAPISession(host=server, username=user, password=password, domain="Global") except Exception as e: print( f"Issue getting cloudshell API session. {type(e).__name__}: {str(e)}" ) raise return api