def Update_server_ip(server_ip,user="******",password="******",domain="Global"): print "the selected server is on " + server_ip global session session = api.CloudShellAPISession(server_ip, user, password, domain) global quali_api_s quali_api_s = quali_api.QualiAPISession(server_ip, "admin", "admin") return
def create_HTML(self): session = api.CloudShellAPISession( host=connectivity_details['serverAddress'], token_id=connectivity_details['adminAuthToken'], domain=reservation_details['domain']) all_resources = session.GetReservationDetails( reservation_details['id']).ReservationDescription.Resources res_end_time = session.GetReservationDetails( reservation_details['id']).ReservationDescription.EndTime for a_resource in all_resources: if a_resource.ResourceModelName == 'vRouter Virtual Machine': router_ip = a_resource.FullAddress subject = 'R00tCamp POD - Reservation ID {0}'.format( reservation_details['id']) html_message = ''' <html> <head></head> <body> <h1>R00TCAMP REMOTE ACCESS DETAILS</h1> <h3>Reservation will end in ''' + res_end_time + '''</h3> <h2>SUT Details: </h2> <p>No Machine -> ''' + router_ip + ''' : 9003</p> <p>SSH -> ''' + router_ip + ''': 9002</p> <h2>KALI Details: </h2> <p>No Machine -> ''' + router_ip + ''' : 9001 </p> <p>SSH -> ''' + router_ip + ''' : 9000 </p> <h2>Win7 Details: </h2> <p>No Machine -> ''' + router_ip + ''' : 9004 </p> <p>to access your reservation , <a href="https://qs.cisco.com/RM/Diagram/Index/''' + reservation_details[ 'id'] + '''">click here</a></p> </body> </html> ''' return subject, html_message
def __init__(self, context): self.session = cs_api.CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain="Global") self.context = context self.logger = LogHelper.get_logger(context) self.address = self.context.resource.address self.community_read = self.session.DecryptPassword( get_attribute_by_name( context=self.context, attribute_name='SNMP Read Community')).Value or 'public' self.community_write = self.session.DecryptPassword( get_attribute_by_name( context=self.context, attribute_name='SNMP Write Community')).Value or 'private' self.password = get_attribute_by_name( context=self.context, attribute_name='SNMP Password') or '', self.user = get_attribute_by_name(context=self.context, attribute_name='SNMP User') or '', self.version = get_attribute_by_name(context=self.context, attribute_name='SNMP Version') self.private_key = get_attribute_by_name( context=self.context, attribute_name='SNMP Private Key')
def __init__(self): """ :rtype: object :param self: :return: """ # set the config file path & load the json file cwd = os.getcwd() self.json_file_path = '%s/config.json' % cwd self.configs = json.loads(open(self.json_file_path).read()) # set logging file path self.logfilename = self.configs['log_file_path'] self.loglevel = self.configs['log_level'].upper() # set logging logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', filename=self.logfilename, level=LOG_DICT[self.loglevel]) # set the default password for new user self.default_password = self.configs['new_user_default_password'] # start CloudShell API Session self.cs_session = cs_api.CloudShellAPISession( self.configs["qs_server_hostname"], self.configs["qs_admin_username"], base64.b64decode(self.configs["qs_admin_password"]), domain="Global")
def change_app_input_value(self, AppName, attr_name, attr_value, context): """ :type context: drivercontext.ResourceCommandContext """ edit_list = [] session = api.CloudShellAPISession( context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain) Appdetails = session.GetAppsDetailsInReservation( context.reservation.reservation_id, [AppName]) DeployModel = Appdetails.Apps[0].DeploymentPaths[ 0].DeploymentService.Model AppModel = Appdetails.Apps[0].LogicalResource.Model session.WriteMessageToReservationOutput( context.reservation.reservation_id, DeployModel) edit_vals = api.ApiEditAppRequest( AppName, AppName, '', api.AppDetails(ModelName=AppModel, Attributes=[], Driver=''), api.DefaultDeployment( DeployModel, api.Deployment([api.NameValuePair(attr_name, attr_value)]), Installation=None)) edit_list.append(edit_vals) qq = session.EditAppsInReservation( reservationId=context.reservation.reservation_id, editAppsRequests=edit_list) session.RemoveResourcesFromReservation() return qq
def Update_server_ip(server_ip, user="******", password="******", domain="Global"): global session session = api.CloudShellAPISession(server_ip, user, password, domain) return
def Power_Physical_Devices(): # AppName = os.environ['App_Name'] # attr_name = os.environ['Attribute_Name'] # attr_value = os.environ['New_Image_Name'] # auto_deploy = os.environ['Auto_deploy'] # session = api.CloudShellAPISession(host=connectivity_details['serverAddress'], # token_id=connectivity_details['adminAuthToken'], # domain=reservation_details['domain']) physical_resources = [] session = api.CloudShellAPISession('qs.cisco.com', 'admin', 'admin', 'Global') qq = session.GetReservationDetails( reservationId='9fd08e7c-e35e-4027-8531-b394731890a7') for res in qq.ReservationDescription.Resources: res_det = session.GetResourceDetails(res.Name) for child in res_det.ChildResources: if child.ResourceFamilyName == 'Power Port': physical_resources.append(res.Name) if physical_resources: for phys_res in physical_resources: session.ExecuteResourceConnectedCommand( reservationId='', resourceFullPath=phys_res.Name, commandName='', commandName='power', ) pass
def __init__(self): # credentials username = '******' password = '******' server = 'localhost' domain = 'Global' # create CS API session self.session = api.CloudShellAPISession(host=server, username=username, password=password, domain=domain)
def _start_cloudshell_session(self): try: return cs_api.CloudShellAPISession( self.configs['cs_host'], username=self.configs['cs_user'], password=b64decode(self.configs['cs_pwrd']), domain=self.configs['cs_domain']) except CloudShellAPIError as e: print 'Unable to Connect to CloudShell!' print ' {}'.format(e.message) return None
def run_test(self, ip, sandboxId): session = cs_api.CloudShellAPISession(ip, 'admin', 'admin', 'Global') resourceDict = {} for resource in session.GetReservationDetails( reservationId=sandboxId).ReservationDescription.Resources: attributeDict = {} for attribute in session.GetResourceDetails( resource.Name).ResourceAttributes: attributeDict[attribute.Name] = attribute.Value resourceDict[resource.Name] = attributeDict return resourceDict
def get_cloudshell_session(credentialsFilePath = 'creds.json'): jsonfile = open(credentialsFilePath, 'r') credentials = json.load(jsonfile) jsonfile.close() serverAddress = credentials.get('cloudshell login details').get('server address') domain = credentials.get('cloudshell login details').get('domain') username = credentials.get('cloudshell login details').get('user') password = credentials.get('cloudshell login details').get('password') session = api.CloudShellAPISession(host = serverAddress,username = username, password = password, domain= domain) return session
def get_cs_api_session(): username = '******' password = '******' server = 'localhost' domain = 'Global' session = api.CloudShellAPISession(username=username, password=password, domain=domain, host=server) return session
def Terminals_wipe(): session = api.CloudShellAPISession( host=connectivity_details['serverAddress'], token_id=connectivity_details['adminAuthToken'], domain=reservation_details['domain']) session.WriteMessageToReservationOutput(reservation_details['id'], 'Logged On') reservation_details_data = session.GetReservationDetails( reservation_details['id']).ReservationDescription.Resources if reservation_details_data.__len__() < 1: raise Exception("no resources detected") else: for resource in reservation_details_data: for attr in attribute_names: at_n_v = '' try: at_n_v = session.GetAttributeValue( resourceFullPath=resource.Name, attributeName=attr) # session.WriteMessageToReservationOutput(reservation_details['id'], at_n_v.Name) # session.WriteMessageToReservationOutput(reservation_details['id'], at_n_v.Value) except: pass try: session.SetAttributeValue(resourceFullPath=resource.Name, attributeName=at_n_v.Name, attributeValue='') session.WriteMessageToReservationOutput( reservation_details['id'], 'attribute {0} on resource {1} has been wiped.\n'. format(attr, resource.Name)) except Exception as e: if e.message == 'Error updating attribute value': try: session.SetAttributeValue( resourceFullPath=resource.Name, attributeName=at_n_v.Name, attributeValue='-1') session.WriteMessageToReservationOutput( reservation_details['id'], 'attribute {0} on resource {1} has been wiped.\n' .format(attr, resource.Name)) except: pass elif e.message == '\'str\' object has no attribute \'Name\'': session.WriteMessageToReservationOutput( reservation_details['id'], 'There is no attribute {0} on resource {1}.\n'. format(attr, resource.Name)) else: session.WriteMessageToReservationOutput( reservation_details['id'], 'can not change attribute {0} on resource {1}. reason {2}\n' .format(attr, resource.Name, e.message))
def establish_cs_session(): from credentials import credentials import cloudshell.api.cloudshell_api as cs_api try: ses = cs_api.CloudShellAPISession(host=credentials["server"], username=credentials["user"], password=credentials["password"], domain=credentials["domain"]) except Exception as e: print(error_red("[-] ERROR ESTABLISHING CS_API SESSION. CHECK CREDENTIALS AND CONNECTIVITY.\n" + str(e))) exit(1) else: return ses
def executePlaybookScript(self): # AppName = os.environ['App_Name'] session = api.CloudShellAPISession(host=connectivity_details['serverAddress'], token_id=connectivity_details['adminAuthToken'], domain=reservation_details.domain) reservation_details_data = session.GetReservationDetails(reservation_details.id).ReservationDescription JsonDetails = self._sort_out_json(template_json, session) session.WriteMessageToReservationOutput(reservation_details.id, JsonDetails) self._run_ansible_playbook(session, reservation_details.id, JsonDetails, scripthelpers.get_resource_context_details().name) return None
def start_cloudshell_api(self, context): """ :param ResourceCommandContext context: :return: """ if not self.cs_session: try: self.cs_session = cs_api.CloudShellAPISession(context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain=context.reservation.domain ) except CloudShellAPIError as e: print e.message
def showPoolInfo(self, context): server = context.resource.address user = context.resource.attributes.get('User') db = context.resource.attributes.get('database') encryptedPassword = context.resource.attributes.get('Password') csssesion = api.CloudShellAPISession('localhost', 'admin', 'admin', 'Global') password = csssesion.DecryptPassword(encryptedPassword).Value sqlinfo = sqlinfodata(server, user, password, db) conn = pymssql.connect(sqlinfo.server, sqlinfo.user, sqlinfo.password) cursor = conn.cursor() inst = GetVlanPoolTable() items = inst._getpoolstatus(cursor, sqlinfo.database) result = inst._buildHtmlString(items) csssesion.UpdateReservationDescription(context.reservation.reservation_id ,result) return result
def load_to_cs(): switch_debug_to_false() zip_files() ses = cs_api.CloudShellAPISession(host=server_host, username=user_name, password=password, domain=domain) try: ses.UpdateScript(script_name, zip_address) except Exception as e: print(str(e) + "\nPLEASE LOAD SCRIPT MANUALLY THE FIRST TIME") pass else: print(" '{script}' uploaded to CloudShell".format(script=script_name))
def open_session(self): """ :return: """ cs_session = None try: cs_session = cs_api.CloudShellAPISession(b64decode(self.config['host']), b64decode(self.config['user']), b64decode(self.config['pwrd']), domain='Global', port=str(self.config['port']) ) except CloudShellAPIError as err: logging.critical(err.message) return cs_session
def open_cs_session(self): # connect to CloudShell try: return cs_api.CloudShellAPISession(self.cs_host, username=self.cs_username, password=self.cs_password, domain=self.cs_domain, port=int(self.cs_port)) except CloudShellAPIError as err: print err.message logging.critical('Unable to open CloudShell API session: %s' % err.message) return None except StandardError as err: print err.message logging.critical( 'General Error on CloudShell API Session Start\n>> Check Configuration \n>> Msg: %s' % err.message) return None
def run_script(self): try: session = cs_api.CloudShellAPISession('localhost', username=ADMIN_USERNAME, password=ADMIN_PASSWORD, domain='Global') res_list = session.GetScheduledReservations(fromTime=START_TIME, untilTime=END_TIME).Reservations deleted = 0 if USERS_TO_DELETE: for res in res_list: if res.Owner in USERS_TO_DELETE: deleted += 1 session.DeleteReservation(reservationId=res.Id) print 'Number of deleted Reservations: ' + str(deleted) except Exception: print 'Error: please contact Quali for assistance'
def __init__(self): """ :rtype: object :param self: :return: """ # set the config file path & load the json file self.json_file_path = 'config.json' self.configs = json.loads(open(self.json_file_path).read()) # set logging file path self.logfile = self.configs['log_file_path'] # set the default password for new user self.default_password = self.configs['new_user_default_password'] # start CloudShell API Session self.cs_session = cs_api.CloudShellAPISession( self.configs["qs_server_hostname"], self.configs["qs_admin_username"], base64.b64decode(self.configs["qs_admin_password"]), domain="Global")
def printIPsInContainer(self, context, containerName): ApiSession = api.CloudShellAPISession( host=context.connectivity.server_address, token_id=context.connectivity.admin_auth_token, domain="Global") try: containerResource = ApiSession.GetResourceDetails(containerName) except: raise ValueError("Specified container does not exist.") rl = ApiSession.FindResources(resourceFamily="Address", resourceModel="IP Address", includeSubResources=True) cleanList = [] for address in rl.Resources: if (containerName in address.FullName): cleanList.append(address.Name) cleanList = natsorted(cleanList, alg=ns.IGNORECASE) return json.dumps(cleanList)
def export(self, cloudshell_server, user, password, domain): session = api.CloudShellAPISession(cloudshell_server, user, password, domain) models = session.ExportFamiliesAndModels() """ :type models: cloudshell.api.cloudshell_api.ExportConfigurationInfo """ import xml.etree.ElementTree as ET xmlstring = re.sub(' xmlns="[^"]+"', '', models.Configuration, count=1) tree = ET.fromstring(xmlstring) tosca = { 'tosca_definitions_version': 'tosca_simple_yaml_1_0', 'description': 'CloudShell node types' } node_types = {} node_types['cloudshell.nodes.resource'] = { 'derived_from': 'root', 'properties': { 'vendor': { 'type': 'string' } } } for family in tree.findall("./ResourceFamilies/ResourceFamily"): if not family.get('IsService'): for model in family.findall("./Models/ResourceModel"): name = 'cloudshell.nodes.{model_name}'.format( model_name=model.get('Name')) node_types[name] = { 'derived_from': 'cloudshell.nodes.resource' } tosca['node_types'] = node_types with open('template.yaml', 'w') as yaml_file: yaml_file.write(yaml.dump(tosca, default_flow_style=False))
import zipfile import cloudshell.api.cloudshell_api as api NameOfDriver = 'CalculateOrchTimes' ZipAddress = NameOfDriver + '.zip' z = zipfile.ZipFile(ZipAddress, "w") # z.write("drivermetadata.xml") z.write("requirements.txt") z.write("html_table_builder.py") z.write("calculate.py") z.write("login_sbox_api_activityFeed.py") z.write("__main__.py") z.close() ss = api.CloudShellAPISession('localhost', 'admin', 'admin', 'Global') ss.UpdateScript(NameOfDriver, ZipAddress)
cancellation_context = mock.create_autospec(CancellationContext) context = mock.create_autospec(ResourceCommandContext) context.resource = mock.MagicMock() context.reservation = mock.MagicMock() context.connectivity = mock.MagicMock() context.reservation.reservation_id = "<Reservation ID>" context.resource.address = "<IP Address>" # Sentry 3 context.resource.name = "Debug_Sentry3" context.resource.attributes = dict() context.resource.attributes["{}.User".format(shell_name)] = "admn" context.resource.attributes["{}.Password".format(shell_name)] = "admn" context.resource.attributes["{}.SNMP Read Community".format( shell_name)] = "public" context.resource.attributes["{}.SNMP Write Community".format( shell_name)] = "private" cs_session = cs_api.CloudShellAPISession("localhost", "admin", "admin", domain="Global", port=8029) context.connectivity.cloudshell_api_port = cs_session.port context.connectivity.server_address = cs_session.host context.connectivity.admin_auth_token = cs_session.token_id driver = SentryPduDriver() # print driver.run_custom_command(context, custom_command="sh run", cancellation_context=cancellation_context) driver.initialize(context) result = driver.get_inventory(context) print "done"
import cloudshell.api.cloudshell_api as api session = api.CloudShellAPISession("1.1.1.1","admin","admin","Global") def clp_selector (clp_type): if clp_type=="VC": clp_vcenter_creator("VMware vCenter") elif clp_type=="MA": clp_Azure_creator("Microsoft Azure") elif clp_type=="OS": clp_OpenStack_creator("OpenStack") elif clp_type=="AWS": clp_AWS_creator("AWS EC2") elif clp_type=="-hlp" or clp_type=="--help" or clp_type=="-h": help_doco() def help_doco(): print "AWS for aws Ec2 \n"\ "VC for VMWare vCenter \n"\ "OS for OpenStack \n"\ "MA for Microsoft Azure \n" return def clp_vcenter_creator (clp_type): try: vCenter = session.CreateResource("Cloud Provider",clp_type,clp_type,"192.168.42.110") print "Creating "+clp_type+" cloudProvider" except: print "There is already cloudprovider named VMWare vCenter" set_attributes = [] User = ""
def cli(): # Build CLI parser to get info. Should be passed in via CLI from PHP parser = argparse.ArgumentParser( description='CLI Tool to import resources via CLI into CloudShell v0.3' ) # creds parser.add_argument('-c', action="store", dest="create", help="create a sample CSV") parser.add_argument('-q', action="store", dest="host", help="server hostname for API session") parser.add_argument('-u', action="store", dest="un", help="username for API session") parser.add_argument('-p', action="store", dest="pw", help="password for API session") parser.add_argument('-d', action="store", dest="dom", help="domain for API session") # args parser.add_argument('-f', action='store', dest="file", help="filename to import") arg = parser.parse_args() if (arg.create != None): print "Creating sample CSV file in " + arg.create csvContents = """Parent,Description,Name,ResourceFamilyName,ResourceModelName,FolderFullPath,Address,Location,Vendor,Gateway,Duplex,Speed ,description,MyAccess,Access,ALU ADSL,LabA/room-C,199.999.777,,Huawei,,, MyAccess,,Port1,Generic Port,Generic Ethernet Port,not relevant,1,,,,,1 Gbps MyAccess,,Port2,Generic Port,Generic Ethernet Port,,2,,,,Half, ,,,,,,,,,,, ,,,,,,,,,,, ,GW description,myGateWay,Gateway,Gateway Generic Model,Lab_B/room_A,12.23.3.2,RoshPina,,,, myGateWay,nas gateway,myBlade,Generic Blade,Generic Blade Model,not relevant,1,,,,, myGateWay/myBlade,,p1,Generic Port,Generic Ethernet Port,,1,,,,Half,1 Gbps myGateWay/myBlade,,p2,Generic Port,Generic Ethernet Port,,1,,,,Half,1 Gbps """ fh = open(arg.create, "w") fh.write(csvContents) fh.close() exit(0) # make sure all args are there elif ((arg.host != None) and (arg.un != None) and (arg.pw != None) and (arg.dom != None) and (arg.file != None)): ApiSession = api.CloudShellAPISession(arg.host, arg.un, arg.pw, arg.dom) manager = CloudShellManager(ApiSession) with open(arg.file) as csvfile: csvReader = csv.reader(csvfile, delimiter=',', quotechar='\n') for row in csvReader: parent = row[manager.ParentColumn] name = row[manager.ResourceNameColumn] folder = row[manager.FolderColumn].decode('unicode_escape') try: if name == 'Name': #Row 0 - manager.SetHeader(row) else: # if folder and (not parent): #root resource print folder manager.session.CreateFolder(folder) if not manager.isEmptyRow(row): manager.AddResource(row) manager.AddAttributes(row) except Exception as error: print "Error in CSV row entry: '" + ', '.join( row) + ". " + error.message exit(5) else: print "You must provide the username, password, domain, and file." exit(1)
import json username = '******' password = '******' server = 'localhost' domain = 'Global' login_url = 'http://localhost:82/api/login' login_data = {"username": "******", "password": "******", "domain": "Global"} login_response = requests.put(url=login_url, json=login_data).text[1:-1] headers = {"Authorization": "Basic {}".format(login_response)} sandboxes_current_url = 'http://localhost:82/api/v2/sandboxes' sandboxes_current = requests.get(url=sandboxes_current_url, headers=headers).text sandboxes__current_json = json.loads(sandboxes_current) sandboxes_historic_url = 'http://localhost:82/api/v2/sandboxes?show_historic=true' sandboxes_historic = requests.get(url=sandboxes_historic_url, headers=headers).text sandboxes_historic_json = json.loads(sandboxes_historic) old_sandboxes = [] for item in sandboxes_historic_json: if item not in sandboxes__current_json: old_sandboxes.append(item.get('id')) session = api.CloudShellAPISession(username=username, password=password, domain=domain, host=server) for sbox in old_sandboxes: session.DeleteReservation(reservationId=sbox)
loss_rate = float(raw[1:]) else: raw = raw.split('%')[0] loss_rate = float(raw.split(' ')[-1]) packet_Rx = 100 - loss_rate if packet_Rx >= pass_rate: return True return False except Exception as e: return True session = cs_api.CloudShellAPISession('localhost', username='******', password='******', domain='Global') resources = session.GetResourceList().Resources csv_data = [['Name', 'IP']] for each in resources: address = each.Address if ':Matrix' in each.Address: address = each.Address.split(':')[0] if each.Address == 'NA' or each.ResourceModelName == 'Generic App Model': continue if not ping(address): csv_data.append([each.Name, each.Address]) print each.Name, address, each.ResourceModelName