text
stringlengths 81
112k
|
---|
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.
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)
|
Params:
::text = Text for identify language.
Returns:
Returns language present on text.
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:
::texts = Array of texts for detect languages
Returns:
Returns language present on array of text.
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)
|
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.
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 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".
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)
|
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
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"
|
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
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'
|
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:
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'
|
Args:
value: index
Returns: index of the values
Raises:
ValueError: value is not in list
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: 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
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
|
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
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"
|
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
>>>
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"
|
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
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"
|
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'
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"
|
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
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"
|
Wraps the given text with bold enable/disable ANSI sequences.
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))
|
Returns the current status of the configured API server.
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()
|
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.
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
|
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
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'
|
Upload files to user's home folder.
\b
SESSID: Session ID or its alias given when creating the session.
FILES: Path to upload.
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)
|
Download files from a running container.
\b
SESSID: Session ID or its alias given when creating the session.
FILES: Paths inside container.
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)
|
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.
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)
|
Main function.
:return:
None.
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
|
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
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"
|
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
>>>
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"
|
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
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 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
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"
|
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)
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
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
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"
|
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
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 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)
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 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
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 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.
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 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.
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 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
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 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
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'
|
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]
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'
|
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
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'
|
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.
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 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.
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)
|
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.
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 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
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 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]
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 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]
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 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
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 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)
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 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)
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 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
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 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]
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"
|
: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
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
|
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 '''
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()
|
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.
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)
|
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]
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 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]
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'
|
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)
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 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)
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 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)
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
|
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
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 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.
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 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"
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 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"
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 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.
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"
|
List and manage virtual folders.
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)))
|
Shows the current configuration.
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)))
|
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]
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 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]
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 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]
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 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]
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 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]
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 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
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"
|
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]
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 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]
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 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
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 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]
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 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
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 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
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"
|
Creates a new keypair resource policy with the given options.
You need an admin privilege for this operation.
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']
|
Lists the keypair resource policies.
You need an admin privilege for this operation.
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']
|
Show the server-side information of the currently configured access key.
def keypair():
'''
Show the server-side information of the currently configured access key.
'''
fields = [
('User ID', 'user_id'),
('Access Key', 'access_key'),
('Secret Key', 'secret_key'),
('Active?', 'is_active'),
('Admin?', 'is_admin'),
('Created At', 'created_at'),
('Last Used', 'last_used'),
('Res.Policy', 'resource_policy'),
('Rate Limit', 'rate_limit'),
('Concur.Limit', 'concurrency_limit'),
('Concur.Used', 'concurrency_used'),
]
with Session() as session:
try:
kp = session.KeyPair(session.config.access_key)
info = kp.info(fields=(item[1] for item in fields))
except Exception as e:
print_error(e)
sys.exit(1)
rows = []
for name, key in fields:
rows.append((name, info[key]))
print(tabulate(rows, headers=('Field', 'Value')))
|
List and manage keypairs.
To show all keypairs or other user's, your access key must have the admin
privilege.
(admin privilege required)
def keypairs(ctx, user_id, is_active):
'''
List and manage keypairs.
To show all keypairs or other user's, your access key must have the admin
privilege.
(admin privilege required)
'''
if ctx.invoked_subcommand is not None:
return
fields = [
('User ID', 'user_id'),
('Access Key', 'access_key'),
('Secret Key', 'secret_key'),
('Active?', 'is_active'),
('Admin?', 'is_admin'),
('Created At', 'created_at'),
('Last Used', 'last_used'),
('Res.Policy', 'resource_policy'),
('Rate Limit', 'rate_limit'),
('Concur.Limit', 'concurrency_limit'),
('Concur.Used', 'concurrency_used'),
]
try:
user_id = int(user_id)
except (TypeError, ValueError):
pass # string-based user ID for Backend.AI v1.4+
with Session() as session:
try:
items = session.KeyPair.list(user_id, is_active,
fields=(item[1] for item in fields))
except Exception as e:
print_error(e)
sys.exit(1)
if len(items) == 0:
print('There are no matching keypairs associated '
'with the user ID {0}'.format(user_id))
return
print(tabulate((item.values() for item in items),
headers=(item[0] for item in fields)))
|
Add a new keypair.
USER_ID: User ID of a new key pair.
RESOURCE_POLICY: resource policy for new key pair.
def add(user_id, resource_policy, admin, inactive, rate_limit):
'''
Add a new keypair.
USER_ID: User ID of a new key pair.
RESOURCE_POLICY: resource policy for new key pair.
'''
try:
user_id = int(user_id)
except ValueError:
pass # string-based user ID for Backend.AI v1.4+
with Session() as session:
try:
data = session.KeyPair.create(
user_id,
is_active=not inactive,
is_admin=admin,
resource_policy=resource_policy,
rate_limit=rate_limit)
except Exception as e:
print_error(e)
sys.exit(1)
if not data['ok']:
print_fail('KeyPair creation has failed: {0}'.format(data['msg']))
sys.exit(1)
item = data['keypair']
print('Access Key: {0}'.format(item['access_key']))
print('Secret Key: {0}'.format(item['secret_key']))
|
Update an existing keypair.
ACCESS_KEY: Access key of an existing key pair.
def update(access_key, resource_policy, is_admin, is_active, rate_limit):
'''
Update an existing keypair.
ACCESS_KEY: Access key of an existing key pair.
'''
with Session() as session:
try:
data = session.KeyPair.update(
access_key,
is_active=is_active,
is_admin=is_admin,
resource_policy=resource_policy,
rate_limit=rate_limit)
except Exception as e:
print_error(e)
sys.exit(1)
if not data['ok']:
print_fail('KeyPair creation has failed: {0}'.format(data['msg']))
sys.exit(1)
print('Key pair is updated: ' + access_key + '.')
|
Delete an existing keypair.
ACCESSKEY: ACCESSKEY for a keypair to delete.
def delete(access_key):
"""
Delete an existing keypair.
ACCESSKEY: ACCESSKEY for a keypair to delete.
"""
with Session() as session:
try:
data = session.KeyPair.delete(access_key)
except Exception as e:
print_error(e)
sys.exit(1)
if not data['ok']:
print_fail('KeyPair deletion has failed: {0}'.format(data['msg']))
sys.exit(1)
print('Key pair is deleted: ' + access_key + '.')
|
perform API auth test returning user and team
def login(self):
""" perform API auth test returning user and team """
log.debug('performing auth test')
test = self._get(urls['test'])
user = User({ 'name': test['user'], 'id': test['user_id'] })
self._refresh()
return test['team'], user
|
Return User object for a given Slack ID or name
def user(self, match):
""" Return User object for a given Slack ID or name """
if len(match) == 9 and match[0] == 'U':
return self._lookup(User, 'id', match)
return self._lookup(User, 'name', match)
|
Return Channel object for a given Slack ID or name
def channel(self, match):
""" Return Channel object for a given Slack ID or name """
if len(match) == 9 and match[0] in ('C','G','D'):
return self._lookup(Channel, 'id', match)
return self._lookup(Channel, 'name', match)
|
refresh internal directory cache
def _refresh(self):
""" refresh internal directory cache """
log.debug('refreshing directory cache')
self._users.update(list(self._user_gen()))
self._channels.update(list(self._channel_gen()))
|
lookup object in directory with attribute matching value
def match(self, attr, val):
""" lookup object in directory with attribute matching value """
self._lock.acquire()
try:
for x in self:
if getattr(x, attr) == val:
return x
finally:
self._lock.release()
|
Collect data into fixed-length chunks or blocks.
def _groups_of_size(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks."""
# _groups_of_size('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return zip_longest(fillvalue=fillvalue, *args)
|
Turn things like `slice(None, 2, -1)` into `:2:-1`.
def slice_repr(slice_instance):
"""
Turn things like `slice(None, 2, -1)` into `:2:-1`.
"""
if not isinstance(slice_instance, slice):
raise TypeError('Unhandled type {}'.format(type(slice_instance)))
start = slice_instance.start or ''
stop = slice_instance.stop or ''
step = slice_instance.step or ''
msg = '{}:'.format(start)
if stop:
msg += '{}'.format(stop)
if step:
msg += ':'
if step:
msg += '{}'.format(step)
return msg
|
A function that lazily evaluates a biggus.Chunk. This is useful for
passing through as a dask task so that we don't have to compute the
chunk in order to compute the graph.
def biggus_chunk(chunk_key, biggus_array, masked):
"""
A function that lazily evaluates a biggus.Chunk. This is useful for
passing through as a dask task so that we don't have to compute the
chunk in order to compute the graph.
"""
if masked:
array = biggus_array.masked_array()
else:
array = biggus_array.ndarray()
return biggus._init.Chunk(chunk_key, array)
|
Produce task graph entries for an array that comes from a biggus
StreamsHandler.
This is essentially every type of array that isn't already a thing on
disk/in-memory. StreamsHandler arrays include all aggregations and
elementwise operations.
def _make_stream_handler_nodes(self, dsk_graph, array, iteration_order,
masked):
"""
Produce task graph entries for an array that comes from a biggus
StreamsHandler.
This is essentially every type of array that isn't already a thing on
disk/in-memory. StreamsHandler arrays include all aggregations and
elementwise operations.
"""
nodes = {}
handler = array.streams_handler(masked)
input_iteration_order = handler.input_iteration_order(iteration_order)
def input_keys_transform(input_array, keys):
if hasattr(input_array, 'streams_handler'):
handler = input_array.streams_handler(masked)
# Get the transformer of the input array, and apply it to the
# keys.
input_transformer = getattr(handler,
'output_keys', None)
if input_transformer is not None:
keys = input_transformer(keys)
return keys
sources_keys = []
sources_chunks = []
for input_array in array.sources:
# Bring together all chunks that influence the same part of this
# (resultant) array.
source_chunks_by_key = {}
sources_chunks.append(source_chunks_by_key)
source_keys = []
sources_keys.append(source_keys)
# Make nodes for the source arrays (if they don't already exist)
# before we do anything else.
input_nodes = self._make_nodes(dsk_graph, input_array,
input_iteration_order, masked)
for chunk_id, task in input_nodes.items():
chunk_keys = task[1]
t_keys = chunk_keys
t_keys = input_keys_transform(array, t_keys)
source_keys.append(t_keys)
this_key = str(t_keys)
source_chunks_by_key.setdefault(this_key,
[]).append([chunk_id, task])
sources_keys_grouped = key_grouper.group_keys(array.shape,
*sources_keys)
for slice_group, sources_keys_group in sources_keys_grouped.items():
# Each group is entirely independent and can have its own task
# without knowledge of results from items in other groups.
t_keys = tuple(slice(*slice_tuple) for slice_tuple in slice_group)
all_chunks = []
for source_keys, source_chunks_by_key in zip(sources_keys_group,
sources_chunks):
dependencies = tuple(
the_id
for keys in source_keys
for the_id, task in source_chunks_by_key[str(keys)])
# Uniquify source_keys, but keep the order.
dependencies = tuple(_unique_everseen(dependencies))
def normalize_keys(keys, shape):
result = []
for key, dim_length in zip(keys, shape):
result.append(key_grouper.normalize_slice(key,
dim_length))
return tuple(result)
# If we don't have the same chunks for all inputs then we
# should combine them before passing them on to the handler.
# TODO: Fix slice equality to deal with 0 and None etc.
if not all(t_keys == normalize_keys(keys, array.shape)
for keys in source_keys):
combined = self.collect(array[t_keys], masked, chunk=True)
new_task = (combined, ) + dependencies
new_id = ('chunk shape: {}\n\n{}'
''.format(array[t_keys].shape, uuid.uuid()))
dsk_graph[new_id] = new_task
dependencies = (new_id, )
all_chunks.append(dependencies)
pivoted = all_chunks
sub_array = array[t_keys]
handler = sub_array.streams_handler(masked)
name = getattr(handler, 'nice_name', handler.__class__.__name__)
if hasattr(handler, 'axis'):
name += '\n(axis={})'.format(handler.axis)
# For ElementwiseStreams handlers, use the function that they wrap
# (e.g "add")
if hasattr(handler, 'operator'):
name = handler.operator.__name__
n_sources = len(array.sources)
handler_of_chunks_fn = self.create_chunks_handler_fn(handler,
n_sources,
name)
shape = sub_array.shape
if all(key == slice(None) for key in t_keys):
subset = ''
else:
pretty_index = ', '.join(map(slice_repr, t_keys))
subset = 'target subset [{}]\n'.format(pretty_index)
# Flatten out the pivot so that dask can dereferences the IDs
source_chunks = [item for sublist in pivoted for item in sublist]
task = tuple([handler_of_chunks_fn, t_keys] + source_chunks)
shape_repr = ', '.join(map(str, shape))
chunk_id = 'chunk shape: ({})\n\n{}{}'.format(shape_repr,
subset,
uuid.uuid4())
assert chunk_id not in dsk_graph
dsk_graph[chunk_id] = task
nodes[chunk_id] = task
return nodes
|
Create a lazy chunk creating function with a nice name that is suitable
for representation in a dask graph.
def lazy_chunk_creator(name):
"""
Create a lazy chunk creating function with a nice name that is suitable
for representation in a dask graph.
"""
# TODO: Could this become a LazyChunk class?
def biggus_chunk(chunk_key, biggus_array, masked):
"""
A function that lazily evaluates a biggus.Chunk. This is useful for
passing through as a dask task so that we don't have to compute the
chunk in order to compute the graph.
"""
if masked:
array = biggus_array.masked_array()
else:
array = biggus_array.ndarray()
return biggus._init.Chunk(chunk_key, array)
biggus_chunk.__name__ = name
return biggus_chunk
|
Recursive function that returns the dask items for the given array.
NOTE: Currently assuming that all tasks are a tuple, with the second
item being the keys used to index the source of the respective input
array.
def _make_nodes(self, dsk_graph, array, iteration_order, masked,
top=False):
"""
Recursive function that returns the dask items for the given array.
NOTE: Currently assuming that all tasks are a tuple, with the second
item being the keys used to index the source of the respective input
array.
"""
cache_key = _array_id(array, iteration_order, masked)
# By the end of this function Nodes will be a dictionary with one item
# per chunk to be processed for this array.
nodes = self._node_cache.get(cache_key, None)
if nodes is None:
if hasattr(array, 'streams_handler'):
nodes = self._make_stream_handler_nodes(dsk_graph, array,
iteration_order,
masked)
else:
nodes = {}
chunks = []
name = '{}\n{}'.format(array.__class__.__name__, array.shape)
biggus_chunk_func = self.lazy_chunk_creator(name)
chunk_index_gen = biggus._init.ProducerNode.chunk_index_gen
for chunk_key in chunk_index_gen(array.shape,
iteration_order[::-1]):
biggus_array = array[chunk_key]
pretty_key = ', '.join(map(slice_repr, chunk_key))
chunk_id = ('chunk shape: {}\nsource key: [{}]\n\n{}'
''.format(biggus_array.shape, pretty_key,
uuid.uuid4()))
task = (biggus_chunk_func, chunk_key, biggus_array, masked)
chunks.append(task)
assert chunk_id not in dsk_graph
dsk_graph[chunk_id] = task
nodes[chunk_id] = task
self._node_cache[cache_key] = nodes
return nodes
|
Usecase: Two sets of chunks, one spans the whole of a dimension, the other
chunked it up. We need to know that we need to collect together the
chunked form, so that we can work with both sets at the same time.
Conceptually we have multiple source inputs, each with multiple key sets
for indexing.
NOTE: We treat the grouping independently per dimension. In practice this
means we may be grouping more than is strictly necessary if we were being
smart about multi-dimensional grouping. Anecdotally, that optimisation is
currently not worth the implementation effort.
def group_keys(shape, *inputs_keys):
"""
Usecase: Two sets of chunks, one spans the whole of a dimension, the other
chunked it up. We need to know that we need to collect together the
chunked form, so that we can work with both sets at the same time.
Conceptually we have multiple source inputs, each with multiple key sets
for indexing.
NOTE: We treat the grouping independently per dimension. In practice this
means we may be grouping more than is strictly necessary if we were being
smart about multi-dimensional grouping. Anecdotally, that optimisation is
currently not worth the implementation effort.
"""
# Store the result as a slice mapping to a subset of the inputs_keys. We
# start with the assumption that there will be only one group, and
# subdivide when we find this not to be the case.
ndim = len(inputs_keys[0][0])
grouped_inputs_keys = {tuple((None, None, None)
for _ in range(ndim)): inputs_keys}
for dim, dim_len in enumerate(shape):
# Compute the groups for this dimension.
for group_keys, group_inputs_keys in grouped_inputs_keys.copy(
).items():
group_inputs_key_for_dim = [[keys[dim] for keys in input_keys]
for input_keys in group_inputs_keys]
grouped_inputs_key = dimension_group_to_lowest_common(
dim_len, group_inputs_key_for_dim).items()
# If this group hasn't sub-divided, continue on to next group.
if len(grouped_inputs_key) == 1:
continue
else:
# Drop the bigger group from the result dictionary and in its
# place, add all of the subgroups.
grouped_inputs_keys.pop(group_keys)
# Make the group keys mutable so that we can inject our
# subgroups.
group_keys = list(group_keys)
group_inputs_keys = list(group_inputs_keys)
for subgroup_key, subgroup_inputs_key in grouped_inputs_key:
group_keys[dim] = subgroup_key
# Start with an empty list, one for each input.
subgroup_inputs_keys = [[] for _ in subgroup_inputs_key]
per_input = zip(group_inputs_keys, subgroup_inputs_key,
subgroup_inputs_keys)
for (input_keys, subgroup_input_key,
new_input_keys) in per_input:
for keys in input_keys[:]:
norm_key = normalize_slice(keys[dim], dim_len)
if norm_key in subgroup_input_key:
input_keys.remove(keys)
new_input_keys.append(keys)
subgroup_inputs_keys = tuple(subgroup_inputs_keys)
grouped_inputs_keys[tuple(
group_keys)] = subgroup_inputs_keys
return grouped_inputs_keys
|
<Purpose>
Return the password entered by the user. If 'confirm' is True, the user is
asked to enter the previously entered password once again. If they match,
the password is returned to the caller.
<Arguments>
prompt:
The text of the password prompt that is displayed to the user.
confirm:
Boolean indicating whether the user should be prompted for the password
a second time. The two entered password must match, otherwise the
user is again prompted for a password.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
The password entered by the user.
def get_password(prompt='Password: ', confirm=False):
"""
<Purpose>
Return the password entered by the user. If 'confirm' is True, the user is
asked to enter the previously entered password once again. If they match,
the password is returned to the caller.
<Arguments>
prompt:
The text of the password prompt that is displayed to the user.
confirm:
Boolean indicating whether the user should be prompted for the password
a second time. The two entered password must match, otherwise the
user is again prompted for a password.
<Exceptions>
None.
<Side Effects>
None.
<Returns>
The password entered by the user.
"""
# Are the arguments the expected type?
# If not, raise 'securesystemslib.exceptions.FormatError'.
securesystemslib.formats.TEXT_SCHEMA.check_match(prompt)
securesystemslib.formats.BOOLEAN_SCHEMA.check_match(confirm)
while True:
# getpass() prompts the user for a password without echoing
# the user input.
password = getpass.getpass(prompt, sys.stderr)
if not confirm:
return password
password2 = getpass.getpass('Confirm: ', sys.stderr)
if password == password2:
return password
else:
print('Mismatch; try again.')
|
<Purpose>
Generate an RSA key pair. The public portion of the generated RSA key is
saved to <'filepath'>.pub, whereas the private key portion is saved to
<'filepath'>. If no password is given, the user is prompted for one. If
the 'password' is an empty string, the private key is saved unencrypted to
<'filepath'>. If the filepath is not given, the KEYID is used as the
filename and the keypair saved to the current working directory.
The best available form of encryption, for a given key's backend, is used
with pyca/cryptography. According to their documentation, "it is a curated
encryption choice and the algorithm may change over time."
<Arguments>
filepath:
The public and private key files are saved to <filepath>.pub and
<filepath>, respectively. If the filepath is not given, the public and
private keys are saved to the current working directory as <KEYID>.pub
and <KEYID>. KEYID is the generated key's KEYID.
bits:
The number of bits of the generated RSA key.
password:
The password to encrypt 'filepath'. If None, the user is prompted for a
password. If an empty string is given, the private key is written to
disk unencrypted.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
<Side Effects>
Writes key files to '<filepath>' and '<filepath>.pub'.
<Returns>
The 'filepath' of the written key.
def generate_and_write_rsa_keypair(filepath=None, bits=DEFAULT_RSA_KEY_BITS,
password=None):
"""
<Purpose>
Generate an RSA key pair. The public portion of the generated RSA key is
saved to <'filepath'>.pub, whereas the private key portion is saved to
<'filepath'>. If no password is given, the user is prompted for one. If
the 'password' is an empty string, the private key is saved unencrypted to
<'filepath'>. If the filepath is not given, the KEYID is used as the
filename and the keypair saved to the current working directory.
The best available form of encryption, for a given key's backend, is used
with pyca/cryptography. According to their documentation, "it is a curated
encryption choice and the algorithm may change over time."
<Arguments>
filepath:
The public and private key files are saved to <filepath>.pub and
<filepath>, respectively. If the filepath is not given, the public and
private keys are saved to the current working directory as <KEYID>.pub
and <KEYID>. KEYID is the generated key's KEYID.
bits:
The number of bits of the generated RSA key.
password:
The password to encrypt 'filepath'. If None, the user is prompted for a
password. If an empty string is given, the private key is written to
disk unencrypted.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
<Side Effects>
Writes key files to '<filepath>' and '<filepath>.pub'.
<Returns>
The 'filepath' of the written key.
"""
# Does 'bits' have the correct format?
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.RSAKEYBITS_SCHEMA.check_match(bits)
# Generate the public and private RSA keys.
rsa_key = securesystemslib.keys.generate_rsa_key(bits)
public = rsa_key['keyval']['public']
private = rsa_key['keyval']['private']
if not filepath:
filepath = os.path.join(os.getcwd(), rsa_key['keyid'])
else:
logger.debug('The filepath has been specified. Not using the key\'s'
' KEYID as the default filepath.')
# Does 'filepath' have the correct format?
securesystemslib.formats.PATH_SCHEMA.check_match(filepath)
# If the caller does not provide a password argument, prompt for one.
if password is None: # pragma: no cover
# It is safe to specify the full path of 'filepath' in the prompt and not
# worry about leaking sensitive information about the key's location.
# However, care should be taken when including the full path in exceptions
# and log files.
password = get_password('Enter a password for the encrypted RSA'
' key (' + Fore.RED + filepath + Fore.RESET + '): ',
confirm=True)
else:
logger.debug('The password has been specified. Not prompting for one')
# Does 'password' have the correct format?
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
# Encrypt the private key if 'password' is set.
if len(password):
private = securesystemslib.keys.create_rsa_encrypted_pem(private, password)
else:
logger.debug('An empty password was given. Not encrypting the private key.')
# If the parent directory of filepath does not exist,
# create it (and all its parent directories, if necessary).
securesystemslib.util.ensure_parent_dir(filepath)
# Write the public key (i.e., 'public', which is in PEM format) to
# '<filepath>.pub'. (1) Create a temporary file, (2) write the contents of
# the public key, and (3) move to final destination.
file_object = securesystemslib.util.TempFile()
file_object.write(public.encode('utf-8'))
# The temporary file is closed after the final move.
file_object.move(filepath + '.pub')
# Write the private key in encrypted PEM format to '<filepath>'.
# Unlike the public key file, the private key does not have a file
# extension.
file_object = securesystemslib.util.TempFile()
file_object.write(private.encode('utf-8'))
file_object.move(filepath)
return filepath
|
<Purpose>
Import the PEM file in 'filepath' containing the private key.
If password is passed use passed password for decryption.
If prompt is True use entered password for decryption.
If no password is passed and either prompt is False or if the password
entered at the prompt is an empty string, omit decryption, treating the
key as if it is not encrypted.
If password is passed and prompt is True, an error is raised. (See below.)
The returned key is an object in the
'securesystemslib.formats.RSAKEY_SCHEMA' format.
<Arguments>
filepath:
<filepath> file, an RSA encrypted PEM file. Unlike the public RSA PEM
key file, 'filepath' does not have an extension.
password:
The passphrase to decrypt 'filepath'.
scheme:
The signature scheme used by the imported key.
prompt:
If True the user is prompted for a passphrase to decrypt 'filepath'.
Default is False.
<Exceptions>
ValueError, if 'password' is passed and 'prompt' is True.
ValueError, if 'password' is passed and it is an empty string.
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.FormatError, if the entered password is
improperly formatted.
IOError, if 'filepath' can't be loaded.
securesystemslib.exceptions.CryptoError, if a password is available
and 'filepath' is not a valid key file encrypted using that password.
securesystemslib.exceptions.CryptoError, if no password is available
and 'filepath' is not a valid non-encrypted key file.
<Side Effects>
The contents of 'filepath' are read, optionally decrypted, and returned.
<Returns>
An RSA key object, conformant to 'securesystemslib.formats.RSAKEY_SCHEMA'.
def import_rsa_privatekey_from_file(filepath, password=None,
scheme='rsassa-pss-sha256', prompt=False):
"""
<Purpose>
Import the PEM file in 'filepath' containing the private key.
If password is passed use passed password for decryption.
If prompt is True use entered password for decryption.
If no password is passed and either prompt is False or if the password
entered at the prompt is an empty string, omit decryption, treating the
key as if it is not encrypted.
If password is passed and prompt is True, an error is raised. (See below.)
The returned key is an object in the
'securesystemslib.formats.RSAKEY_SCHEMA' format.
<Arguments>
filepath:
<filepath> file, an RSA encrypted PEM file. Unlike the public RSA PEM
key file, 'filepath' does not have an extension.
password:
The passphrase to decrypt 'filepath'.
scheme:
The signature scheme used by the imported key.
prompt:
If True the user is prompted for a passphrase to decrypt 'filepath'.
Default is False.
<Exceptions>
ValueError, if 'password' is passed and 'prompt' is True.
ValueError, if 'password' is passed and it is an empty string.
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.FormatError, if the entered password is
improperly formatted.
IOError, if 'filepath' can't be loaded.
securesystemslib.exceptions.CryptoError, if a password is available
and 'filepath' is not a valid key file encrypted using that password.
securesystemslib.exceptions.CryptoError, if no password is available
and 'filepath' is not a valid non-encrypted key file.
<Side Effects>
The contents of 'filepath' are read, optionally decrypted, and returned.
<Returns>
An RSA key object, conformant to 'securesystemslib.formats.RSAKEY_SCHEMA'.
"""
# Does 'filepath' have the correct format?
# Ensure the arguments have the appropriate number of objects and object
# types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.PATH_SCHEMA.check_match(filepath)
# Is 'scheme' properly formatted?
securesystemslib.formats.RSA_SCHEME_SCHEMA.check_match(scheme)
if password and prompt:
raise ValueError("Passing 'password' and 'prompt' True is not allowed.")
# If 'password' was passed check format and that it is not empty.
if password is not None:
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
# TODO: PASSWORD_SCHEMA should be securesystemslib.schema.AnyString(min=1)
if not len(password):
raise ValueError('Password must be 1 or more characters')
elif prompt:
# Password confirmation disabled here, which should ideally happen only
# when creating encrypted key files (i.e., improve usability).
# It is safe to specify the full path of 'filepath' in the prompt and not
# worry about leaking sensitive information about the key's location.
# However, care should be taken when including the full path in exceptions
# and log files.
# NOTE: A user who gets prompted for a password, can only signal that the
# key is not encrypted by entering no password in the prompt, as opposed
# to a programmer who can call the function with or without a 'password'.
# Hence, we treat an empty password here, as if no 'password' was passed.
password = get_password('Enter a password for an encrypted RSA'
' file \'' + Fore.RED + filepath + Fore.RESET + '\': ',
confirm=False) or None
if password is not None:
# This check will not fail, because a mal-formatted passed password fails
# above and an entered password will always be a string (see get_password)
# However, we include it in case PASSWORD_SCHEMA or get_password changes.
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
else:
logger.debug('No password was given. Attempting to import an'
' unencrypted file.')
# Read the contents of 'filepath' that should be a PEM formatted private key.
with open(filepath, 'rb') as file_object:
pem_key = file_object.read().decode('utf-8')
# Convert 'pem_key' to 'securesystemslib.formats.RSAKEY_SCHEMA' format.
# Raise 'securesystemslib.exceptions.CryptoError' if 'pem_key' is invalid.
# If 'password' is None decryption will be omitted.
rsa_key = securesystemslib.keys.import_rsakey_from_private_pem(pem_key,
scheme, password)
return rsa_key
|
<Purpose>
Import the RSA key stored in 'filepath'. The key object returned is in the
format 'securesystemslib.formats.RSAKEY_SCHEMA'. If the RSA PEM in
'filepath' contains a private key, it is discarded.
<Arguments>
filepath:
<filepath>.pub file, an RSA PEM file.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'filepath' is improperly
formatted.
securesystemslib.exceptions.Error, if a valid RSA key object cannot be
generated. This may be caused by an improperly formatted PEM file.
<Side Effects>
'filepath' is read and its contents extracted.
<Returns>
An RSA key object conformant to 'securesystemslib.formats.RSAKEY_SCHEMA'.
def import_rsa_publickey_from_file(filepath):
"""
<Purpose>
Import the RSA key stored in 'filepath'. The key object returned is in the
format 'securesystemslib.formats.RSAKEY_SCHEMA'. If the RSA PEM in
'filepath' contains a private key, it is discarded.
<Arguments>
filepath:
<filepath>.pub file, an RSA PEM file.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'filepath' is improperly
formatted.
securesystemslib.exceptions.Error, if a valid RSA key object cannot be
generated. This may be caused by an improperly formatted PEM file.
<Side Effects>
'filepath' is read and its contents extracted.
<Returns>
An RSA key object conformant to 'securesystemslib.formats.RSAKEY_SCHEMA'.
"""
# Does 'filepath' have the correct format?
# Ensure the arguments have the appropriate number of objects and object
# types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.PATH_SCHEMA.check_match(filepath)
# Read the contents of the key file that should be in PEM format and contains
# the public portion of the RSA key.
with open(filepath, 'rb') as file_object:
rsa_pubkey_pem = file_object.read().decode('utf-8')
# Convert 'rsa_pubkey_pem' to 'securesystemslib.formats.RSAKEY_SCHEMA' format.
try:
rsakey_dict = securesystemslib.keys.import_rsakey_from_public_pem(rsa_pubkey_pem)
except securesystemslib.exceptions.FormatError as e:
raise securesystemslib.exceptions.Error('Cannot import improperly formatted'
' PEM file.' + repr(str(e)))
return rsakey_dict
|
<Purpose>
Generate an Ed25519 keypair, where the encrypted key (using 'password' as
the passphrase) is saved to <'filepath'>. The public key portion of the
generated Ed25519 key is saved to <'filepath'>.pub. If the filepath is not
given, the KEYID is used as the filename and the keypair saved to the
current working directory.
The private key is encrypted according to 'cryptography's approach:
"Encrypt using the best available encryption for a given key's backend.
This is a curated encryption choice and the algorithm may change over
time."
<Arguments>
filepath:
The public and private key files are saved to <filepath>.pub and
<filepath>, respectively. If the filepath is not given, the public and
private keys are saved to the current working directory as <KEYID>.pub
and <KEYID>. KEYID is the generated key's KEYID.
password:
The password, or passphrase, to encrypt the private portion of the
generated Ed25519 key. A symmetric encryption key is derived from
'password', so it is not directly used.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'filepath' cannot be encrypted.
<Side Effects>
Writes key files to '<filepath>' and '<filepath>.pub'.
<Returns>
The 'filepath' of the written key.
def generate_and_write_ed25519_keypair(filepath=None, password=None):
"""
<Purpose>
Generate an Ed25519 keypair, where the encrypted key (using 'password' as
the passphrase) is saved to <'filepath'>. The public key portion of the
generated Ed25519 key is saved to <'filepath'>.pub. If the filepath is not
given, the KEYID is used as the filename and the keypair saved to the
current working directory.
The private key is encrypted according to 'cryptography's approach:
"Encrypt using the best available encryption for a given key's backend.
This is a curated encryption choice and the algorithm may change over
time."
<Arguments>
filepath:
The public and private key files are saved to <filepath>.pub and
<filepath>, respectively. If the filepath is not given, the public and
private keys are saved to the current working directory as <KEYID>.pub
and <KEYID>. KEYID is the generated key's KEYID.
password:
The password, or passphrase, to encrypt the private portion of the
generated Ed25519 key. A symmetric encryption key is derived from
'password', so it is not directly used.
<Exceptions>
securesystemslib.exceptions.FormatError, if the arguments are improperly
formatted.
securesystemslib.exceptions.CryptoError, if 'filepath' cannot be encrypted.
<Side Effects>
Writes key files to '<filepath>' and '<filepath>.pub'.
<Returns>
The 'filepath' of the written key.
"""
# Generate a new Ed25519 key object.
ed25519_key = securesystemslib.keys.generate_ed25519_key()
if not filepath:
filepath = os.path.join(os.getcwd(), ed25519_key['keyid'])
else:
logger.debug('The filepath has been specified. Not using the key\'s'
' KEYID as the default filepath.')
# Does 'filepath' have the correct format?
# Ensure the arguments have the appropriate number of objects and object
# types, and that all dict keys are properly named.
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.PATH_SCHEMA.check_match(filepath)
# If the caller does not provide a password argument, prompt for one.
if password is None: # pragma: no cover
# It is safe to specify the full path of 'filepath' in the prompt and not
# worry about leaking sensitive information about the key's location.
# However, care should be taken when including the full path in exceptions
# and log files.
password = get_password('Enter a password for the Ed25519'
' key (' + Fore.RED + filepath + Fore.RESET + '): ',
confirm=True)
else:
logger.debug('The password has been specified. Not prompting for one.')
# Does 'password' have the correct format?
securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
# If the parent directory of filepath does not exist,
# create it (and all its parent directories, if necessary).
securesystemslib.util.ensure_parent_dir(filepath)
# Create a temporary file, write the contents of the public key, and move
# to final destination.
file_object = securesystemslib.util.TempFile()
# Generate the ed25519 public key file contents in metadata format (i.e.,
# does not include the keyid portion).
keytype = ed25519_key['keytype']
keyval = ed25519_key['keyval']
scheme = ed25519_key['scheme']
ed25519key_metadata_format = securesystemslib.keys.format_keyval_to_metadata(
keytype, scheme, keyval, private=False)
file_object.write(json.dumps(ed25519key_metadata_format).encode('utf-8'))
# Write the public key (i.e., 'public', which is in PEM format) to
# '<filepath>.pub'. (1) Create a temporary file, (2) write the contents of
# the public key, and (3) move to final destination.
# The temporary file is closed after the final move.
file_object.move(filepath + '.pub')
# Write the encrypted key string, conformant to
# 'securesystemslib.formats.ENCRYPTEDKEY_SCHEMA', to '<filepath>'.
file_object = securesystemslib.util.TempFile()
# Encrypt the private key if 'password' is set.
if len(password):
ed25519_key = securesystemslib.keys.encrypt_key(ed25519_key, password)
else:
logger.debug('An empty password was given. '
'Not encrypting the private key.')
ed25519_key = json.dumps(ed25519_key)
# Raise 'securesystemslib.exceptions.CryptoError' if 'ed25519_key' cannot be
# encrypted.
file_object.write(ed25519_key.encode('utf-8'))
file_object.move(filepath)
return filepath
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.