sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get_dev_run_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentRun" f_url = url + get_dev_run_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # print (r.status_code) if r.status_code == 200: run_conf = (json.loads(r.text))['content'] type(run_conf) if run_conf is None: return "This features is no supported on this device" else: return run_conf else: return "This features is not supported on this device"
function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device"
entailment
def get_dev_start_config(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentStart" f_url = url + get_dev_run_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) if r.status_code == 200: start_conf = (json.loads(r.text))['content'] return start_conf else: # print (r.status_code) return "This feature is not supported on this device"
function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device"
entailment
def get_dev_alarms(devId): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_dev_alarm_url = "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devId) + "&desc=false" f_url = url + get_dev_alarm_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) if r.status_code == 200: dev_alarm = (json.loads(r.text)) if 'alarm' in dev_alarm: return dev_alarm['alarm'] else: return "Device has no alarms"
function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device
entailment
def get_real_time_locate(ipAddress): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() real_time_locate_url = "/imcrs/res/access/realtimeLocate?type=2&value=" + str(ipAddress) + "&total=false" f_url = url + real_time_locate_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: return json.loads(r.text)['realtimeLocation'] else: print(r.status_code) print("An Error has occured")
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex
entailment
def get_ip_mac_arp_list(devId): """ function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :return: list of dictionaries containing the IP/MAC/ARP list of the target device. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() ip_mac_arp_list_url = "/imcrs/res/access/ipMacArp/" + str(devId) f_url = url + ip_mac_arp_list_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: macarplist = (json.loads(r.text)) if len(macarplist) > 1: return macarplist['ipMacArp'] else: return ['this function is unsupported'] else: print(r.status_code) print("An Error has occured")
function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param devId: int or str value of the target device. :return: list of dictionaries containing the IP/MAC/ARP list of the target device.
entailment
def get_custom_views(name=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() if name is None: get_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=false' elif name is not None: get_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name='+ name + '&desc=false&total=false' f_url = url + get_custom_views_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: customviewlist = (json.loads(r.text))['customView'] if type(customviewlist) is dict: customviewlist = [customviewlist] return customviewlist else: return customviewlist else: print(r.status_code) print("An Error has occured")
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views.
entailment
def create_custom_views(name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=falsee' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(upperview)[0]['symbolId'] payload = '''{ "name": "'''+name+ '''"upperview" : "'''+str(parentviewid)+'''"}''' print (payload) r = requests.post(f_url, data = payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 201: return 'View ' + name +' created successfully' else: print(r.status_code) print("An Error has occured")
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views.
entailment
def create_dev_vlan(devid, vlanid, vlan_name): """ function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() create_dev_vlan_url = "/imcrs/vlan?devId=" + str(devid) f_url = url + create_dev_vlan_url payload = '''{ "vlanId": "''' + str(vlanid) + '''", "vlanName" : "''' + str(vlan_name) + '''"}''' r = requests.post(f_url, data=payload, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print (r.status_code) if r.status_code == 201: print ('Vlan Created') return r.status_code elif r.status_code == 409: return '''Unable to create VLAN.\nVLAN Already Exists\nDevice does not support VLAN function''' else: print("An Error has occured")
function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values.
entailment
def delete_dev_vlans(devid, vlanid): """ function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() remove_dev_vlan_url = "/imcrs/vlan/delvlan?devId=" + str(devid) + "&vlanId=" + str(vlanid) f_url = url + remove_dev_vlan_url payload = None r = requests.delete(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print (r.status_code) if r.status_code == 204: print ('Vlan deleted') return r.status_code elif r.status_code == 409: print ('Unable to delete VLAN.\nVLAN does not Exist\nDevice does not support VLAN function') return r.status_code else: print("An Error has occured")
function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values.
entailment
def set_inteface_down(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/down" f_url = url + set_int_down_url payload = None r = requests.put(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code else: print("An Error has occured")
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values.
entailment
def set_inteface_up(devid, ifindex): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url payload = None r = requests.put(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code else: print("An Error has occured")
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values.
entailment
def get_vm_host_info(hostId): """ function takes hostId as input to RESTFUL call to HP IMC :param hostId: int or string of HostId of Hypervisor host :return:list of dictionatires contraining the VM Host information for the target hypervisor """ global r if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() get_vm_host_info_url = "/imcrs/vrm/host?hostId=" + str(hostId) f_url = url + get_vm_host_info_url payload = None r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents # print(r.status_code) if r.status_code == 200: if len(r.text) > 0: return json.loads(r.text) elif r.status_code == 204: print("Device is not a supported Hypervisor") return "Device is not a supported Hypervisor" else: print("An Error has occured")
function takes hostId as input to RESTFUL call to HP IMC :param hostId: int or string of HostId of Hypervisor host :return:list of dictionatires contraining the VM Host information for the target hypervisor
entailment
def get_trap_definitions(): """Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details """ # checks to see if the imc credentials are already available if auth is None or url is None: set_imc_creds() global r get_trap_def_url = "/imcrs/fault/trapDefine/sync/query?enterpriseId=1.3.6.1.4.1.11&size=10000" f_url = url + get_trap_def_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) # r.status_code if r.status_code == 200: trap_def_list = (json.loads(r.text)) return trap_def_list['trapDefine'] else: print("get_dev_asset_details: An Error has occured")
Takes in no param as input to fetch SNMP TRAP definitions from HP IMC RESTFUL API :param None :return: object of type list containing the device asset details
entailment
def rate_limits(self): """Returns list of rate limit information from the response""" if not self._rate_limits: self._rate_limits = utilities.get_rate_limits(self._response) return self._rate_limits
Returns list of rate limit information from the response
entailment
def get_custom_views(auth, url, name=None): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_views = get_custom_views(auth.creds, auth.url) >>> assert type(all_views) is list >>> assert 'name' in all_views[0] >>> non_existant_view = get_custom_views(auth.creds, auth.url, name = '''Doesn't Exist''') >>> assert non_existant_view is None """ get_custom_view_url = None if name is None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \ '&total=false' elif name is not None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name=' + \ name + '&desc=false&total=false' f_url = url + get_custom_view_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: custom_view_list = (json.loads(response.text)) if 'customView' in custom_view_list: custom_view_list = custom_view_list['customView'] if isinstance(custom_view_list, dict): custom_view_list = [custom_view_list] return custom_view_list else: return custom_view_list except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_views = get_custom_views(auth.creds, auth.url) >>> assert type(all_views) is list >>> assert 'name' in all_views[0] >>> non_existant_view = get_custom_views(auth.creds, auth.url, name = '''Doesn't Exist''') >>> assert non_existant_view is None
entailment
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0] """ view_id = get_custom_views(auth, url, name=name) if view_id is None: return view_id view_id = get_custom_views(auth, url, name=name)[0]['symbolId'] get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + get_custom_view_details_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: current_devices = (json.loads(response.text)) if 'device' in current_devices: if isinstance(current_devices['device'], dict): return [current_devices['device']] else: return current_devices['device'] else: return [] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_view_details('My Network View', auth.creds, auth.url) >>> assert type(view_details) is list >>> assert 'label' in view_details[0]
entailment
def create_custom_views(auth, url, name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optional Name input will return only the specified view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: string containg the name of the desired custom view :param upperview: str contraining the name of the desired parent custom view :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") #Create L1 custom view >>> create_custom_views(auth.creds, auth.url, name='L1 View') 'View L1 View created successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert type(view_1) is list >>> assert view_1[0]['name'] == 'L1 View' #Create Nested custome view >>> create_custom_views(auth.creds, auth.url, name='L2 View', upperview='L1 View') 'View L2 View created successfully' >>> view_2 = get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert type(view_2) is list >>> assert view_2[0]['name'] == 'L2 View' """ create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \ '&total=false' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' else: parentviewid = get_custom_views(auth, url, upperview)[0]['symbolId'] payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : "''' + str(parentviewid) + '''"}''' response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 201: print('View ' + name + ' created successfully') return response.status_code elif response.status_code == 409: print("View " + name + " already exists") return response.status_code else: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optional Name input will return only the specified view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param name: string containg the name of the desired custom view :param upperview: str contraining the name of the desired parent custom view :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") #Create L1 custom view >>> create_custom_views(auth.creds, auth.url, name='L1 View') 'View L1 View created successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert type(view_1) is list >>> assert view_1[0]['name'] == 'L1 View' #Create Nested custome view >>> create_custom_views(auth.creds, auth.url, name='L2 View', upperview='L1 View') 'View L2 View created successfully' >>> view_2 = get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert type(view_2) is list >>> assert view_2[0]['name'] == 'L2 View'
entailment
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param custom_view_name: str of the target custom view name :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") """ view_id = get_custom_views(auth, url, name=custom_view_name) if view_id is None: print("View " + custom_view_name + " doesn't exist") return view_id view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId'] add_devs_custom_views_url = '/imcrs/plat/res/view/custom/' + str(view_id) device_list = [] for dev in dev_list: new_dev = {"id": dev} device_list.append(new_dev) payload = '''{"device" : ''' + json.dumps(device_list) + '''}''' print(payload) f_url = url + add_devs_custom_views_url response = requests.put(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('View ' + custom_view_name + ' : Devices Successfully Added') return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_custom_views: An Error has occured'
function takes a list of devIDs from devices discovered in the HPE IMC platform and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param custom_view_name: str of the target custom view name :param dev_list: list containing the devID of all devices to be contained in this custom view. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
entailment
def delete_custom_view(auth, url, name): """ function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 is None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 is None """ view_id = get_custom_views(auth, url, name) if view_id is None: print("View " + name + " doesn't exists") return view_id view_id = get_custom_views(auth, url, name)[0]['symbolId'] delete_custom_view_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + delete_custom_view_url response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: print('View ' + name + ' deleted successfully') return response.status_code else: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' delete_custom_view: An Error has occured'
function takes input of auth, url, and name and issues a RESTFUL call to delete a specific of custom views from HPE IMC. :param name: string containg the name of the desired custom view :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_custom_view(auth.creds, auth.url, name = "L1 View") 'View L1 View deleted successfully' >>> view_1 =get_custom_views( auth.creds, auth.url, name = 'L1 View') >>> assert view_1 is None >>> delete_custom_view(auth.creds, auth.url, name = "L2 View") 'View L2 View deleted successfully' >>> view_2 =get_custom_views( auth.creds, auth.url, name = 'L2 View') >>> assert view_2 is None
entailment
def _get_token(self): """ Get token for make request. The The data obtained herein are used in the variable header. Returns: To perform the request, receive in return a dictionary with several keys. With this method only return the token as it will use it for subsequent requests, such as a sentence translate. Returns one string type. """ informations = self._set_format_oauth() oauth_url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13" token = requests.post(oauth_url, informations).json() return token["access_token"]
Get token for make request. The The data obtained herein are used in the variable header. Returns: To perform the request, receive in return a dictionary with several keys. With this method only return the token as it will use it for subsequent requests, such as a sentence translate. Returns one string type.
entailment
def _set_format_oauth(self): """ Format and encode dict for make authentication on microsoft servers. """ format_oauth = urllib.parse.urlencode({ 'client_id': self._client_id, 'client_secret': self._client_secret, 'scope': self._url_request, 'grant_type': self._grant_type }).encode("utf-8") return format_oauth
Format and encode dict for make authentication on microsoft servers.
entailment
def _make_request(self, params, translation_url, headers): """ This is the final step, where the request is made, the data is retrieved and returned. """ resp = requests.get(translation_url, params=params, headers=headers) resp.encoding = "UTF-8-sig" result = resp.json() return result
This is the final step, where the request is made, the data is retrieved and returned.
entailment
def _get_content(self, params, mode_translate): """ This method gets the token and makes the header variable that will be used in connection authentication. After that, calls the _make_request() method to return the desired data. """ token = self._get_token() headers = {'Authorization': 'Bearer '+ token} parameters = params translation_url = mode_translate return self._make_request(parameters, translation_url, headers)
This method gets the token and makes the header variable that will be used in connection authentication. After that, calls the _make_request() method to return the desired data.
entailment
def detect_language(self, text): """ Params: ::text = Text for identify language. Returns: Returns language present on text. """ infos_translate = TextDetectLanguageModel(text).to_dict() mode_translate = TranslatorMode.Detect.value return self._get_content(infos_translate, mode_translate)
Params: ::text = Text for identify language. Returns: Returns language present on text.
entailment
def detect_languages(self, texts): """ Params: ::texts = Array of texts for detect languages Returns: Returns language present on array of text. """ text_list = TextUtils.format_list_to_send(texts) infos_translate = TextDetectLanguageModel(text_list).to_dict() texts_for_detect = TextUtils.change_key(infos_translate, "text", "texts", infos_translate["text"]) mode_translate = TranslatorMode.DetectArray.value return self._get_content(texts_for_detect, mode_translate)
Params: ::texts = Array of texts for detect languages Returns: Returns language present on array of text.
entailment
def translate(self, text, to_lang, from_lang=None, content_type="text/plain", category=None): """ This method takes as a parameter the desired text to be translated and the language to which should be translated. To find the code for each language just go to the library home page. The parameter ::from_lang:: is optional because the api microsoft recognizes the language used in a sentence automatically. The parameter ::content_type:: defaults to "text/plain". In fact it can be of two types: the very "text/plain" or "text/html". By default the parameter ::category:: is defined as "general", we do not touch it. """ infos_translate = TextModel(text, to_lang, from_lang, content_type, category).to_dict() mode_translate = TranslatorMode.Translate.value return self._get_content(infos_translate, mode_translate)
This method takes as a parameter the desired text to be translated and the language to which should be translated. To find the code for each language just go to the library home page. The parameter ::from_lang:: is optional because the api microsoft recognizes the language used in a sentence automatically. The parameter ::content_type:: defaults to "text/plain". In fact it can be of two types: the very "text/plain" or "text/html". By default the parameter ::category:: is defined as "general", we do not touch it.
entailment
def speak_phrase(self, text, language, format_audio=None, option=None): """ This method is very similar to the above, the difference between them is that this method creates an object of class TranslateSpeak(having therefore different attributes) and use another url, as we see the presence of SpeakMode enumerator instead of Translate. The parameter ::language:: is the same as the previous method(the parameter ::lang_to::). To see all possible languages go to the home page of the documentation that library. The parameter ::format_audio:: can be of two types: "audio/mp3" or "audio/wav". If we do not define, Microsoft api will insert by default the "audio/wav". It is important to be aware that, to properly name the file downloaded by AudioSpeaked class(which uses theclassmethod download). The parameter ::option:: is responsible for setting the audio quality. It can be of two types: "MaxQuality" or "MinQuality". By default, if not define, it will be "MinQuality". """ infos_speak_translate = SpeakModel( text, language, format_audio, option).to_dict() mode_translate = TranslatorMode.SpeakMode.value return self._get_content(infos_speak_translate, mode_translate)
This method is very similar to the above, the difference between them is that this method creates an object of class TranslateSpeak(having therefore different attributes) and use another url, as we see the presence of SpeakMode enumerator instead of Translate. The parameter ::language:: is the same as the previous method(the parameter ::lang_to::). To see all possible languages go to the home page of the documentation that library. The parameter ::format_audio:: can be of two types: "audio/mp3" or "audio/wav". If we do not define, Microsoft api will insert by default the "audio/wav". It is important to be aware that, to properly name the file downloaded by AudioSpeaked class(which uses theclassmethod download). The parameter ::option:: is responsible for setting the audio quality. It can be of two types: "MaxQuality" or "MinQuality". By default, if not define, it will be "MinQuality".
entailment
def get_vm_host_info(hostip, auth, url): """ function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: Dictionary contraining the information for the target VM host :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vrm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url) >>> assert type(host_info) is dict >>> assert len(host_info) == 10 >>> assert 'cpuFeg' in host_info >>> assert 'cpuNum' in host_info >>> assert 'devId' in host_info >>> assert 'devIp' in host_info >>> assert 'diskSize' in host_info >>> assert 'memory' in host_info >>> assert 'parentDevId' in host_info >>> assert 'porductFlag' in host_info >>> assert 'serverName' in host_info >>> assert 'vendor' in host_info """ hostid = get_dev_details(hostip, auth, url)['id'] f_url = url + "/imcrs/vrm/host?hostId=" + str(hostid) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: if len(response.text) > 0: return json.loads(response.text) elif response.status_code == 204: print("Device is not a supported Hypervisor") return "Device is not a supported Hypervisor" except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_vm_host_info: An Error has occured"
function takes hostId as input to RESTFUL call to HP IMC :param hostip: int or string of hostip of Hypervisor host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: Dictionary contraining the information for the target VM host :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.vrm import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url) >>> assert type(host_info) is dict >>> assert len(host_info) == 10 >>> assert 'cpuFeg' in host_info >>> assert 'cpuNum' in host_info >>> assert 'devId' in host_info >>> assert 'devIp' in host_info >>> assert 'diskSize' in host_info >>> assert 'memory' in host_info >>> assert 'parentDevId' in host_info >>> assert 'porductFlag' in host_info >>> assert 'serverName' in host_info >>> assert 'vendor' in host_info
entailment
def get_plat_operator(auth, url,headers=HEADERS): ''' Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC system :return: list of dictionaries ''' get_operator_url = '/imcrs/plat/operator?start=0&size=1000&orderBy=id&desc=false&total=false' f_url = url + get_operator_url try: r = requests.get(f_url, auth=auth, headers=headers) plat_oper_list = json.loads(r.text) return plat_oper_list['operator'] except requests.exceptions.RequestException as e: print ("Error:\n" + str(e) + ' get_plat_operator: An Error has occured') return "Error:\n" + str(e) + ' get_plat_operator: An Error has occured'
Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC system :return: list of dictionaries
entailment
def delete_plat_operator(operator,auth, url, headers=HEADERS): """ Function to set the password of an existing operator :param operator: str Name of the operator account :param password: str New password :param url: str url of IMC server, see requests library docs for more info :param auth: str see requests library docs for more info :param headers: json formated string. default values set in module :return: """ #oper_id = None plat_oper_list = get_plat_operator(auth, url) for i in plat_oper_list: if operator == i['name']: oper_id = i['id'] if oper_id == None: return("\n User does not exist") delete_plat_operator_url = "/imcrs/plat/operator/" f_url = url + delete_plat_operator_url + str(oper_id) r = requests.delete(f_url, auth=auth, headers=headers) try: if r.status_code == 204: print("\n Operator: " + operator + " was successfully deleted") return r.status_code except requests.exceptions.RequestException as e: print ("Error:\n" + str(e) + ' delete_plat_operator: An Error has occured') return "Error:\n" + str(e) + ' delete_plat_operator: An Error has occured'
Function to set the password of an existing operator :param operator: str Name of the operator account :param password: str New password :param url: str url of IMC server, see requests library docs for more info :param auth: str see requests library docs for more info :param headers: json formated string. default values set in module :return:
entailment
def index(self, value): """ Args: value: index Returns: index of the values Raises: ValueError: value is not in list """ for i, x in enumerate(self): if x == value: return i raise ValueError("{} is not in list".format(value))
Args: value: index Returns: index of the values Raises: ValueError: value is not in list
entailment
def to_d(self): """ Args: self Returns: a d that stems from self Raises: ValueError: dictionary update sequence element #index has length len(tuple); 2 is required TypeError: cannot convert dictionary update sequence element #index to a sequence """ try: return ww.d(self) except (TypeError, ValueError): for i, element in enumerate(self): try: iter(element) # TODO: find out why we can't cover this branch. The code # is tested but don't appear in coverage except TypeError: # pragma: no cover # TODO: use raise_from ? raise ValueError(("'{}' (position {}) is not iterable. You" " can only create a dictionary from a " "elements that are iterables, such as " "tuples, lists, etc.") .format(element, i)) try: size = len(element) except TypeError: # ignore generators, it's already consummed pass else: raise ValueError(("'{}' (position {}) contains {} " "elements. You can only create a " "dictionary from iterables containing " "2 elements.").format(element, i, size)) raise
Args: self Returns: a d that stems from self Raises: ValueError: dictionary update sequence element #index has length len(tuple); 2 is required TypeError: cannot convert dictionary update sequence element #index to a sequence
entailment
def get_cfg_template(auth, url, folder = None): ''' Function takes no input and returns a list of dictionaries containing the configuration templates in the root folder of the icc configuration template library. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: List of Dictionaries containing folders and configuration files in the ICC library. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> config_templates = get_cfg_template(auth.creds, auth.url) >>> assert type(config_templates) is list >>> assert 'confFileName' in config_templates[0] >>> config_templates_folder = get_cfg_template(auth.creds, auth.url, folder='ADP_Configs') >>> assert type(config_templates_folder) is list >>> assert 'confFileName' in config_templates_folder[0] >>> config_template_no_folder = get_cfg_template(auth.creds, auth.url, folder='Doesnt_Exist') >>> assert config_template_no_folder == None ''' if folder == None: get_cfg_template_url = "/imcrs/icc/confFile/list" else: folder_id = get_folder_id(folder, auth, url) get_cfg_template_url = "/imcrs/icc/confFile/list/"+str(folder_id) f_url = url + get_cfg_template_url r = requests.get(f_url,auth=auth, headers=HEADERS) #print (r.status_code) try: if r.status_code == 200: cfg_template_list = (json.loads(r.text)) return cfg_template_list['confFile'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_cfg_template: An Error has occured"
Function takes no input and returns a list of dictionaries containing the configuration templates in the root folder of the icc configuration template library. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: List of Dictionaries containing folders and configuration files in the ICC library. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> config_templates = get_cfg_template(auth.creds, auth.url) >>> assert type(config_templates) is list >>> assert 'confFileName' in config_templates[0] >>> config_templates_folder = get_cfg_template(auth.creds, auth.url, folder='ADP_Configs') >>> assert type(config_templates_folder) is list >>> assert 'confFileName' in config_templates_folder[0] >>> config_template_no_folder = get_cfg_template(auth.creds, auth.url, folder='Doesnt_Exist') >>> assert config_template_no_folder == None
entailment
def create_cfg_segment(filename, filecontent, description, auth, url): ''' Takes a str into var filecontent which represents the entire content of a configuration segment, or partial configuration file. Takes a str into var description which represents the description of the configuration segment :param filename: str containing the name of the configuration segment. :param filecontent: str containing the entire contents of the configuration segment :param description: str contrianing the description of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolena of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = ("""sample file content""") >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_id) is str >>> ''' payload = {"confFileName": filename, "confFileType": "2", "cfgFileParent": "-1", "confFileDesc": description, "content": filecontent} create_cfg_segment_url = "/imcrs/icc/confFile" f_url = url + create_cfg_segment_url # creates the URL using the payload variable as the contents r = requests.post(f_url,data= (json.dumps(payload)), auth=auth, headers=HEADERS) try: if r.status_code == 201: return True except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " create_cfg_segment: An Error has occured"
Takes a str into var filecontent which represents the entire content of a configuration segment, or partial configuration file. Takes a str into var description which represents the description of the configuration segment :param filename: str containing the name of the configuration segment. :param filecontent: str containing the entire contents of the configuration segment :param description: str contrianing the description of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolena of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = ("""sample file content""") >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_id) is str >>>
entailment
def get_template_id(template_name, auth, url): """ Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> file_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(file_id) is str """ object_list = get_cfg_template(auth=auth, url=url) for object in object_list: if object['confFileName'] == template_name: return object['confFileId'] return "template not found"
Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> file_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(file_id) is str
entailment
def delete_cfg_template(template_name, auth, url): '''Uses the get_template_id() funct to gather the template_id to craft a url which is sent to the IMC server using a Delete Method :param template_name: str containing the entire contents of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolean of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_cfg_template('CW7SNMP.cfg', auth.creds, auth.url) True >>> get_template_id('CW7SNMP.cfg', auth.creds, auth.url) 'template not found' ''' file_id = get_template_id(template_name, auth, url) delete_cfg_template_url = "/imcrs/icc/confFile/"+str(file_id) f_url = url + delete_cfg_template_url # creates the URL using the payload variable as the contents r = requests.delete(f_url, auth=auth, headers=HEADERS) #print (r.status_code) try: if r.status_code == 204: return True except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " delete_cfg_template: An Error has occured"
Uses the get_template_id() funct to gather the template_id to craft a url which is sent to the IMC server using a Delete Method :param template_name: str containing the entire contents of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolean of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_cfg_template('CW7SNMP.cfg', auth.creds, auth.url) True >>> get_template_id('CW7SNMP.cfg', auth.creds, auth.url) 'template not found'
entailment
def get_folder_id(folder_name, auth, url): """ Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> default_folder_id = get_folder_id('Default Folder', auth.creds, auth.url) >>> assert type(default_folder_id) is str """ object_list = get_cfg_template(auth=auth, url=url) for object in object_list: if object['confFileName'] == folder_name: return object['confFileId'] return "Folder not found"
Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> default_folder_id = get_folder_id('Default Folder', auth.creds, auth.url) >>> assert type(default_folder_id) is str
entailment
def bold(text: str) -> str: ''' Wraps the given text with bold enable/disable ANSI sequences. ''' return (style(text, bold=True, reset=False) + style('', bold=False, reset=False))
Wraps the given text with bold enable/disable ANSI sequences.
entailment
async def status(cls): ''' Returns the current status of the configured API server. ''' rqst = Request(cls.session, 'GET', '/manager/status') rqst.set_json({ 'status': 'running', }) async with rqst.fetch() as resp: return await resp.json()
Returns the current status of the configured API server.
entailment
async def freeze(cls, force_kill: bool = False): ''' Freezes the configured API server. Any API clients will no longer be able to create new compute sessions nor create and modify vfolders/keypairs/etc. This is used to enter the maintenance mode of the server for unobtrusive manager and/or agent upgrades. :param force_kill: If set ``True``, immediately shuts down all running compute sessions forcibly. If not set, clients who have running compute session are still able to interact with them though they cannot create new compute sessions. ''' rqst = Request(cls.session, 'PUT', '/manager/status') rqst.set_json({ 'status': 'frozen', 'force_kill': force_kill, }) async with rqst.fetch() as resp: assert resp.status == 204
Freezes the configured API server. Any API clients will no longer be able to create new compute sessions nor create and modify vfolders/keypairs/etc. This is used to enter the maintenance mode of the server for unobtrusive manager and/or agent upgrades. :param force_kill: If set ``True``, immediately shuts down all running compute sessions forcibly. If not set, clients who have running compute session are still able to interact with them though they cannot create new compute sessions.
entailment
def get_dev_alarms(devId, auth=auth.creds, url=auth.url): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device """ # checks to see if the imc credentials are already available get_dev_alarm_url = "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devId) + "&desc=false" f_url = url + get_dev_alarm_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=headers) try: if r.status_code == 200: dev_alarm = (json.loads(r.text)) if 'alarm' in dev_alarm: return dev_alarm['alarm'] else: return "Device has no alarms" except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devId: int or str value of the target device :return:list of dictionaries containing the alarms for this device
entailment
def upload(sess_id_or_alias, files): """ Upload files to user's home folder. \b SESSID: Session ID or its alias given when creating the session. FILES: Path to upload. """ if len(files) < 1: return with Session() as session: try: print_wait('Uploading files...') kernel = session.Kernel(sess_id_or_alias) kernel.upload(files, show_progress=True) print_done('Uploaded.') except Exception as e: print_error(e) sys.exit(1)
Upload files to user's home folder. \b SESSID: Session ID or its alias given when creating the session. FILES: Path to upload.
entailment
def download(sess_id_or_alias, files, dest): """ Download files from a running container. \b SESSID: Session ID or its alias given when creating the session. FILES: Paths inside container. """ if len(files) < 1: return with Session() as session: try: print_wait('Downloading file(s) from {}...' .format(sess_id_or_alias)) kernel = session.Kernel(sess_id_or_alias) kernel.download(files, dest, show_progress=True) print_done('Downloaded to {}.'.format(dest.resolve())) except Exception as e: print_error(e) sys.exit(1)
Download files from a running container. \b SESSID: Session ID or its alias given when creating the session. FILES: Paths inside container.
entailment
def ls(sess_id_or_alias, path): """ List files in a path of a running container. \b SESSID: Session ID or its alias given when creating the session. PATH: Path inside container. """ with Session() as session: try: print_wait('Retrieving list of files in "{}"...'.format(path)) kernel = session.Kernel(sess_id_or_alias) result = kernel.list_files(path) if 'errors' in result and result['errors']: print_fail(result['errors']) sys.exit(1) files = json.loads(result['files']) table = [] headers = ['file name', 'size', 'modified', 'mode'] for file in files: mdt = datetime.fromtimestamp(file['mtime']) mtime = mdt.strftime('%b %d %Y %H:%M:%S') row = [file['filename'], file['size'], mtime, file['mode']] table.append(row) print_done('Retrived.') print('Path in container:', result['abspath'], end='') print(tabulate(table, headers=headers)) except Exception as e: print_error(e) sys.exit(1)
List files in a path of a running container. \b SESSID: Session ID or its alias given when creating the session. PATH: Path inside container.
entailment
def main(): """ Main function. :return: None. """ try: # Get the `src` directory's absolute path src_path = os.path.dirname( # `aoiklivereload` directory's absolute path os.path.dirname( # `demo` directory's absolute path os.path.dirname( # This file's absolute path os.path.abspath(__file__) ) ) ) # If the `src` directory path is not in `sys.path` if src_path not in sys.path: # Add to `sys.path`. # # This aims to save user setting PYTHONPATH when running this demo. # sys.path.append(src_path) # Import reloader class from aoiklivereload import LiveReloader # Create reloader reloader = LiveReloader() # Start watcher thread reloader.start_watcher_thread() # Server host server_host = '0.0.0.0' # Server port server_port = 8000 # Get message msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format( server_host, server_port ) # Print message print(msg) # Create Sanic app sanic_app = Sanic() # Create request handler @sanic_app.route('/') async def hello_handler(request): # pylint: disable=unused-variable """ Request handler. :return: Response body. """ # Return response body return text('hello') # Run server. # # Notice `KeyboardInterrupt` will be caught inside `sanic_app.run`. # sanic_app.run( host=server_host, port=server_port, ) # If have `KeyboardInterrupt` except KeyboardInterrupt: # Not treat as error pass
Main function. :return: None.
entailment
def get_cfg_template(auth, url, folder=None): """ Function takes no input and returns a list of dictionaries containing the configuration templates in the root folder of the icc configuration template library. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param folder: optional str of name of target folder :folder = str of target folder name :return: List of Dictionaries containing folders and configuration files in the ICC library. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> config_templates = get_cfg_template(auth.creds, auth.url) >>> assert type(config_templates) is list >>> assert 'confFileName' in config_templates[0] >>> config_templates_folder = get_cfg_template(auth.creds, auth.url, folder='ADP_Configs') >>> assert type(config_templates_folder) is list >>> assert 'confFileName' in config_templates_folder[0] >>> config_template_no_folder = get_cfg_template(auth.creds, auth.url, folder='Doesnt_Exist') >>> assert config_template_no_folder is None """ if folder is None: get_cfg_template_url = "/imcrs/icc/confFile/list" else: folder_id = get_folder_id(folder, auth, url) get_cfg_template_url = "/imcrs/icc/confFile/list/" + str(folder_id) f_url = url + get_cfg_template_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: cfg_template_list = (json.loads(response.text))['confFile'] if isinstance(cfg_template_list, list): return cfg_template_list elif isinstance(cfg_template_list, dict): return [cfg_template_list] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_cfg_template: An Error has occured"
Function takes no input and returns a list of dictionaries containing the configuration templates in the root folder of the icc configuration template library. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param folder: optional str of name of target folder :folder = str of target folder name :return: List of Dictionaries containing folders and configuration files in the ICC library. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> config_templates = get_cfg_template(auth.creds, auth.url) >>> assert type(config_templates) is list >>> assert 'confFileName' in config_templates[0] >>> config_templates_folder = get_cfg_template(auth.creds, auth.url, folder='ADP_Configs') >>> assert type(config_templates_folder) is list >>> assert 'confFileName' in config_templates_folder[0] >>> config_template_no_folder = get_cfg_template(auth.creds, auth.url, folder='Doesnt_Exist') >>> assert config_template_no_folder is None
entailment
def create_cfg_segment(filename, filecontent, description, auth, url): """ Takes a str into var filecontent which represents the entire content of a configuration segment, or partial configuration file. Takes a str into var description which represents the description of the configuration segment :param filename: str containing the name of the configuration segment. :param filecontent: str containing the entire contents of the configuration segment :param description: str contrianing the description of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolena of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = 'sample file content' >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_id) is str >>> """ payload = {"confFileName": filename, "confFileType": "2", "cfgFileParent": "-1", "confFileDesc": description, "content": filecontent} f_url = url + "/imcrs/icc/confFile" response = requests.post(f_url, data=(json.dumps(payload)), auth=auth, headers=HEADERS) try: if response.status_code == 201: print("Template successfully created") return response.status_code elif response.status_code is not 201: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " create_cfg_segment: An Error has occured"
Takes a str into var filecontent which represents the entire content of a configuration segment, or partial configuration file. Takes a str into var description which represents the description of the configuration segment :param filename: str containing the name of the configuration segment. :param filecontent: str containing the entire contents of the configuration segment :param description: str contrianing the description of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolena of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = 'sample file content' >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_id) is str >>>
entailment
def get_template_id(template_name, auth, url): """ Helper function takes str input of folder name and returns str numerical id of the folder. :param template_name: str name of the target template :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> file_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(file_id) is int """ object_list = get_cfg_template(auth=auth, url=url) for template in object_list: if template['confFileName'] == template_name: return int(template['confFileId']) return "template not found"
Helper function takes str input of folder name and returns str numerical id of the folder. :param template_name: str name of the target template :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> file_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(file_id) is int
entailment
def get_folder_id(folder_name, auth, url): """ Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> default_folder_id = get_folder_id('Default Folder', auth.creds, auth.url) >>> assert type(default_folder_id) is int """ object_list = get_cfg_template(auth=auth, url=url) for template in object_list: if template['confFileName'] == folder_name: return int(template['confFileId']) return "Folder not found"
Helper function takes str input of folder name and returns str numerical id of the folder. :param folder_name: str name of the folder :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str numerical id of the folder :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> default_folder_id = get_folder_id('Default Folder', auth.creds, auth.url) >>> assert type(default_folder_id) is int
entailment
def delete_cfg_template(template_name, auth, url): """Uses the get_template_id() funct to gather the template_id to craft a url which is sent to the IMC server using a Delete Method :param template_name: str containing the entire contents of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, return int of status.code 204. :rtype: Int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_cfg_template('CW7SNMP.cfg', auth.creds, auth.url) """ file_id = get_template_id(template_name, auth, url) f_url = url + "/imcrs/icc/confFile/" + str(file_id) response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: print("Template successfully Deleted") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_cfg_template: An Error has occured"
Uses the get_template_id() funct to gather the template_id to craft a url which is sent to the IMC server using a Delete Method :param template_name: str containing the entire contents of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, return int of status.code 204. :rtype: Int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_cfg_template('CW7SNMP.cfg', auth.creds, auth.url)
entailment
def get_template_details(template_name, auth, url): """Uses the get_template_id() funct to gather the template_id to craft a get_template_details_url which is sent to the IMC server using a get Method :param template_name: str containing the entire contents of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, return dict containing the template details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = 'sample file content' >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_contents = get_template_details('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_contents) is dict """ file_id = get_template_id(template_name, auth, url) if isinstance(file_id, str): return file_id f_url = url + "/imcrs/icc/confFile/" + str(file_id) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: template_details = json.loads(response.text) return template_details except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_template_contents: An Error has occured"
Uses the get_template_id() funct to gather the template_id to craft a get_template_details_url which is sent to the IMC server using a get Method :param template_name: str containing the entire contents of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, return dict containing the template details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = 'sample file content' >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_contents = get_template_details('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_contents) is dict
entailment
def get_dev_vlans(devid, auth, url): """Function takes input of devID to issue RESTUL call to HP IMC :param devid: requires devId as the only input parameter :return: dictionary of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module """ # checks to see if the imc credentials are already available get_dev_vlans_url = "/imcrs/vlan?devId=" + str(devid) + "&start=0&size=5000&total=false" f_url = url + get_dev_vlans_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_vlans = (json.loads(r.text)) return dev_vlans['vlan'] elif r.status_code == 409: return {'vlan': 'no vlans'} except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_vlans: An Error has occured'
Function takes input of devID to issue RESTUL call to HP IMC :param devid: requires devId as the only input parameter :return: dictionary of existing vlans on the devices. Device must be supported in HP IMC platform VLAN manager module
entailment
def get_trunk_interfaces(devId, auth, url): """Function takes devId as input to RESTFULL call to HP IMC platform :param devId: output of get_dev_details :return: list of dictionaries containing of interfaces configured as an 802.1q trunk Example: auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") get_dev_asset_details("2", auth.creds, auth.url) """ # checks to see if the imc credentials are already available get_trunk_interfaces_url = "/imcrs/vlan/trunk?devId=" + str(devId) + "&start=1&size=5000&total=false" f_url = url + get_trunk_interfaces_url r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_trunk_interfaces = (json.loads(r.text)) if len(dev_trunk_interfaces) == 2: return dev_trunk_interfaces['trunkIf'] else: dev_trunk_interfaces['trunkIf'] = ["No trunk inteface"] return dev_trunk_interfaces['trunkIf'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_trunk_interfaces: An Error has occured'
Function takes devId as input to RESTFULL call to HP IMC platform :param devId: output of get_dev_details :return: list of dictionaries containing of interfaces configured as an 802.1q trunk Example: auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") get_dev_asset_details("2", auth.creds, auth.url)
entailment
def get_device_access_interfaces(devId, auth, url): """Function takes devId as input to RESTFUL call to HP IMC platform :param devId: requires deviceID as the only input parameter :return: list of dictionaries containing interfaces configured as access ports """ # checks to see if the imc credentials are already available get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devId) + "&start=1&size=500&total=false" f_url = url + get_access_interface_vlan_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_access_interfaces = (json.loads(r.text)) if len(dev_access_interfaces) == 2: return dev_access_interfaces['accessIf'] else: dev_access_interfaces['accessIf'] = ["No access inteface"] return dev_access_interfaces['accessIf'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_device_access_interfaces: An Error has occured"
Function takes devId as input to RESTFUL call to HP IMC platform :param devId: requires deviceID as the only input parameter :return: list of dictionaries containing interfaces configured as access ports
entailment
def create_dev_vlan(devid, vlanid, vlan_name, auth, url): """ function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values. """ create_dev_vlan_url = "/imcrs/vlan?devId=" + str(devid) f_url = url + create_dev_vlan_url payload = '''{ "vlanId": "''' + str(vlanid) + '''", "vlanName" : "''' + str(vlan_name) + '''"}''' r = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents return r try: if r.status_code == 201: print ('Vlan Created') return r.status_code elif r.status_code == 409: return '''Unable to create VLAN.\nVLAN Already Exists\nDevice does not support VLAN function''' except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " create_dev_vlan: An Error has occured"
function takes devid and vlanid vlan_name of specific device and 802.1q VLAN tag and issues a RESTFUL call to add the specified VLAN from the target device. VLAN Name MUST be valid on target device. :param devid: int or str value of the target device :param vlanid:int or str value of target 802.1q VLAN :param vlan_name: str value of the target 802.1q VLAN name. MUST be valid name on target device. :return:HTTP Status code of 201 with no values.
entailment
def delete_dev_vlans(devid, vlanid, auth, url): """ function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values. """ remove_dev_vlan_url = "/imcrs/vlan/delvlan?devId=" + str(devid) + "&vlanId=" + str(vlanid) f_url = url + remove_dev_vlan_url payload = None r = requests.delete(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 204: print ('Vlan deleted') return r.status_code elif r.status_code == 409: print ('Unable to delete VLAN.\nVLAN does not Exist\nDevice does not support VLAN function') return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " delete_dev_vlans: An Error has occured"
function takes devid and vlanid of specific device and 802.1q VLAN tag and issues a RESTFUL call to remove the specified VLAN from the target device. :param devid: int or str value of the target device :param vlanid: :return:HTTP Status code of 204 with no values.
entailment
def create_operator(operator, auth, url): """ Function takes input of dictionary operator with the following keys operator = { "fullName" : "" , "sessionTimeout" : "", "password" : "", "operatorGroupId" : "", "name" : "", "desc" : "", "defaultAcl" : "", "authType" : ""} converts to json and issues a HTTP POST request to the HPE IMC Restful API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param operator: dictionary with the required operator key-value pairs as defined above. :return: :rtype: >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = { "fullName" : "test administrator", "sessionTimeout" : "30", "password" : "password", "operatorGroupId" : "1", "name" : "testadmin", "desc" : "test admin account", "defaultAcl" : "", "authType" : "0"} >>> delete_if_exists = delete_plat_operator('testadmin', auth.creds, auth.url) >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> assert type(new_operator) is int >>> assert new_operator == 201 >>> fail_operator_create = create_operator(operator, auth.creds, auth.url) >>> assert type(fail_operator_create) is int >>> assert fail_operator_create == 409 """ f_url = url + '/imcrs/plat/operator' payload = json.dumps(operator, indent=4) response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 409: return response.status_code elif response.status_code == 201: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' create_operator: An Error has occured'
Function takes input of dictionary operator with the following keys operator = { "fullName" : "" , "sessionTimeout" : "", "password" : "", "operatorGroupId" : "", "name" : "", "desc" : "", "defaultAcl" : "", "authType" : ""} converts to json and issues a HTTP POST request to the HPE IMC Restful API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param operator: dictionary with the required operator key-value pairs as defined above. :return: :rtype: >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = { "fullName" : "test administrator", "sessionTimeout" : "30", "password" : "password", "operatorGroupId" : "1", "name" : "testadmin", "desc" : "test admin account", "defaultAcl" : "", "authType" : "0"} >>> delete_if_exists = delete_plat_operator('testadmin', auth.creds, auth.url) >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> assert type(new_operator) is int >>> assert new_operator == 201 >>> fail_operator_create = create_operator(operator, auth.creds, auth.url) >>> assert type(fail_operator_create) is int >>> assert fail_operator_create == 409
entailment
def set_operator_password(operator, password, auth, url): """ Function to set the password of an existing operator :param operator: str Name of the operator account :param password: str New password :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: int of 204 if successfull, :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = { "fullName" : "test administrator", "sessionTimeout" : "30", "password" : "password","operatorGroupId" : "1", "name" : "testadmin","desc" : "test admin account", "defaultAcl" : "","authType" : "0"} >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> set_new_password = set_operator_password('testadmin', 'newpassword', auth.creds, auth.url) >>> assert type(set_new_password) is int >>> assert set_new_password == 204 """ if operator is None: operator = input( '''\n What is the username you wish to change the password?''') oper_id = '' authtype = None plat_oper_list = get_plat_operator(auth, url) for i in plat_oper_list: if i['name'] == operator: oper_id = i['id'] authtype = i['authType'] if oper_id == '': return "User does not exist" change_pw_url = "/imcrs/plat/operator/" f_url = url + change_pw_url + oper_id if password is None: password = input( '''\n ============ Please input the operators new password:\n ============ ''') payload = json.dumps({'password': password, 'authType': authtype}) response = requests.put(f_url, data=payload, auth=auth, headers=HEADERS) try: if response.status_code == 204: # print("Operator:" + operator + # " password was successfully changed") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' set_operator_password: An Error has occured'
Function to set the password of an existing operator :param operator: str Name of the operator account :param password: str New password :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: int of 204 if successfull, :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> operator = { "fullName" : "test administrator", "sessionTimeout" : "30", "password" : "password","operatorGroupId" : "1", "name" : "testadmin","desc" : "test admin account", "defaultAcl" : "","authType" : "0"} >>> new_operator = create_operator(operator, auth.creds, auth.url) >>> set_new_password = set_operator_password('testadmin', 'newpassword', auth.creds, auth.url) >>> assert type(set_new_password) is int >>> assert set_new_password == 204
entailment
def get_plat_operator(auth, url): """ Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC system :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element represents one operator :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> plat_operators = get_plat_operator(auth.creds, auth.url) >>> assert type(plat_operators) is list >>> assert 'name' in plat_operators[0] """ f_url = url + '/imcrs/plat/operator?start=0&size=1000&orderBy=id&desc=false&total=false' try: response = requests.get(f_url, auth=auth, headers=HEADERS) plat_oper_list = json.loads(response.text)['operator'] if isinstance(plat_oper_list, dict): oper_list = [plat_oper_list] return oper_list return plat_oper_list except requests.exceptions.RequestException as error: print("Error:\n" + str(error) + ' get_plat_operator: An Error has occured') return "Error:\n" + str(error) + ' get_plat_operator: An Error has occured'
Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC system :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element represents one operator :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> plat_operators = get_plat_operator(auth.creds, auth.url) >>> assert type(plat_operators) is list >>> assert 'name' in plat_operators[0]
entailment
def delete_plat_operator(operator, auth, url): """ Function to set the password of an existing operator :param operator: str Name of the operator account :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: int of 204 if successfull :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> success_delete_operator = delete_plat_operator('testadmin', auth.creds, auth.url) >>> assert type(success_delete_operator) is int >>> assert success_delete_operator == 204 >>> fail_delete_operator = delete_plat_operator('testadmin', auth.creds, auth.url) >>> assert type(fail_delete_operator) is int >>> assert fail_delete_operator == 409 """ oper_id = None plat_oper_list = get_plat_operator(auth, url) for i in plat_oper_list: if operator == i['name']: oper_id = i['id'] else: oper_id = None if oper_id is None: # print ("User does not exist") return 409 f_url = url + "/imcrs/plat/operator/" + str(oper_id) response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: # print("Operator: " + operator + # " was successfully deleted") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' delete_plat_operator: An Error has occured'
Function to set the password of an existing operator :param operator: str Name of the operator account :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: int of 204 if successfull :rtype: int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.operator import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> success_delete_operator = delete_plat_operator('testadmin', auth.creds, auth.url) >>> assert type(success_delete_operator) is int >>> assert success_delete_operator == 204 >>> fail_delete_operator = delete_plat_operator('testadmin', auth.creds, auth.url) >>> assert type(fail_delete_operator) is int >>> assert fail_delete_operator == 409
entailment
def execute_request(self, url, http_method, query_params, post_data): """Makes a request to the specified url endpoint with the specified http method, params and post data. Args: url (string): The url to the API without query params. Example: "https://api.housecanary.com/v2/property/value" http_method (string): The http method to use for the request. query_params (dict): Dictionary of query params to add to the request. post_data: Json post data to send in the body of the request. Returns: The result of calling this instance's OutputGenerator process_response method on the requests.Response object. If no OutputGenerator is specified for this instance, returns the requests.Response. """ response = requests.request(http_method, url, params=query_params, auth=self._auth, json=post_data, headers={'User-Agent': USER_AGENT}) if isinstance(self._output_generator, str) and self._output_generator.lower() == "json": # shortcut for just getting json back return response.json() elif self._output_generator is not None: return self._output_generator.process_response(response) else: return response
Makes a request to the specified url endpoint with the specified http method, params and post data. Args: url (string): The url to the API without query params. Example: "https://api.housecanary.com/v2/property/value" http_method (string): The http method to use for the request. query_params (dict): Dictionary of query params to add to the request. post_data: Json post data to send in the body of the request. Returns: The result of calling this instance's OutputGenerator process_response method on the requests.Response object. If no OutputGenerator is specified for this instance, returns the requests.Response.
entailment
def post(self, url, post_data, query_params=None): """Makes a POST request to the specified url endpoint. Args: url (string): The url to the API without query params. Example: "https://api.housecanary.com/v2/property/value" post_data: Json post data to send in the body of the request. query_params (dict): Optional. Dictionary of query params to add to the request. Returns: The result of calling this instance's OutputGenerator process_response method on the requests.Response object. If no OutputGenerator is specified for this instance, returns the requests.Response. """ if query_params is None: query_params = {} return self.execute_request(url, "POST", query_params, post_data)
Makes a POST request to the specified url endpoint. Args: url (string): The url to the API without query params. Example: "https://api.housecanary.com/v2/property/value" post_data: Json post data to send in the body of the request. query_params (dict): Optional. Dictionary of query params to add to the request. Returns: The result of calling this instance's OutputGenerator process_response method on the requests.Response object. If no OutputGenerator is specified for this instance, returns the requests.Response.
entailment
def import_custom_views(filename): """ Function which takes in a csv files as input to the create_custom_views function from the pyhpeimc python module available at https://github.com/HPNetworking/HP-Intelligent-Management-Center :param filename: user-defined filename which contains two column named "name" and "upperview" as input into the create_custom_views function from the pyhpeimc module. :return: returns output of the create_custom_vies function (str) for each item in the CSV file. """ with open(filename) as csvfile: # decodes file as csv as a python dictionary reader = csv.DictReader(csvfile) for view in reader: # loads each row of the CSV as a JSON string name = view['name'] upperview = view['upperview'] if len(upperview) is 0: upperview = None create_custom_views(name,upperview,auth=auth.creds, url=auth.url)
Function which takes in a csv files as input to the create_custom_views function from the pyhpeimc python module available at https://github.com/HPNetworking/HP-Intelligent-Management-Center :param filename: user-defined filename which contains two column named "name" and "upperview" as input into the create_custom_views function from the pyhpeimc module. :return: returns output of the create_custom_vies function (str) for each item in the CSV file.
entailment
def get_real_time_locate(host_ipaddress, auth, url): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a partially discovered network or misconfigured environment. :param host_ipaddress: str value valid IPv4 IP address :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element of the list represents the location of the target host :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> found_device = get_real_time_locate('10.101.0.51', auth.creds, auth.url) >>> assert type(found_device) is list >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> no_device = get_real_time_locate('192.168.254.254', auth.creds, auth.url) >>> assert type(no_device) is dict >>> assert len(no_device) == 0 """ f_url = url + "/imcrs/res/access/realtimeLocate?type=2&value=" + str(host_ipaddress) + \ "&total=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: response = json.loads(response.text) if 'realtimeLocation' in response: real_time_locate = response['realtimeLocation'] if isinstance(real_time_locate, dict): real_time_locate = [real_time_locate] return real_time_locate else: return json.loads(response)['realtimeLocation'] else: print("Host not found") return 403 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_real_time_locate: An Error has occured"
function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a partially discovered network or misconfigured environment. :param host_ipaddress: str value valid IPv4 IP address :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element of the list represents the location of the target host :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> found_device = get_real_time_locate('10.101.0.51', auth.creds, auth.url) >>> assert type(found_device) is list >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> no_device = get_real_time_locate('192.168.254.254', auth.creds, auth.url) >>> assert type(no_device) is dict >>> assert len(no_device) == 0
entailment
def get_ip_mac_arp_list(auth, url, devid=None, devip=None): """ function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: int or str value of the target device. :param devip: str of ipv4 address of the target device :return: list of dictionaries containing the IP/MAC/ARP list of the target device. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ip_mac_list = get_ip_mac_arp_list( auth.creds, auth.url, devid='10') >>> ip_mac_list = get_ip_mac_arp_list( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(ip_mac_list) is list >>> assert 'deviceId' in ip_mac_list[0] """ if devip is not None: dev_details = get_dev_details(devip, auth, url) if isinstance(dev_details, str): print("Device not found") return 403 else: devid = get_dev_details(devip, auth, url)['id'] f_url = url + "/imcrs/res/access/ipMacArp/" + str(devid) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: ipmacarplist = (json.loads(response.text)) if 'ipMacArp' in ipmacarplist: return ipmacarplist['ipMacArp'] else: return ['this function is unsupported'] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_ip_mac_arp_list: An Error has occured"
function takes devid of specific device and issues a RESTFUL call to get the IP/MAC/ARP list from the target device. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param devid: int or str value of the target device. :param devip: str of ipv4 address of the target device :return: list of dictionaries containing the IP/MAC/ARP list of the target device. :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ip_mac_list = get_ip_mac_arp_list( auth.creds, auth.url, devid='10') >>> ip_mac_list = get_ip_mac_arp_list( auth.creds, auth.url, devip='10.101.0.221') >>> assert type(ip_mac_list) is list >>> assert 'deviceId' in ip_mac_list[0]
entailment
def get_ip_scope(auth, url, scopeid=None, ): """ function requires no inputs and returns all IP address scopes currently configured on the HPE IMC server. If the optional scopeid parameter is included, this will automatically return only the desired scope id. :param scopeid: integer of the desired scope id ( optional ) :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionary objects where each element of the list represents one IP scope :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ip_scope_list = get_ip_scope(auth.creds, auth.url) >>> assert type(ip_scope_list) is list >>> assert 'ip' in ip_scope_list[0] """ if scopeid is None: get_ip_scope_url = "/imcrs/res/access/assignedIpScope" else: get_ip_scope_url = "/imcrs/res/access/assignedIpScope/ip?ipScopeId=" + str(scopeid) f_url = url + get_ip_scope_url response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: ipscopelist = (json.loads(response.text))['assignedIpScope'] if isinstance(ipscopelist, list): return ipscopelist elif isinstance(ipscopelist, dict): return [ipscopelist] except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_ip_scope: An Error has occured"
function requires no inputs and returns all IP address scopes currently configured on the HPE IMC server. If the optional scopeid parameter is included, this will automatically return only the desired scope id. :param scopeid: integer of the desired scope id ( optional ) :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionary objects where each element of the list represents one IP scope :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ip_scope_list = get_ip_scope(auth.creds, auth.url) >>> assert type(ip_scope_list) is list >>> assert 'ip' in ip_scope_list[0]
entailment
def add_ip_scope(name, description, auth, url, startip=None, endip=None, network_address=None): """ Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access in the HPE IMC base platform :param name: str Name of the owner of this IP scope ex. 'admin' :param description: str description of the Ip scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param startip: str Start of IP address scope ex. '10.101.0.1' :param endip: str End of IP address scope ex. '10.101.0.254' :param network_address: ipv4 network address + subnet bits of target scope :return: 200 if successfull :rtype: >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_ip_scope('10.50.0.0/24', auth.creds, auth.url) <Response [204]> >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> assert type(new_scope) is int >>> assert new_scope == 200 >>> existing_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> assert type(existing_scope) is int >>> assert existing_scope == 409 """ if network_address is not None: nw_address = ipaddress.IPv4Network(network_address) startip = nw_address[1] endip = nw_address[-2] f_url = url + "/imcrs/res/access/assignedIpScope" payload = ('''{ "startIp": "%s", "endIp": "%s","name": "%s","description": "%s" }''' % (str(startip), str(endip), str(name), str(description))) response = requests.post(f_url, auth=auth, headers=HEADERS, data=payload) try: if response.status_code == 200: # print("IP Scope Successfully Created") return response.status_code elif response.status_code == 409: # print ("IP Scope Already Exists") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " add_ip_scope: An Error has occured"
Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access in the HPE IMC base platform :param name: str Name of the owner of this IP scope ex. 'admin' :param description: str description of the Ip scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param startip: str Start of IP address scope ex. '10.101.0.1' :param endip: str End of IP address scope ex. '10.101.0.254' :param network_address: ipv4 network address + subnet bits of target scope :return: 200 if successfull :rtype: >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> delete_ip_scope('10.50.0.0/24', auth.creds, auth.url) <Response [204]> >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> assert type(new_scope) is int >>> assert new_scope == 200 >>> existing_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> assert type(existing_scope) is int >>> assert existing_scope == 409
entailment
def delete_ip_scope(network_address, auth, url): """ Function to delete an entire IP segment from the IMC IP Address management under terminal access :param network_address :param auth :param url >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> delete_scope = delete_ip_scope('10.50.0.0/24', auth.creds, auth.url) """ scope_id = get_scope_id(network_address, auth, url) if scope_id == "Scope Doesn't Exist": return scope_id f_url = url + '''/imcrs/res/access/assignedIpScope/''' + str(scope_id) response = requests.delete(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 204: # print("IP Segment Successfully Deleted") return 204 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " delete_ip_scope: An Error has occured"
Function to delete an entire IP segment from the IMC IP Address management under terminal access :param network_address :param auth :param url >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> delete_scope = delete_ip_scope('10.50.0.0/24', auth.creds, auth.url)
entailment
def add_scope_ip(hostipaddress, name, description, auth, url, scopeid=None, network_address=None): """ Function to add new host IP address allocation to existing scope ID :param hostipaddress: ipv4 address of the target host to be added to the target scope :param name: name of the owner of this host :param description: Description of the host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param scopeid: integer of the desired scope id ( optional ) :param network_address: ipv4 network address + subnet bits of target scope :return: :rtype: >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_host = add_scope_ip('10.50.0.5', 'cyoung', 'New Test Host','175', auth.creds, auth.url) """ if network_address is not None: scopeid = get_scope_id(network_address, auth, url) if scopeid == "Scope Doesn't Exist": return scopeid new_ip = {"ip": hostipaddress, "name": name, "description": description} f_url = url + '/imcrs/res/access/assignedIpScope/ip?ipScopeId=' + str(scopeid) payload = json.dumps(new_ip) response = requests.post(f_url, auth=auth, headers=HEADERS, data=payload) try: if response.status_code == 200: # print("IP Host Successfully Created") return response.status_code elif response.status_code == 409: # print("IP Host Already Exists") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " add_ip_scope: An Error has occured"
Function to add new host IP address allocation to existing scope ID :param hostipaddress: ipv4 address of the target host to be added to the target scope :param name: name of the owner of this host :param description: Description of the host :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param scopeid: integer of the desired scope id ( optional ) :param network_address: ipv4 network address + subnet bits of target scope :return: :rtype: >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_host = add_scope_ip('10.50.0.5', 'cyoung', 'New Test Host','175', auth.creds, auth.url)
entailment
def remove_scope_ip(hostid, auth, url): """ Function to add remove IP address allocation :param hostid: Host id of the host to be deleted :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: String of HTTP response code. Should be 204 is successfull :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> add_host_to_segment('10.50.0.5', 'cyoung', 'New Test Host', '10.50.0.0/24', auth.creds, auth.url) >>> host_id = get_host_id('10.50.0.5', '10.50.0.0/24', auth.creds, auth.url) >>> rem_host = remove_scope_ip(host_id, auth.creds, auth.url) >>> assert type(rem_host) is int >>> assert rem_host == 204 """ f_url = url + '/imcrs/res/access/assignedIpScope/ip/' + str(hostid) response = requests.delete(f_url, auth=auth, headers=HEADERS, ) try: if response.status_code == 204: # print("Host Successfully Deleted") return response.status_code elif response.status_code == 409: # print("IP Scope Already Exists") return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " add_ip_scope: An Error has occured"
Function to add remove IP address allocation :param hostid: Host id of the host to be deleted :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: String of HTTP response code. Should be 204 is successfull :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> new_scope = add_ip_scope('10.50.0.1', '10.50.0.254', 'cyoung', 'test group', auth.creds, auth.url) >>> add_host_to_segment('10.50.0.5', 'cyoung', 'New Test Host', '10.50.0.0/24', auth.creds, auth.url) >>> host_id = get_host_id('10.50.0.5', '10.50.0.0/24', auth.creds, auth.url) >>> rem_host = remove_scope_ip(host_id, auth.creds, auth.url) >>> assert type(rem_host) is int >>> assert rem_host == 204
entailment
def get_ip_scope_hosts(auth, url, scopeid=None, network_address=None): """ Function requires input of scope ID and returns list of allocated IP address for the specified scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param scopeid: Integer of the desired scope id :param network_address: ipv4 network address + subnet bits of target scope :return: list of dictionary objects where each element of the list represents a single host assigned to the IP scope :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> scope_id = get_scope_id('10.50.0.0/24', auth.creds, auth.url) >>> ip_scope_hosts = get_ip_scope_hosts(scope_id, auth.creds, auth.url) >>> assert type(ip_scope_hosts) is list >>> assert 'name' in ip_scope_hosts[0] >>> assert 'description' in ip_scope_hosts[0] >>> assert 'ip' in ip_scope_hosts[0] >>> assert 'id' in ip_scope_hosts[0] """ if network_address is not None: scopeid = get_scope_id(network_address, auth, url) if scopeid == "Scope Doesn't Exist": return scopeid f_url = url + "/imcrs/res/access/assignedIpScope/ip?size=10000&ipScopeId=" + str(scopeid) response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: ipscopelist = (json.loads(response.text)) if ipscopelist == {}: return [ipscopelist] else: ipscopelist = ipscopelist['assignedIpInfo'] if isinstance(ipscopelist, dict): ipscope = [ipscopelist] return ipscope return ipscopelist except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_ip_scope: An Error has occured"
Function requires input of scope ID and returns list of allocated IP address for the specified scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param scopeid: Integer of the desired scope id :param network_address: ipv4 network address + subnet bits of target scope :return: list of dictionary objects where each element of the list represents a single host assigned to the IP scope :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> scope_id = get_scope_id('10.50.0.0/24', auth.creds, auth.url) >>> ip_scope_hosts = get_ip_scope_hosts(scope_id, auth.creds, auth.url) >>> assert type(ip_scope_hosts) is list >>> assert 'name' in ip_scope_hosts[0] >>> assert 'description' in ip_scope_hosts[0] >>> assert 'ip' in ip_scope_hosts[0] >>> assert 'id' in ip_scope_hosts[0]
entailment
def delete_host_from_segment(hostipaddress, networkaddress, auth, url): """ :param hostipaddress: str ipv4 address of the target host to be deleted :param networkaddress: ipv4 network address + subnet bits of target scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: String of HTTP response code. Should be 204 is successfull :rtype: str """ host_id = get_host_id(hostipaddress, networkaddress, auth, url) delete_host = remove_scope_ip(host_id, auth, url) return delete_host
:param hostipaddress: str ipv4 address of the target host to be deleted :param networkaddress: ipv4 network address + subnet bits of target scope :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: String of HTTP response code. Should be 204 is successfull :rtype: str
entailment
def allow_attribute_comments(chain, node): """ This augmentation is to allow comments on class attributes, for example: class SomeClass(object): some_attribute = 5 ''' This is a docstring for the above attribute ''' """ # TODO: find the relevant citation for why this is the correct way to comment attributes if isinstance(node.previous_sibling(), astroid.Assign) and \ isinstance(node.parent, (astroid.Class, astroid.Module)) and \ isinstance(node.value, astroid.Const) and \ isinstance(node.value.value, BASESTRING): return chain()
This augmentation is to allow comments on class attributes, for example: class SomeClass(object): some_attribute = 5 ''' This is a docstring for the above attribute '''
entailment
def download(self, url, path, name_audio): """ Params: ::url = Comprises the url used to download the audio. ::path = Comprises the location where the file should be saved. ::name_audio = Is the name of the desired audio. Definition: Basically, we do a get with the requests module and after that we recorded in the desired location by the developer or user, depending on the occasion. """ if path is not None: with open(str(path+name_audio), 'wb') as handle: response = requests.get(url, stream = True) if not response.ok: raise Exception("Error in audio download.") for block in response.iter_content(1024): if not block: break handle.write(block)
Params: ::url = Comprises the url used to download the audio. ::path = Comprises the location where the file should be saved. ::name_audio = Is the name of the desired audio. Definition: Basically, we do a get with the requests module and after that we recorded in the desired location by the developer or user, depending on the occasion.
entailment
def get_dev_asset_details(ipaddress, auth, url): """Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API :param ipaddress: IP address of the device you wish to gather the asset details :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: object of type list containing the device asset details, with each asset contained in a dictionary :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url) >>> assert type(single_asset) is list >>> assert 'name' in single_asset[0] """ get_dev_asset_url = "/imcrs/netasset/asset?assetDevice.ip=" + str(ipaddress) f_url = url + get_dev_asset_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_asset_info = (json.loads(r.text)) if len(dev_asset_info) > 0: dev_asset_info = dev_asset_info['netAsset'] if type(dev_asset_info) == dict: dev_asset_info = [dev_asset_info] if type(dev_asset_info) == list: dev_asset_info[:] = [dev for dev in dev_asset_info if dev.get('deviceIp') == ipaddress] return dev_asset_info except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_asset_details: An Error has occured'
Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API :param ipaddress: IP address of the device you wish to gather the asset details :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: object of type list containing the device asset details, with each asset contained in a dictionary :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url) >>> assert type(single_asset) is list >>> assert 'name' in single_asset[0]
entailment
def get_dev_asset_details_all(auth, url): """Takes no input to fetch device assett details from HP IMC RESTFUL API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionatires containing the device asset details :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_assets = get_dev_asset_details_all( auth.creds, auth.url) >>> assert type(all_assets) is list >>> assert 'asset' in all_assets[0] """ get_dev_asset_details_all_url = "/imcrs/netasset/asset?start=0&size=15000" f_url = url + get_dev_asset_details_all_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_asset_info = (json.loads(r.text))['netAsset'] return dev_asset_info except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_dev_asset_details: An Error has occured'
Takes no input to fetch device assett details from HP IMC RESTFUL API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionatires containing the device asset details :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.netassets import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_assets = get_dev_asset_details_all( auth.creds, auth.url) >>> assert type(all_assets) is list >>> assert 'asset' in all_assets[0]
entailment
def check_database_connected(db): """ A built-in check to see if connecting to the configured default database backend succeeds. It's automatically added to the list of Dockerflow checks if a :class:`~flask_sqlalchemy.SQLAlchemy` object is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during instantiation, e.g.:: from flask import Flask from flask_sqlalchemy import SQLAlchemy from dockerflow.flask import Dockerflow app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) dockerflow = Dockerflow(app, db=db) """ from sqlalchemy.exc import DBAPIError, SQLAlchemyError errors = [] try: with db.engine.connect() as connection: connection.execute('SELECT 1;') except DBAPIError as e: msg = 'DB-API error: {!s}'.format(e) errors.append(Error(msg, id=health.ERROR_DB_API_EXCEPTION)) except SQLAlchemyError as e: msg = 'Database misconfigured: "{!s}"'.format(e) errors.append(Error(msg, id=health.ERROR_SQLALCHEMY_EXCEPTION)) return errors
A built-in check to see if connecting to the configured default database backend succeeds. It's automatically added to the list of Dockerflow checks if a :class:`~flask_sqlalchemy.SQLAlchemy` object is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during instantiation, e.g.:: from flask import Flask from flask_sqlalchemy import SQLAlchemy from dockerflow.flask import Dockerflow app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) dockerflow = Dockerflow(app, db=db)
entailment
def check_migrations_applied(migrate): """ A built-in check to see if all migrations have been applied correctly. It's automatically added to the list of Dockerflow checks if a `flask_migrate.Migrate <https://flask-migrate.readthedocs.io/>`_ object is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during instantiation, e.g.:: from flask import Flask from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from dockerflow.flask import Dockerflow app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) migrate = Migrate(app, db) dockerflow = Dockerflow(app, db=db, migrate=migrate) """ errors = [] from alembic.migration import MigrationContext from alembic.script import ScriptDirectory from sqlalchemy.exc import DBAPIError, SQLAlchemyError # pass in Migrate.directory here explicitly to be compatible with # older versions of Flask-Migrate that required the directory to be passed config = migrate.get_config(directory=migrate.directory) script = ScriptDirectory.from_config(config) try: with migrate.db.engine.connect() as connection: context = MigrationContext.configure(connection) db_heads = set(context.get_current_heads()) script_heads = set(script.get_heads()) except (DBAPIError, SQLAlchemyError) as e: msg = "Can't connect to database to check migrations: {!s}".format(e) return [Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)] if db_heads != script_heads: msg = "Unapplied migrations found: {}".format(', '.join(script_heads)) errors.append(Warning(msg, id=health.WARNING_UNAPPLIED_MIGRATION)) return errors
A built-in check to see if all migrations have been applied correctly. It's automatically added to the list of Dockerflow checks if a `flask_migrate.Migrate <https://flask-migrate.readthedocs.io/>`_ object is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during instantiation, e.g.:: from flask import Flask from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from dockerflow.flask import Dockerflow app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) migrate = Migrate(app, db) dockerflow = Dockerflow(app, db=db, migrate=migrate)
entailment
def check_redis_connected(client): """ A built-in check to connect to Redis using the given client and see if it responds to the ``PING`` command. It's automatically added to the list of Dockerflow checks if a :class:`~redis.StrictRedis` instances is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during instantiation, e.g.:: import redis from flask import Flask from dockerflow.flask import Dockerflow app = Flask(__name__) redis_client = redis.StrictRedis(host='localhost', port=6379, db=0) dockerflow = Dockerflow(app, redis=redis) An alternative approach to instantiating a Redis client directly would be using the `Flask-Redis <https://github.com/underyx/flask-redis>`_ Flask extension:: from flask import Flask from flask_redis import FlaskRedis from dockerflow.flask import Dockerflow app = Flask(__name__) app.config['REDIS_URL'] = 'redis://:password@localhost:6379/0' redis_store = FlaskRedis(app) dockerflow = Dockerflow(app, redis=redis_store) """ import redis errors = [] try: result = client.ping() except redis.ConnectionError as e: msg = 'Could not connect to redis: {!s}'.format(e) errors.append(Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS)) except redis.RedisError as e: errors.append(Error('Redis error: "{!s}"'.format(e), id=health.ERROR_REDIS_EXCEPTION)) else: if not result: errors.append(Error('Redis ping failed', id=health.ERROR_REDIS_PING_FAILED)) return errors
A built-in check to connect to Redis using the given client and see if it responds to the ``PING`` command. It's automatically added to the list of Dockerflow checks if a :class:`~redis.StrictRedis` instances is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during instantiation, e.g.:: import redis from flask import Flask from dockerflow.flask import Dockerflow app = Flask(__name__) redis_client = redis.StrictRedis(host='localhost', port=6379, db=0) dockerflow = Dockerflow(app, redis=redis) An alternative approach to instantiating a Redis client directly would be using the `Flask-Redis <https://github.com/underyx/flask-redis>`_ Flask extension:: from flask import Flask from flask_redis import FlaskRedis from dockerflow.flask import Dockerflow app = Flask(__name__) app.config['REDIS_URL'] = 'redis://:password@localhost:6379/0' redis_store = FlaskRedis(app) dockerflow = Dockerflow(app, redis=redis_store)
entailment
def get_custom_views(auth, url,name=None,headers=HEADERS): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :return: list of dictionaties containing attributes of the custom views """ if name is None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=false' elif name is not None: get_custom_view_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&name='+name+'&desc=false&total=false' f_url = url + get_custom_view_url r = requests.get(f_url, auth=auth, headers=headers) try: if r.status_code == 200: custom_view_list = (json.loads(r.text))["customView"] if type(custom_view_list) == dict: custom_view_list = [custom_view_list] return custom_view_list else: return custom_view_list except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_custom_views: An Error has occured'
function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :return: list of dictionaties containing attributes of the custom views
entailment
def create_custom_views(auth, url,name=None, upperview=None): """ function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views. """ create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false&total=false' f_url = url + create_custom_views_url if upperview is None: payload = '''{ "name": "''' + name + '''", "upLevelSymbolId" : ""}''' print (payload) else: parentviewid = get_custom_views(auth, url, upperview)[0]['symbolId'] payload = '''{ "name": "'''+name+ '''", "upLevelSymbolId" : "'''+str(parentviewid)+'''"}''' print (payload) r = requests.post(f_url, data = payload, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 201: return 'View ' + name +' created successfully' except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_custom_views: An Error has occured'
function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. Optioanl Name input will return only the specified view. :param name: string containg the name of the desired custom view :return: list of dictionaries containing attributes of the custom views.
entailment
def get_dev_run_config(devid, auth, url): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devid: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devid) + "/currentRun" f_url = url + get_dev_run_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # print (r.status_code) try: if r.status_code == 200: try: run_conf = (json.loads(r.text))['content'] return run_conf except: return "This features is no supported on this device" except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_run_config: An Error has occured"
function takes the devId of a specific device and issues a RESTFUL call to get the most current running config file as known by the HP IMC Base Platform ICC module for the target device. :param devid: int or str value of the target device :return: str which contains the entire content of the target device running configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device"
entailment
def get_dev_start_config(devId, auth, url): """ function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device" """ # checks to see if the imc credentials are already available get_dev_run_url = "/imcrs/icc/deviceCfg/" + str(devId) + "/currentStart" f_url = url + get_dev_run_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) try: if r.status_code == 200: try: start_conf = (json.loads(r.text))['content'] return start_conf except: return "Start Conf not supported on this device" except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_run_config: An Error has occured"
function takes the devId of a specific device and issues a RESTFUL call to get the most current startup config file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the target device :return: str which contains the entire content of the target device startup configuration. If the device is not currently supported in the HP IMC Base Platform ICC module, this call returns a string of "This feature is not supported on this device"
entailment
def set_inteface_up(devid, ifindex, auth, url): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values. """ set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up" f_url = url + set_int_up_url try: r = requests.put(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents if r.status_code == 204: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " set_inteface_up: An Error has occured"
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to "undo shut" the spec ified interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :return: HTTP status code 204 with no values.
entailment
def vfolders(access_key): ''' List and manage virtual folders. ''' fields = [ ('Name', 'name'), ('Created At', 'created_at'), ('Last Used', 'last_used'), ('Max Files', 'max_files'), ('Max Size', 'max_size'), ] if access_key is None: q = 'query { vfolders { $fields } }' else: q = 'query($ak:String) { vfolders(access_key:$ak) { $fields } }' q = q.replace('$fields', ' '.join(item[1] for item in fields)) v = {'ak': access_key} with Session() as session: try: resp = session.Admin.query(q, v) except Exception as e: print_error(e) sys.exit(1) print(tabulate((item.values() for item in resp['vfolders']), headers=(item[0] for item in fields)))
List and manage virtual folders.
entailment
def config(): ''' Shows the current configuration. ''' config = get_config() print('Client version: {0}'.format(click.style(__version__, bold=True))) print('API endpoint: {0}'.format(click.style(str(config.endpoint), bold=True))) print('API version: {0}'.format(click.style(config.version, bold=True))) print('Access key: "{0}"'.format(click.style(config.access_key, bold=True))) masked_skey = config.secret_key[:6] + ('*' * 24) + config.secret_key[-10:] print('Secret key: "{0}"'.format(click.style(masked_skey, bold=True))) print('Signature hash type: {0}'.format( click.style(config.hash_type, bold=True))) print('Skip SSL certificate validation? {0}'.format( click.style(str(config.skip_sslcert_validation), bold=True)))
Shows the current configuration.
entailment
def get_system_vendors(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single vendor :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> vendors = get_system_vendors(auth.creds, auth.url) >>> assert type(vendors) is list >>> assert 'name' in vendors[0] """ get_system_vendors_url = '/imcrs/plat/res/vendor?start=0&size=10000&orderBy=id&desc=false&total=false' f_url = url + get_system_vendors_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: system_vendors = (json.loads(r.text)) return system_vendors['deviceVendor'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single vendor :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> vendors = get_system_vendors(auth.creds, auth.url) >>> assert type(vendors) is list >>> assert 'name' in vendors[0]
entailment
def get_system_category(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single device category :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> categories = get_system_category(auth.creds, auth.url) >>> assert type(categories) is list >>> assert 'name' in categories[0] """ get_system_category_url = '/imcrs/plat/res/category?start=0&size=10000&orderBy=id&desc=false&total=false' f_url = url + get_system_category_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: system_category = (json.loads(r.text)) return system_category['deviceCategory'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single device category :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> categories = get_system_category(auth.creds, auth.url) >>> assert type(categories) is list >>> assert 'name' in categories[0]
entailment
def get_system_device_models(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single device model :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> device_models = get_system_device_models(auth.creds, auth.url) >>> assert type(device_models) is list >>> assert 'virtualDeviceName' in device_models[0] """ get_system_device_model_url = '/imcrs/plat/res/model?start=0&size=10000&orderBy=id&desc=false&total=false' f_url = url + get_system_device_model_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: system_device_model = (json.loads(r.text)) return system_device_model['deviceModel'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single device model :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> device_models = get_system_device_models(auth.creds, auth.url) >>> assert type(device_models) is list >>> assert 'virtualDeviceName' in device_models[0]
entailment
def get_system_series(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single device series :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> series = get_system_series(auth.creds, auth.url) >>> assert type(series) is list >>> assert 'name' in series[0] """ get_system_series_url = '/imcrs/plat/res/series?managedOnly=false&start=0&size=10000&orderBy=id&desc=false&total=false' f_url = url + get_system_series_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: system_series = (json.loads(r.text)) return system_series['deviceSeries'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_series: An Error has occured"
Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each dictionary represents a single device series :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> series = get_system_series(auth.creds, auth.url) >>> assert type(series) is list >>> assert 'name' in series[0]
entailment
def get_all_devs(auth, url, network_address= None): """Takes string input of IP address to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param network_address= str IPv4 Network Address :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.') >>> assert type(dev_list) is list >>> assert 'sysName' in dev_list[0] """ if network_address != None: get_all_devs_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \ str(network_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false" else: get_all_devs_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&start=0&size=1000&orderBy=id&desc=false&total=false&exact=false" f_url = url + get_all_devs_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_details = (json.loads(r.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" else: return dev_details['device'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
Takes string input of IP address to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param network_address= str IPv4 Network Address :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.') >>> assert type(dev_list) is list >>> assert 'sysName' in dev_list[0]
entailment
def get_dev_details(ip_address, auth, url): """Takes string input of IP address to issue RESTUL call to HP IMC\n :param ip_address: string object of dotted decimal notation of IPv4 address :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url) >>> assert type(dev_1) is dict >>> assert 'sysName' in dev_1 >>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url) Device not found >>> assert type(dev_2) is str """ get_dev_details_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \ str(ip_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false" f_url = url + get_dev_details_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_details = (json.loads(r.text)) if len(dev_details) == 0: print("Device not found") return "Device not found" elif type(dev_details['device']) == list: for i in dev_details['device']: if i['ip'] == ip_address: dev_details = i return dev_details elif type(dev_details['device']) == dict: return dev_details['device'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
Takes string input of IP address to issue RESTUL call to HP IMC\n :param ip_address: string object of dotted decimal notation of IPv4 address :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: dictionary of device details :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url) >>> assert type(dev_1) is dict >>> assert 'sysName' in dev_1 >>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url) Device not found >>> assert type(dev_2) is str
entailment
def get_dev_interface(devid, auth, url): """ Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: requires devid as the only input :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list object which contains a dictionary per interface :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_interfaces = get_dev_interface('15', auth.creds, auth.url) >>> assert type(dev_interfaces) is list >>> assert 'ifAlias' in dev_interfaces[0] """ get_dev_interface_url = "/imcrs/plat/res/device/" + str(devid) + \ "/interface?start=0&size=1000&desc=false&total=false" f_url = url + get_dev_interface_url # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: int_list = (json.loads(r.text))['interface'] return int_list except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_interface: An Error has occured"
Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device interfaces :param devid: requires devid as the only input :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list object which contains a dictionary per interface :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_interfaces = get_dev_interface('15', auth.creds, auth.url) >>> assert type(dev_interfaces) is list >>> assert 'ifAlias' in dev_interfaces[0]
entailment
def get_dev_mac_learn(devid, auth, url): ''' function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn('10', auth.creds, auth.url) >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0] ''' get_dev_mac_learn_url='/imcrs/res/access/ipMacLearn/'+str(devid) f_url = url+get_dev_mac_learn_url try: r = requests.get(f_url, auth=auth, headers=HEADERS) if r.status_code == 200: if len(r.text) < 1: mac_learn_query = {} return mac_learn_query else: mac_learn_query = (json.loads(r.text))['ipMacLearnResult'] return mac_learn_query except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_dev_mac_learn: An Error has occured"
function takes devid of specific device and issues a RESTFUL call to gather the current IP-MAC learning entries on the target device. :param devid: int value of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict objects which contain the mac learn table of target device id :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_mac_learn = get_dev_mac_learn('10', auth.creds, auth.url) >>> assert type(dev_mac_learn) is list >>> assert 'deviceId' in dev_mac_learn[0]
entailment
def run_dev_cmd(devid, cmd_list, auth, url): ''' Function takes devid of target device and a sequential list of strings which define the specific commands to be run on the target device and returns a str object containing the output of the commands. :param devid: int devid of the target device :param cmd_list: list of strings :return: str containing the response of the commands >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> cmd_list = ['display version'] >>> cmd_output = run_dev_cmd('10', cmd_list, auth.creds, auth.url) >>> assert type(cmd_output) is dict >>> assert 'cmdlist' in cmd_output >>> assert 'success' in cmd_output ''' run_dev_cmd_url = '/imcrs/icc/confFile/executeCmd' f_url = url + run_dev_cmd_url cmd_list = _make_cmd_list(cmd_list) payload = '''{ "deviceId" : "'''+str(devid) + '''", "cmdlist" : { "cmd" : ['''+ cmd_list + '''] } }''' r = requests.post(f_url, data=payload, auth=auth, headers=HEADERS) if r.status_code == 200: if len(r.text) < 1: return '' else: return json.loads(r.text)
Function takes devid of target device and a sequential list of strings which define the specific commands to be run on the target device and returns a str object containing the output of the commands. :param devid: int devid of the target device :param cmd_list: list of strings :return: str containing the response of the commands >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> cmd_list = ['display version'] >>> cmd_output = run_dev_cmd('10', cmd_list, auth.creds, auth.url) >>> assert type(cmd_output) is dict >>> assert 'cmdlist' in cmd_output >>> assert 'success' in cmd_output
entailment
def get_all_interface_details(devId, auth, url): """ function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the devId of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict objects which contains the details of all interfaces on the target device :retype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_interface_details = get_all_interface_details('10', auth.creds, auth.url) >>> assert type(all_interface_details) is list >>> assert 'ifAlias' in all_interface_details[0] """ get_all_interface_details_url = "/imcrs/plat/res/device/" + str(devId) + "/interface/?start=0&size=1000&desc=false&total=false" f_url = url + get_all_interface_details_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_details = (json.loads(r.text)) return dev_details['interface'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_interface_details: An Error has occured"
function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the devId of the target device :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict objects which contains the details of all interfaces on the target device :retype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_interface_details = get_all_interface_details('10', auth.creds, auth.url) >>> assert type(all_interface_details) is list >>> assert 'ifAlias' in all_interface_details[0]
entailment
def get_interface_details(devId, ifIndex, auth, url): """ function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the devId of the target device :param ifIndex: int or str value of the ifIndex of the target interface :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: dict which contains the details of the target interface" :retype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> interface_details = get_interface_details('10', '1', auth.creds, auth.url) >>> assert type(interface_details) is dict >>> assert 'ifAlias' in interface_details """ get_interface_details_url = "/imcrs/plat/res/device/" + str(devId) + "/interface/" + str(ifIndex) f_url = url + get_interface_details_url payload = None # creates the URL using the payload variable as the contents r = requests.get(f_url, auth=auth, headers=HEADERS) # r.status_code try: if r.status_code == 200: dev_details = (json.loads(r.text)) return dev_details except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_interface_details: An Error has occured"
function takes the devId of a specific device and the ifindex value assigned to a specific interface and issues a RESTFUL call to get the interface details file as known by the HP IMC Base Platform ICC module for the target device. :param devId: int or str value of the devId of the target device :param ifIndex: int or str value of the ifIndex of the target interface :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: dict which contains the details of the target interface" :retype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> interface_details = get_interface_details('10', '1', auth.creds, auth.url) >>> assert type(interface_details) is dict >>> assert 'ifAlias' in interface_details
entailment
def set_interface_down(devid, ifindex, auth, url): """ function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP status code 204 with no values. :rtype:int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_down_response = set_interface_down('10', '9', auth.creds, auth.url) 204 >>> assert type(int_down_response) is int >>> assert int_down_response is 204 """ set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/down" f_url = url + set_int_down_url try: r = requests.put(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents print(r.status_code) if r.status_code == 204: return r.status_code except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " set_inteface_down: An Error has occured"
function takest devid and ifindex of specific device and interface and issues a RESTFUL call to " shut" the specifie d interface on the target device. :param devid: int or str value of the target device :param ifindex: int or str value of the target interface :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: HTTP status code 204 with no values. :rtype:int >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.device import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> int_down_response = set_interface_down('10', '9', auth.creds, auth.url) 204 >>> assert type(int_down_response) is int >>> assert int_down_response is 204
entailment
async def create(cls, name: str, default_for_unspecified: int, total_resource_slots: int, max_concurrent_sessions: int, max_containers_per_session: int, max_vfolder_count: int, max_vfolder_size: int, idle_timeout: int, allowed_vfolder_hosts: Sequence[str], fields: Iterable[str] = None) -> dict: """ Creates a new keypair resource policy with the given options. You need an admin privilege for this operation. """ if fields is None: fields = ('name',) q = 'mutation($name: String!, $input: CreateKeyPairResourcePolicyInput!) {' \ + \ ' create_keypair_resource_policy(name: $name, props: $input) {' \ ' ok msg resource_policy { $fields }' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) variables = { 'name': name, 'input': { 'default_for_unspecified': default_for_unspecified, 'total_resource_slots': total_resource_slots, 'max_concurrent_sessions': max_concurrent_sessions, 'max_containers_per_session': max_containers_per_session, 'max_vfolder_count': max_vfolder_count, 'max_vfolder_size': max_vfolder_size, 'idle_timeout': idle_timeout, 'allowed_vfolder_hosts': allowed_vfolder_hosts, }, } rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, 'variables': variables, }) async with rqst.fetch() as resp: data = await resp.json() return data['create_keypair_resource_policy']
Creates a new keypair resource policy with the given options. You need an admin privilege for this operation.
entailment
async def list(cls, fields: Iterable[str] = None) -> Sequence[dict]: ''' Lists the keypair resource policies. You need an admin privilege for this operation. ''' if fields is None: fields = ( 'name', 'created_at', 'total_resource_slots', 'max_concurrent_sessions', 'max_vfolder_count', 'max_vfolder_size', 'idle_timeout', ) q = 'query {' \ ' keypair_resource_policies {' \ ' $fields' \ ' }' \ '}' q = q.replace('$fields', ' '.join(fields)) rqst = Request(cls.session, 'POST', '/admin/graphql') rqst.set_json({ 'query': q, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypair_resource_policies']
Lists the keypair resource policies. You need an admin privilege for this operation.
entailment