Esempio n. 1
0
def _keys_del(conf: Configuration,
              ostack: OpenStack,
              name: str,
              force: bool = False):
    if not name:
        _keys = _keys_list(conf, ostack, True)
        item = Console.ask("Select key to remove", _type=int)
        if item is None or item > len(_keys) - 1:
            Console.print_warning("Invalid selection, aborting")
            return
        name = _keys[item].name

    if Console.ask_confirmation(f"Confirm removing key '{name}'", force=force):
        ostack.delete_keypair(name)
        if ostack.has_errors:
            so = StatusOutput(additional_errors=ostack.last_errors)
            so.check_issues()
        else:
            Console.print("Removed from the server")

        if not conf.delete_key(name):
            Console.print_error(
                f"Failed to remove key '{name}' from the configuration")
        else:
            Console.print("Removed from the configuration")
Esempio n. 2
0
def main_entry():

    conf: Configuration = Configuration(upgrade_manager=upgrade_manager,
                                        app_name=app_name,
                                        lazy_init=True)
    if upgrade_manager.upgrade_required(conf):
        import_upgrade_packs()

    is_debug: bool = "debug" in commands.discovery.kwargs_name
    if is_debug:
        os.environ["API_DEBUG"] = "True"
    try:
        # currently hack to avoid key generating on reset command
        if commands.discovery.command_name == "conf" and commands.discovery.command_arguments[:
                                                                                              1] == "reset":
            pass
        elif commands.discovery.command_name == "version":
            pass
        else:
            conf.initialize()
            if conf.check_for_update:
                from openstack_cli.commands.version import print_little_banner
                print_little_banner()

        commands.discovery.start_application(kwargs={
            "conf": conf,
            "debug": is_debug
        })
    except KeyboardInterrupt:
        print("Cancelled by user...")
    except Exception as e:
        if is_debug:
            raise e
        else:
            print(f"Error: {str(e)}")
Esempio n. 3
0
def _create_key(conf: Configuration, ostack: OpenStack,
                keyBuilder: VMKeyPairItemBuilder):
    key = keyBuilder.build()

    try:
        conf.add_key(key)
        ostack.create_key(key)

        Console.print(f"Key with name '{key.name}' successfully added")
    except ValueError as e:
        if ostack.has_errors:
            so = StatusOutput(None,
                              pool_size=0,
                              additional_errors=ostack.last_errors)
            so.check_issues()
        else:
            Console.print_error(
                f"Configuration already have the key with name {key.name}, please remove it first"
            )
Esempio n. 4
0
def get_default_network(conf: Configuration,
                        ostack: OpenStack,
                        force: bool = False) -> OSNetworkItem:
    net: OSNetworkItem or None = conf.default_network

    if not net or force:
        net = print_networks(ostack, True)
        if net:
            conf.default_network = net

    return net
Esempio n. 5
0
def __init__(conf: Configuration, name: str, node_number: int, user_name: str, use_password: bool, use_key: str,
             own: bool, port: int, internal: bool):

  if use_key == "None":
    use_key = None

  ostack = OpenStack(conf)
  node = host_selector(ostack, name, node_number, own)
  print(f"Establishing connection to {node.fqdn}({node.ip_address}) as '{user_name}' user...")
  if use_password:
    _open_console(internal, node.ip_address, port=port, user_name=user_name, password=True)
  else:
    if not os.path.exists(conf.local_key_dir):
      os.makedirs(conf.local_key_dir, exist_ok=True)

    if not use_key and node.key_name and node.key_name in conf.key_names and conf.get_key(node.key_name).private_key:
      #PKCS8 format -> openssl
      pkcs8_frmt_B = "-----BEGIN PRIVATE KEY-----"
      pkcs8_frmt_E ="-----END PRIVATE KEY-----"
      openssl_frmt_B = "-----BEGIN RSA PRIVATE KEY-----"
      openssl_frmt_E = "-----END RSA PRIVATE KEY-----"

      key = conf.get_key(node.key_name).private_key
      if pkcs8_frmt_B in key:
        key = key.replace(pkcs8_frmt_B, openssl_frmt_B)

      if pkcs8_frmt_E in key:
        key = key.replace(pkcs8_frmt_E, openssl_frmt_E)

      use_key = os.path.join(conf.local_key_dir, node.key_name) + ".key"
      with open(use_key, "w+", encoding="UTF-8") as f:
        f.write(key)
      try:
        os.chmod(use_key, 0o600)
      except OSError:
        pass
    else:
      raise ValueError("No custom key provided nor private key found in the key storage. Please add private key to"
                       " storage or use custom one with 'use-key' argument")

    _open_console(internal, node.ip_address, user_name=user_name, port=port, key_file=use_key)
Esempio n. 6
0
def __init__(conf: Configuration, name: str, private: str, public: str):
    if private == "@": private = ""
    if public == "@": public = ""

    ostack = OpenStack(
        conf)  # server keys are imported on object initialization

    if name not in conf.key_names:
        private, public = _check_keys(private, public, True, True)
        _create_key(conf, ostack,
          VMKeyPairItemBuilder()\
                    .set_name(name)\
                    .set_public_key(_get_file(public))\
                    .set_private_key(_get_file(private))
        )
    else:
        _key = conf.get_key(name)
        if private and not public:
            public = _key.public_key
            private, _ = _check_keys(private, None, True, False)
            conf.delete_key(name)
            conf.add_key(VMKeyPairItemBuilder()\
                         .set_name(name)\
                         .set_private_key(_get_file(private))\
                         .set_public_key(public)\
                         .build()
            )
            print("Private key imported")
            return

        _keys_del(conf, ostack, name, True)
        private, public = _check_keys(private, public, True, True)
        _create_key(conf, ostack,
                    VMKeyPairItemBuilder() \
                    .set_name(name) \
                    .set_public_key(_get_file(public)) \
                    .set_private_key(_get_file(private))
                    )
Esempio n. 7
0
def _keys_list(conf: Configuration,
               ostack: OpenStack,
               show_row_nums: bool = False) -> List[VMKeypairItemValue]:
    server_keypairs: Dict[int, VMKeypairItemValue] = {
        hash(key): key
        for key in ostack.get_keypairs()
    }
    conf_keys = conf.get_keys()
    if not conf_keys:
        Console.print_warning("No keys found, add new ones")
        return []

    max_key_len = len(max(conf.key_names))
    to = TableOutput(TableColumn("Key Name",
                                 max_key_len + len(KEY_ICON),
                                 inv_ch=len(KEY_ICON) - 2,
                                 pos=TableColumnPosition.left),
                     TableColumn("Priv.Key",
                                 3,
                                 inv_ch=len(CHECK_ICON) - 2,
                                 pos=TableColumnPosition.center),
                     TableColumn("Pub.Key",
                                 3,
                                 inv_ch=len(CHECK_ICON) - 2,
                                 pos=TableColumnPosition.center),
                     TableColumn("Rem.Sync",
                                 3,
                                 inv_ch=len(CHECK_ICON),
                                 pos=TableColumnPosition.center),
                     TableColumn("Fingerprint",
                                 48,
                                 pos=TableColumnPosition.left),
                     print_row_number=show_row_nums)

    to.print_header()

    for kp in conf_keys:
        to.print_row(
            f"{KEY_ICON}{kp.name}",
            CHECK_ICON if kp.private_key else UNCHECK_ICON,
            CHECK_ICON if kp.public_key else UNCHECK_ICON,
            CHECK_ICON if hash(kp) in server_keypairs else UNCHECK_ICON,
            server_keypairs[hash(kp)].fingerprint
            if hash(kp) in server_keypairs else
            "00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00")

    return conf_keys
Esempio n. 8
0
def _keys_export(conf: Configuration, ostack: OpenStack, name: str):
    if not name:
        _keys = _keys_list(conf, ostack, True)
        item = Console.ask("Select key to export", _type=int)
        if item is None or item > len(_keys) - 1:
            Console.print_warning("Invalid selection, aborting")
            return
        name = _keys[item].name

    _key: VMKeypairItemValue
    try:
        _key = conf.get_key(name)
    except KeyError as e:
        Console.print_error(str(e))
        return

    d = os.getcwd()
    _public_file_path = os.path.join(d, f"{_key.name}.public.key")
    _private_file_path = os.path.join(d, f"{_key.name}.private.key")

    if _key.public_key:
        try:
            with open(_public_file_path, "w+", encoding="UTF-8") as f:
                f.write(_key.public_key)

            Console.print(f"Public key: {_public_file_path}")
        except IOError as e:
            Console.print_error(f"{_key.name}(public): {str(e)}")

    if _key.private_key:
        try:
            with open(_private_file_path, "w+", encoding="UTF-8") as f:
                f.write(_key.private_key)
            Console.print(f"Private key: {_private_file_path}")
        except IOError as e:
            Console.print_error(f"{_key.name}(private): {str(e)}")
Esempio n. 9
0
def __init__(conf: Configuration):
    for cache_item in conf.list_cache_ext:
        print(f"Invalidate cache extention '{cache_item}'...")
        conf.get_cache_ext(cache_item).invalidate_all()
    print("Cached data flushed")
Esempio n. 10
0
def __init__(conf: Configuration, name: str, node_number: int, user_name: str, use_password: bool, use_key: str,
             own: bool, port: int, internal: bool):
  ostack = OpenStack(conf)
  if name == "None":
    name = ""

  if use_key == "None":
    use_key = None

  if name and node_number == -1:
    _name, _, _node_number = name.rpartition("-")

    try:
      node_number = int(_node_number)
      name = _name
    except (ValueError, TypeError):
      pass

  if "." in name:
    name, _ = name.split(".")

  search_result: Dict[str, List[OpenStackVMInfo]] = ostack.get_server_by_cluster(name, sort=True, only_owned=own)
  to = TableOutput(
    TableColumn("Cluster name", 40),
    print_row_number=True
  )
  if len(search_result.keys()) > 1:
    to.print_header()
    for cluster_name in search_result.keys():
      to.print_row(cluster_name)

    selection: int = Console.ask("Choose cluster from the list", int)
    try:
      name = list(search_result.keys())[selection:][0]
    except IndexError:
      raise ValueError("Wrong selection, please select item within an provided range")
  elif search_result:
    name = list(search_result.keys())[0]
  else:
    raise ValueError(f"No matching cluster matching pattern'{name}' found")

  nodes: List[OpenStackVMInfo] = search_result[name]
  if node_number == -1:
    if len(nodes) > 1:
      to = TableOutput(
        TableColumn("IP", 18),
        TableColumn("Host name", 40),

        print_row_number=True
      )
      to.print_header()
      for node in nodes:
        to.print_row(node.ip_address, node.fqdn)
      node_number: int = Console.ask("Choose host from the list", int)
      if node_number > len(nodes):
        raise ValueError("Wrong selection, please select item within an provided range")
    else:
      node_number = 0
  else:
    node_number -= 1    # the node name starts for 1, while list from 0

  try:
    node: OpenStackVMInfo = nodes[node_number]
  except IndexError:
    raise ValueError("Unknown host name, please check the name")

  print(f"Establishing connection to {node.fqdn}({node.ip_address}) as '{user_name}' user...")
  if use_password:
    _open_console(internal, node.ip_address, port=port, user_name=user_name, password=True)
  else:
    if not os.path.exists(conf.local_key_dir):
      os.makedirs(conf.local_key_dir, exist_ok=True)

    if not use_key and node.key_name and node.key_name in conf.key_names and conf.get_key(node.key_name).private_key:
      #PKCS8 format -> openssl
      pkcs8_frmt_B = "-----BEGIN PRIVATE KEY-----"
      pkcs8_frmt_E ="-----END PRIVATE KEY-----"
      openssl_frmt_B = "-----BEGIN RSA PRIVATE KEY-----"
      openssl_frmt_E = "-----END RSA PRIVATE KEY-----"

      key = conf.get_key(node.key_name).private_key
      if pkcs8_frmt_B in key:
        key = key.replace(pkcs8_frmt_B, openssl_frmt_B)

      if pkcs8_frmt_E in key:
        key = key.replace(pkcs8_frmt_E, openssl_frmt_E)

      use_key = os.path.join(conf.local_key_dir, node.key_name) + ".key"
      with open(use_key, "w+", encoding="UTF-8") as f:
        f.write(key)
      try:
        os.chmod(use_key, 0o600)
      except OSError:
        pass
    else:
      raise ValueError("No custom key provided nor private key found in the key storage. Please add private key to"
                       " storage or use custom one with 'use-key' argument")

    _open_console(internal, node.ip_address, user_name=user_name, port=port, key_file=use_key)
Esempio n. 11
0
def __init__(conf: Configuration):
    conf.reset()
    print("Configuration reset completed")