code
stringlengths
1
18.2k
" get_dev_details: An Error has occured"
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 re...
"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 ...
+ " get_dev_details: An Error has occured"
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 dictiona...
"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 = ur...
+ " get_dev_details: An Error has occured"
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 repr...
"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 # ...
+ " get_dev_series: An Error has occured"
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...
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="...
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"
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 #usual...
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 ty...
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_addre...
has occured"
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 ...
>>> 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 = ...
# 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"
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: ...
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 'deviceI...
= {} 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"
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 ...
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 's...
: { "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)
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 t...
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 imp...
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.g...
occured"
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...
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 pyhpeim...
= 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 usi...
e: return "Error:\n" + str(e) + " get_interface_details: An Error has occured"
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 :para...
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('...
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) + " ...
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 keypai...
' 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_session...
resp: data = await resp.json() return data['create_keypair_resource_policy']
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'...
'/admin/graphql') rqst.set_json({ 'query': q, }) async with rqst.fetch() as resp: data = await resp.json() return data['keypair_resource_policies']
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', 'resou...
e: print_error(e) sys.exit(1) rows = [] for name, key in fields: rows.append((name, info[key])) print(tabulate(rows, headers=('Field', 'Value')))
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_k...
'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: ...
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...
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']))
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=rat...
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....
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
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)
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)
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()))
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()
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)
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(...
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() retu...
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 opera...
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 p...
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) ...
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(...
# 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_t...
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...
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...
task nodes[chunk_id] = task return nodes
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 passin...
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
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(...
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__, arra...
[{}]\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
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 s...
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 # ...
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...
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 = li...
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_...
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 dis...
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.for...
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.')
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. ...
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 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 str...
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.FormatErro...
= 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 f...
# 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 pa...
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 ...
'<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 priv...
extension. file_object = securesystemslib.util.TempFile() file_object.write(private.encode('utf-8')) file_object.move(filepath) return filepath
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 an...
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 extensio...
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. se...
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, ...
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 ...
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 ...
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 em...
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 alw...
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 ...
omitted. rsa_key = securesystemslib.keys.import_rsakey_from_private_pem(pem_key, scheme, password) return rsa_key
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. <Excep...
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 d...