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 _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 _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 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 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 decrypt_password(self, context): """ A simple example function :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) password = session.DecryptPassword( context.resource.attributes['Password']).Value
def SOAP_getJobResults(self, context, sessionId, jobunitId, Id): # based on https://github.com/hinemos/hinemos/blob/cb0b0c63d16f201e62b7802a50547abd2f5b1225/HinemosClient/src_jobmanagement/com/clustercontrol/jobmanagement/util/JobEndpointWrapper.java r_id = context.reservation.reservation_id HM = data_model.Hinemos.create_from_context(context) csapisession = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) if jobunitId is None: jobunitId = "" if Id is None: Id = "" ip = context.resource.address username = HM.user password = csapisession.DecryptPassword( context.resource.attributes['Hinemos.Password']).Value with CloudShellSessionContext(context) as session: session.WriteMessageToReservationOutput( context.reservation.reservation_id, "Hinemos GetJobResults:") session.WriteMessageToReservationOutput( r_id, "-Inputs: SessionID=" + sessionId + " JobUnitId=" + jobunitId + " Id=" + Id) session.WriteMessageToReservationOutput(r_id, "-Results:") session = Session() session.auth = HTTPBasicAuth(username, password) client = Client("http://" + ip + ":8080/HinemosWS/JobEndpoint?wsdl", transport=Transport(session=session)) JobTreeItem = client.service.getJobDetailList(sessionId) for job in JobTreeItem.children: if jobunitId == "": for job_cmd in job.children: jobunitId = job.data.jobunitId self.printjobresults(context, job, jobunitId, job_cmd.data.id) else: if str(job.data.jobunitId) == jobunitId: if Id == "": for job_cmd in job.children: self.printjobresults(context, job, jobunitId, job_cmd.data.id) else: for job_cmd in job.children: if str(job_cmd.data.id) == Id: self.printjobresults(context, job, jobunitId, Id) pass
def initialize(self, context): """ Initialize the driver session, this function is called everytime a new instance of the driver is created This is a good place to load and cache the driver configuration, initiate sessions etc. :param InitCommandContext context: the context the command runs on """ if not self.fakedata: self.log(str(dir(context))) self.log(str(dir(context.connectivity))) api = CloudShellAPISession(context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, port=context.connectivity.cloudshell_api_port) self.ssh_connect(context.resource.address, 22, context.resource.attributes['User'], api.DecryptPassword(context.resource.attributes['Password']).Value, '>') e = self.ssh_command('enable', '[#:]') if ':' in e: self.ssh_command(api.DecryptPassword(context.resource.attributes['Enable Password']).Value, '# ') self.ssh_command('cli session terminal type dumb', '# ') self.ssh_command('cli session terminal length 999', '# ')
def _connect(self, context): self._log(context, 'GigamonDriver _connect called\r\n') if self.fakedata: return None, None, None 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) ssh, channel, o = self._ssh_connect( context, context.resource.address, 22, context.resource.attributes['User'], api.DecryptPassword(context.resource.attributes['Password']).Value, '>|security purposes') if 'security purposes' in o: raise Exception('Switch password needs to be initialized: %s' % o) e = self._ssh_command(context, ssh, channel, 'enable', '[#:]') if ':' in e: self._ssh_command( context, ssh, channel, api.DecryptPassword( context.resource.attributes['Enable Password']).Value, '[^[#]# ') # self._ssh_command(context, ssh, channel, 'cli session terminal type dumb', '[^[#]# ') self._ssh_command(context, ssh, channel, 'cli session terminal length 999', '[^[#]# ') return ssh, channel, o
def SOAP_runJob(self, context, jobunitId, jobId, jobWM=1, jobWT=1): HM = data_model.Hinemos.create_from_context(context) csapisession = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) ip = context.resource.address username = HM.user password = csapisession.DecryptPassword( context.resource.attributes['Hinemos.Password']).Value #with CloudShellSessionContext(context) as session: #session.WriteMessageToReservationOutput(context.reservation.reservation_id, 'Password found : {}'.format(password)) session = Session() session.auth = HTTPBasicAuth(username, password) client = Client("http://" + ip + ":8080/HinemosWS/JobEndpoint?wsdl", transport=Transport(session=session)) factory = client.type_factory( 'http://jobmanagement.ws.clustercontrol.com') out = factory.outputBasicInfo() trig = factory.jobTriggerInfo() trig.trigger_type = 2 trig.trigger_info = username out.priority = 0 trig.jobCommand = "" trig.jobWaitMinute = jobWM trig.jobWaitTime = jobWT session_id = client.service.runJob(jobunitId, jobId, out, trig) with CloudShellSessionContext(context) as session: session.WriteMessageToReservationOutput( context.reservation.reservation_id, "Hinemos Runjob:") session.WriteMessageToReservationOutput( context.reservation.reservation_id, "-Inputs: JobUnitId=" + jobunitId + " JobId=" + jobId) session.WriteMessageToReservationOutput( context.reservation.reservation_id, '-RunJob Output (Session ID) = {}'.format(session_id)) pass
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 you can return an AutoLoadDetails object :rtype: AutoLoadDetails """ # See below some example code demonstrating how to return the resource structure and attributes # In real life, this code will be preceded by SNMP/other calls to the resource details and will not be static # run 'shellfoundry generate' in order to create classes that represent your data model self._logger = self._get_logger(context) resource = LinuxServerShell.create_from_context(context) session = CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain='Global') 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 if_table in snmp_service.get_table('IF-MIB', 'ifTable').values(): port = ResourcePort(if_table['ifDescr']) port.model_name = if_table['ifType'] port.mac_address = if_table['ifPhysAddress'] port.port_speed = if_table['ifSpeed'] for ip_table in snmp_service.get_table('IP-MIB', 'ipAddrTable').values(): if ip_table['ipAdEntIfIndex'] == if_table['ifIndex']: port.ipv4_address = ip_table['ipAdEntAddr'] resource.add_sub_resource(if_table['ifIndex'], port) autoload_details = resource.create_autoload_details() self._logger.info( 'autoload attributes: ' + ','.join([str(vars(x)) for x in autoload_details.attributes])) self._logger.info( 'autoload resources: ' + ','.join([str(vars(x)) for x in autoload_details.resources])) return autoload_details
def email_ga_user_report_to_contact(self, context, start_date, end_date, cloudshell_username, email_address, email_title): """ :type context ResourceCommandContext :param context: :param test_name: :return: """ api = CloudShellAPISession( host=context.connectivity.server_address, port=context.connectivity.cloudshell_api_port, token_id=context.connectivity.admin_auth_token, domain="Global") admin_email = api.GetUserDetails("admin").Email smtp_resource = api.FindResources('Mail Server', 'SMTP Server').Resources[0] smtp_resource_details = api.GetResourceDetails(smtp_resource.Name) smtp_attributes = { attribute.Name: attribute.Value if attribute.Type != "Password" else api.DecryptPassword(attribute.Value).Value for attribute in smtp_resource_details.ResourceAttributes } smtp_client = SMTPClient(smtp_attributes["User"], smtp_attributes["Password"], smtp_resource_details.Address, smtp_attributes["Port"]) report_content = self.generate_ga_user_report(context, start_date, end_date, cloudshell_username) if report_content: current_timestamp = datetime.datetime.strftime( datetime.datetime.now(), "%m-%d_%H-%M") filename = "GA_Report_" + current_timestamp + ".csv" with open(filename, 'w') as csv_file: csv_file.write(report_content) smtp_client.send_email(",".join([email_address, admin_email]), email_title, "See attached user activity report", False, [filename]) return "User activity report emailed successfully" else: smtp_client.send_email( ",".join([email_address, admin_email]), email_title, "No activity reported to date for this user", False)
def _decrypt_resource_passwords(self, context, resource): """ :param context: :param resource: SentryPdu resource object with encrypted passwords :type resource: SentryPdu :return: the resource object with the passwords decrypted :rtype : SentryPdu """ logger = LogHelper.get_logger(context) try: domain = context.reservation.domain except: domain = 'Global' logger.info("Creating API Session") api = CloudShellAPISession( context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, port=context.connectivity.cloudshell_api_port, domain=domain) attributes_to_decrypt = ('snmp_write_community', 'snmp_read_community', 'snmp_v3_password', 'snmp_v3_private_key', 'password') for pass_attribute in attributes_to_decrypt: logger.info("Attempting decryption of password value at {}".format( pass_attribute)) value = getattr(resource, pass_attribute) if value is None: # logger.info(" Skipping Decryption of {}: Value is None".format(pass_attribute)) continue elif value.endswith('=='): # logger.info(" Decrypting {}: Detected encrypted value {}".format(pass_attribute, value)) setattr(resource, pass_attribute, api.DecryptPassword(value).Value) # logger.info(" Got: {}".format(getattr(resource, pass_attribute))) continue else: # logger.info(" Skipping Decryption of {}: Unable to determine type for: {}".format(pass_attribute, value)) pass return resource
company = global_inputs["Company Name"] phone = global_inputs["Phone number"] owner_email = global_inputs["Quali Owner"] new_username = email api = CloudShellAPISession(host=connectivityContext["serverAddress"], token_id=connectivityContext["adminAuthToken"], domain=reservationContext["domain"]) # Get SMTP Details from Resource smtp_resource = api.FindResources('Mail Server', 'SMTP Server').Resources[0] smtp_resource_details = api.GetResourceDetails(smtp_resource.Name) smtp_attributes = { attribute.Name: attribute.Value if attribute.Type != "Password" else api.DecryptPassword(attribute.Value).Value for attribute in smtp_resource_details.ResourceAttributes } smtp_client = SMTPClient(smtp_attributes["User"], smtp_attributes["Password"], smtp_resource_details.Address, smtp_attributes["Port"], "*****@*****.**") admin_email = api.GetUserDetails("admin").Email # Create Domain api.WriteMessageToReservationOutput(reservationContext["id"], "Creating New Domain") domain_name = '.'.join(new_username.split('.')[:-1]).replace('@', '-') if domain_name in [ domain.Name for domain in api.GetResourceDetails("AWS us-east-1", True).Domains
class GenericResourceDriver(ResourceDriverInterface): class UnImplementedCliConnectionType(Exception): pass class UnSupportedCliConnectionType(Exception): pass def cleanup(self): """ Destroy the driver session, this function is called everytime a driver instance is destroyed This is a good place to close any open sessions, finish writing to log files """ pass def __init__(self): self.address = None self.cli = None self.cli_connection_type = None self.cli_prompt_regex = None self.cli_session = None self.cs_session = None self.mode = None self.password_hash = None self.session_types = None self.user = None def initialize(self, context): self.cli = CLI() def get_inventory(self, context): self.run_command(context, 'hostname') return AutoLoadDetails() def run_command(self, context, command): logger = LogHelper.get_logger(context) self._cli_session_handler(context) with self.cli.get_session(self.session_types, self.mode, logger) as default_session: output = default_session.send_command(command) return sub(self.cli_prompt_regex, '', output) def _cs_session_handler(self, context): self.address = context.resource.address self.user = context.resource.attributes['User'] self.password_hash = context.resource.attributes['Password'] domain = None try: domain = context.reservation.domain except AttributeError: domain = 'Global' self.cs_session = CloudShellAPISession(host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=domain) def _cli_session_handler(self, context): self._cs_session_handler(context) logger = LogHelper.get_logger(context) self.cli_connection_type = context.resource.attributes['CLI Connection Type'] self.cli_prompt_regex = context.resource.attributes['CLI Prompt Regular Expression'] self.mode = CommandMode(self.cli_prompt_regex) self.session_types = None logger.info('CLI Connection Type: "%s"' % self.cli_connection_type) logger.info('CLI Prompt Regular Expression: "%s"' % self.cli_prompt_regex) if self.cli_connection_type == 'Auto': self.session_types = [SSHSession(host=self.address, username=self.user, password=self.cs_session.DecryptPassword(self.password_hash).Value), TelnetSession(host=self.address, username=self.user, password=self.cs_session.DecryptPassword(self.password_hash).Value)] elif self.cli_connection_type == 'Console': message = 'Unimplemented CLI Connection Type: "%s"' % self.cli_connection_type logger.error(message) raise GenericResourceDriver.UnImplementedCliConnectionType(message) elif self.cli_connection_type == 'SSH': self.session_types = [SSHSession(host=self.address, username=self.user, password=self.cs_session.DecryptPassword(self.password_hash).Value)] elif self.cli_connection_type == 'TCP': message = 'Unimplemented CLI Connection Type: "%s"' % self.cli_connection_type logger.error(message) raise GenericResourceDriver.UnImplementedCliConnectionType(message) elif self.cli_connection_type == 'Telnet': self.session_types = [TelnetSession(host=self.address, username=self.user, password=self.cs_session.DecryptPassword(self.password_hash).Value)] else: message = 'Unsupported CLI Connection Type: "%s"' % self.cli_connection_type logger.error(message) raise GenericResourceDriver.UnSupportedCliConnectionType(message)
# vnet =[attr.Value for attr in azcp.ResourceAttributes if attr.Name == ''][0] vnet = 'CloudShell-Sandbox-VNet' # vm_name = 'apache-web-server-9883d10f' azcp = session.GetResourceDetails(azure_cp_name) clp = CloudProvider( azure_application_id=[attr.Value for attr in azcp.ResourceAttributes if attr.Name == 'Azure Application ID'][0], azure_subscription_id=[attr.Value for attr in azcp.ResourceAttributes if attr.Name == 'Azure Subscription ID'][ 0], azure_tenant=[attr.Value for attr in azcp.ResourceAttributes if attr.Name == 'Azure Tenant ID'][0], azure_application_key=session.DecryptPassword( [attr.Value for attr in azcp.ResourceAttributes if attr.Name == 'Azure Application Key'][0]).Value, ) clients = AzureClientsManager(cloud_provider=clp) # my actual code: all_subnets = clients.network_client.subnets.list( resource_group_name='Quali-Dev', virtual_network_name='CloudShell-Sandbox-VNet' ) import time resource_group = '' done = False count = 0 condemed_subnets = [] while done == False and count < 40: count = count + 1
global_inputs = {in_param["parameterName"]:in_param["value"] for in_param in reservationContext["parameters"]["globalInputs"]} first_name = global_inputs["First Name"] last_name = global_inputs["Last Name"] email = global_inputs["email"].lower() company = global_inputs["Company Name"] phone = global_inputs["Phone number"] owner_email = global_inputs["Quali Owner"] new_username = email api = CloudShellAPISession(host=connectivityContext["serverAddress"], token_id=connectivityContext["adminAuthToken"], domain=reservationContext["domain"]) # Get SMTP Details from Resource smtp_resource = api.FindResources('Mail Server', 'SMTP Server').Resources[0] smtp_resource_details = api.GetResourceDetails(smtp_resource.Name) smtp_attributes = {attribute.Name: attribute.Value if attribute.Type != "Password" else api.DecryptPassword(attribute.Value).Value for attribute in smtp_resource_details.ResourceAttributes} smtp_client = SMTPClient(smtp_attributes["User"], smtp_attributes["Password"], smtp_resource_details.Address, smtp_attributes["Port"], "*****@*****.**") admin_email = api.GetUserDetails("admin").Email # Create Domain api.WriteMessageToReservationOutput(reservationContext["id"], "1. Creating New Domain") domain_name = '.'.join(new_username.split('.')[:-1]).replace('@', '-') if domain_name in [domain.Name for domain in api.GetResourceDetails("AWS us-east-1", True).Domains]: id_suffix = 1 while domain_name + str(id_suffix) in [domain.Name for domain in api.GetResourceDetails("AWS us-east-1", True).Domains]: id_suffix += 1 domain_name = domain_name + str(id_suffix) api.WriteMessageToReservationOutput(reservationContext["id"], "The requested domain already exists, appending {} to new domain name, please contact system admin at [email protected]".format(id_suffix)) api.AddNewDomain(domainName=domain_name, description="Domain for {0} {1}'s Trial".format(first_name, last_name)) else:
from cloudshell.api.cloudshell_api import CloudShellAPISession user = "******" password = "******" server = "localhost" domain = "Global" api = CloudShellAPISession(host=server, username=user, password=password, domain=domain) MY_STRONG_PASSWORD = "******" # setting the password api.SetAttributeValue(resourceFullPath="mock1", attributeName="Putshell.Password", attributeValue=MY_STRONG_PASSWORD) # getting the encrypted password string from the resource encrypted_password_val = api.GetAttributeValue( resourceFullPath="mock1", attributeName="Putshell.Password").Value print("encrypted: " + encrypted_password_val) # to decrypt use api decrypted = api.DecryptPassword(encryptedString=encrypted_password_val).Value print("decrypted: " + decrypted)
def vmx_orch_hook_during_provisioning(self, context): logger = get_qs_logger(log_group=context.reservation.reservation_id, log_file_prefix='vMX') logger.info('deploy called') api = CloudShellAPISession(host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) resid = context.reservation.reservation_id vmxtemplate_resource = context.resource.name logger.info('context attrs: ' + str(context.resource.attributes)) vmxuser = context.resource.attributes['User'] vmxpassword = api.DecryptPassword(context.resource.attributes['Password']).Value vcp_app_template_name = context.resource.attributes['Chassis App'] vfp_app_template_name_template = context.resource.attributes['Module App'] internal_vlan_service_name = context.resource.attributes['Internal Network Service'] or 'VLAN Auto' vlantype = context.resource.attributes.get('Vlan Type') or 'VLAN' ncards = int(context.resource.attributes.get('Number of modules', '1')) router_family = context.resource.attributes['Deployed Resource Family'] router_model = context.resource.attributes['Deployed Resource Model'] router_driver = context.resource.attributes['Deployed Resource Driver'] chassis_deployed_model_name = context.resource.attributes['Controller App Resource Model'] card_deployed_model_name = context.resource.attributes['Card App Resource Model'] requested_vmx_ip = context.resource.attributes.get('Management IP', 'dhcp') username = context.resource.attributes.get('User', 'user') userpassword = api.DecryptPassword(context.resource.attributes.get('Password', '')).Value rootpassword = userpassword userfullname = context.resource.attributes.get('User Full Name', username) missing = [] for a in ['Chassis App', 'Module App', 'Deployed Resource Family', 'Deployed Resource Model']: if a not in context.resource.attributes: missing.append(a) if missing: raise Exception('Template resource missing values for attributes: %s' % ', '.join(missing)) if '%d' not in vfp_app_template_name_template: vfp_app_template_name_template += '%d' px, py = get_resource_position(api, resid, vmxtemplate_resource) vmx_resource = vmxtemplate_resource.replace('Template ', '').replace('Template', '') + '_' + str(randint(1, 10000)) fakel2name = '%s L2' % vmx_resource todeploy = [ (vcp_app_template_name, '%s_vcp' % vmx_resource, px, py + 100) ] + [ (vfp_app_template_name_template % i, '%s_vfp%d' % (vmx_resource, i), px, py+100+100+100*i) for i in range(ncards) ] for _ in range(5): with Mutex(api, resid, logger): for template, alias, x, y in todeploy: add_app(api, resid, template, alias, x, y) app_aliases = [alias for template, alias, x, y in todeploy] api.DeployAppToCloudProviderBulk(resid, app_aliases) with Mutex(api, resid, logger): logger.info('original app aliases = %s' % str(app_aliases)) vmname2details = get_details_of_deployed_app_resources(api, resid, app_aliases) deployed_vcp = sorted([x for x in vmname2details if 'vcp' in x]) deployed_vfp = sorted([x for x in vmname2details if 'vfp' in x]) deployed = deployed_vcp + deployed_vfp logger.info('deployed apps = %s' % str(deployed)) vmxip, mac2nicname, netid50, cpname = post_creation_vm_setup(api, resid, deployed, deployed_vcp, deployed_vfp, internal_vlan_service_name, requested_vmx_ip, rootpassword, userfullname, username, userpassword, vmname2details, vmx_resource, logger) if not vmxip: raise Exception('VCP did not receive an IP (requested %s)' % (requested_vmx_ip)) if not wait_for_ssh_up(api, resid, vmxip, vmxuser, vmxpassword, logger): raise Exception('VCP not reachable via SSH within 5 minutes at IP %s -- check management network' % vmxip) if ssh_wait_for_ge_interfaces(api, resid, vmxip, vmxpassword, ncards, logger): logger.info('All expected ge- interfaces found') break msg = '%d card(s) not discovered within 3 minutes - recreating VMs' % ncards logger.info(msg) api.WriteMessageToReservationOutput(resid, msg) api.DeleteResources(deployed) sleep(10) else: raise Exception('%d cards were not discovered after 10 minutes in 5 attempts' % ncards) for kj in deployed_vfp: api.UpdateResourceAddress(kj, kj) api.CreateResource(router_family, router_model, vmx_resource, vmxip) api.AddResourcesToReservation(resid, [vmx_resource]) api.SetReservationResourcePosition(resid, vmxtemplate_resource, px, py-50) api.SetReservationResourcePosition(resid, vmx_resource, px, py) if router_driver: api.UpdateResourceDriver(vmx_resource, router_driver) try: api.RemoveServicesFromReservation(resid, [vmx_resource + ' vMX resource cleanup']) except: pass api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' vMX resource cleanup', [ AttributeNameValue('Resources to Delete', ','.join([ vmx_resource, ])), ]) copy_resource_attributes(api, vmxtemplate_resource, vmx_resource) for _ in range(5): logger.info('Running autoload...') try: api.AutoLoad(vmx_resource) children_flat = get_all_child_resources(api, vmx_resource) ge_children_flat = {a: b for a, b in children_flat.iteritems() if '/' in a and '-' in a.split('/')[-1]} foundcards2ports = defaultdict(list) for fullpath, attrs in ge_children_flat.iteritems(): foundcards2ports[attrs['ResourceBasename'].split('-')[1]].append(attrs['ResourceBasename']) if len(foundcards2ports) >= ncards: logger.info('Autoload found ports: %s' % (foundcards2ports)) break logger.info('Autoload did not find all cards (%d) or ports per card (10). Retrying in 10 seconds. Found: %s' % (ncards, foundcards2ports)) sleep(10) except Exception as ek: logger.info('Autoload error: %s. Retrying in 30 seconds.' % str(ek)) sleep(30) else: raise Exception('Autoload did not discover all expected ports - unhandled vMX failure') post_autoload_cleanup(api, resid, deployed_vfp, vmname2details, netid50, logger) vfpcardidstr2deployedapp3 = {vfpname.split('_')[2].replace('vfp', '').split('-')[0]: vfpname for vfpname in deployed_vfp} def vm_from_ge_port(portname): if '/' in portname: portname = portname.split('/')[-1] return vfpcardidstr2deployedapp3[portname.split('-')[1]] logger.info('vfpcardidstr2deployedapp = %s' % str(vfpcardidstr2deployedapp3)) autoloadport2vmname_nicname = {} for ch, attrs in ge_children_flat.iteritems(): for attr, val in attrs.iteritems(): if 'mac' in attr.lower() and 'address' in attr.lower(): autoloadport2vmname_nicname[ch] = (vm_from_ge_port(ch), mac2nicname.get(val, attrs['ResourceBasename'].split('-')[-1])) create_fake_L2(api, fakel2name, vlantype, autoloadport2vmname_nicname) try: api.RemoveServicesFromReservation(resid, [vmx_resource + ' L2 cleanup']) except: pass api.AddServiceToReservation(resid, 'VNF Cleanup Service', vmx_resource + ' L2 cleanup', [ AttributeNameValue('Resources to Delete', ','.join([ fakel2name, ])), ]) logger.info('deployed_vcp=%s deployed_vfp=%s deployed=%s' % (deployed_vcp, deployed_vfp, deployed)) with Mutex(api, resid, logger): basename2fullpath = {fullpath.split('/')[-1]: fullpath for fullpath in autoloadport2vmname_nicname} def mapfunc(oldpath): basename = oldpath.split('/')[-1] return basename2fullpath[basename] move_connectors_of(api, resid, vmxtemplate_resource, mapfunc, logger) api.RemoveResourcesFromReservation(resid, [vmxtemplate_resource]) logger.info('SUCCESS deploying vMX %s' % vmx_resource)
nwcf4sCD609ij7GlxGgLMJR04l6Deb5BfZm91QUJeQY+vhYdaNI10FtIs4Y2jtwf jwEctWSe7eHYUwiE7cORIAlwV4PqCbbQjSiOyikQaZ6cxNoQWGUV740WJIRfX1bd WkHwRJ+BAoGBAPboVfCfp3gO8JPUP5ut5KLZx6GfinKBJrYW7YEc6nPXJlryp2K8 g0QW+se3JkCLJyimUCKRRvPCxQqiKdDe4LS00n2zOVSsq7uehNLBMdVTvw9Q/1oa GjKk39l3DsvZpnO7wfOgderChXlxWVopUj/nroIN0VNY5uX/HdBfhkWhAoGBAPZa 6fTu4Qwk0es/i3yxT4ruezFeZpwPgK4PDM38na2jQAGs91ncG78tQheezYlGJhb+ /9gwvzcraQ/e+5PCtWa2IyDm+PYonDEMtFBLzXhAHwGJMCIPIiKai2vd8LDqw1cg zh+Eg1ik4IH0Yfl5SC76Xb3gi1g/W+8TyVN7Xi59AoGATeCEUswYp16W9RmqInFb vx3PwKOwqGMiEabzrJixPm5rE56buyHYiV5yJRIYh50ccc7bUbve1D3npm31oILb /0NVbP5do95+oEPkgxEapb2vcqZKlGHNR5IHZPEPgq6YuMJM74n6B1zpep+M3kpQ PgXWXgD7uD0/PuYTwkiO8mECgYBi9M/ncBD8BMpBmcvY8YxG/VaE1SuYYm3I/Qii sWdQ+TNbuPO+p7iJiY9z13kuO/xO3m08lRAqBAj2tBYQG3UsZdske0Lj9hoPZdAE NP66397UihvIgpWumq+IS6VEG3kNxYKmjF8KO2hnKxgz0rDZFf6Tp9+xOfoexa7o FrUVLQKBgQCLjEJ1iwGEAqqB9AXNcYOyDpWekj+24/6IkrjLZeFuk416d0kGMeE/ 8OJB0iITna1tJUEYbzXLB4biiNVxx8djwK9XIaNr3CjarrM1h3YWtvZmsvzIHSJo +OPNKKHu0xOOTVKrad2XjyNZraU3VvogPxISyqBvxp1lR0yzHdjH4g== -----END RSA PRIVATE KEY-----''' session.SetAttributeValue(resourceFullPath='Ansible-dev-server-vm', attributeName='{}.Password'.format( res_det.ResourceModelName), attributeValue=pvt_key) password = [ attr for attr in res_det.ResourceAttributes if attr.Name == '{}.Password'.format(res_det.ResourceModelName) ][0].Value dec_pass = session.DecryptPassword(password).Value print dec_pass pass session.Service()
class LogCollector(): def __init__(self, context, reservation_id=None): """ :param ResourceCommandContext context: """ self.api = CloudShellAPISession( context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain='Global') self.model_name = context.resource.model self.windows_user = context.resource.attributes[ "{}.Windows User".format(self.model_name)] self.windows_password = context.resource.attributes[ "{}.Windows Password".format(self.model_name)] try: self.windows_password = self.api.DecryptPassword( self.windows_password).Value except: pass self.windows_es = [ x.lstrip().strip() for x in context.resource.attributes[ "{}.Windows ES List".format(self.model_name)].split(",") ] self.linux_user = context.resource.attributes["{}.Linux User".format( self.model_name)] self.linux_password = context.resource.attributes[ "{}.Linux Password".format(self.model_name)] try: self.linux_password = self.api.DecryptPassword( self.linux_password).Value except: pass self.linux_es = [ x.lstrip().strip() for x in context.resource.attributes[ "{}.Linux ES List".format(self.model_name)].split(",") ] self.res_id = reservation_id if reservation_id else context.reservation.reservation_id self.scp_client = LinuxConnection() self.winrm = WindowsConnection() self.temp_folder = "" self.zip_file_name = "" self.linux_log_location = context.resource.attributes[ "{}.Linux Log Location".format(self.model_name)] self.windows_log_location = context.resource.attributes[ "{}.Windows Log Location".format(self.model_name)] self.smtp_server = context.resource.attributes["{}.SMTP Server".format( self.model_name)] self.smtp_port = context.resource.attributes["{}.SMTP Port".format( self.model_name)] self.smtp_tls = context.resource.attributes["{}.SMTP TLS".format( self.model_name)] self.smtp_username = context.resource.attributes[ "{}.SMTP Username".format(self.model_name)] self.smtp_password = context.resource.attributes[ "{}.SMTP Password".format(self.model_name)] try: self.smtp_password = self.api.DecryptPassword( self.smtp_password).Value except: pass self.smtp_from = context.resource.attributes[ "{}.SMTP From Name".format(self.model_name)] self.context = context self._preapre_env() def _preapre_env(self): self.temp_folder = tempfile.mkdtemp(self.res_id) def clean_env(self): shutil.rmtree(self.temp_folder) def get_linux_logs(self): for linux_es in self.linux_es: self.scp_client.connect(linux_es, self.linux_user, self.linux_password, 5) output = self.scp_client.run_command( "ls {}".format(self.linux_log_location), "$") if self.res_id in output: print "Found res id folder in es {}".format(linux_es) self.scp_client.download_file( "{}/{}/lib/".format(self.linux_log_location, self.res_id), self.temp_folder + "/{}".format(linux_es)) else: print "unable to find {} in es {}".format( self.res_id, linux_es) # raise Exception(output) def get_windows_logs(self): for windows_es in self.windows_es: self.winrm.connect(windows_es, self.windows_user, self.windows_password, 10) status, output, err = self.winrm.run_command("dir {}".format( self.windows_log_location)) if self.res_id in output: print "Found res id folder in es {}".format(windows_es) self.winrm.download_file( "{}\\{}".format(self.windows_log_location, self.res_id), self.temp_folder + "/{}".format(windows_es)) else: print "unable to find {} in es {}".format( self.res_id, windows_es) # raise Exception(output) def zip_logs(self): self.zip_file_name = "{}\\{}-LOGS.zip".format(self.temp_folder, self.res_id) self.zip_file = zipfile.ZipFile(self.zip_file_name, "w", zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(self.temp_folder): for fil in files: if fil == self.zip_file_name.split("\\")[-1]: continue self.zip_file.write( os.path.join(root, fil), os.path.join(root, fil).split(self.res_id)[-1]) self.zip_file.close() def upload_to_cs(self): api_base_url = "http://{}:9000/Api".format( self.context.connectivity.server_address) login_result = requests.put( api_base_url + "/Auth/Login", { "token": self.context.connectivity.admin_auth_token, "domain": "Global" }) authcode = "Basic " + login_result._content[1:-1] attached_file = open(self.zip_file_name, "rb") attach_file_result = requests.post( api_base_url + "/Package/AttachFileToReservation", headers={"Authorization": authcode}, data={ "reservationId": self.res_id, "saveFileAs": self.zip_file_name.split("\\")[-1], "overwriteIfExists": "True" }, files={'QualiPackage': attached_file}) def email_logs(self, to): email = SMTP() email.send_email(self.smtp_username, self.smtp_password, self.smtp_server, self.smtp_port, self.smtp_from, to, "Logs for Sandbox: {}".format(self.res_id), self.smtp_tls, "Logs", False, False, self.zip_file_name) def get_byte_logs(self): import base64 with open(self.zip_file_name, "rb") as fl: out = base64.b64encode(fl.read()) return out
from cloudshell.api.cloudshell_api import CloudShellAPISession api = CloudShellAPISession(host="localhost", username="******", password="******", domain="Global") attrs = api.GetResourceDetails("TP-ASR907-03").ResourceAttributes pw = [x.Value for x in attrs if x.Name.endswith("Password")] decrypted = api.DecryptPassword(pw[0]).Value print(decrypted)