Esempio n. 1
0
def UpdatePubKeyFile(data, dry_run, key_file=pathutils.SSH_PUB_KEYS):
    """Updates the file of public SSH keys.

  @type data: dict
  @param data: Input data
  @type dry_run: boolean
  @param dry_run: Whether to perform a dry run

  """
    instructions = data.get(constants.SSHS_SSH_PUBLIC_KEYS)
    if not instructions:
        logging.info("No instructions to modify public keys received."
                     " Not modifying the public key file at all.")
        return
    (action, public_keys) = instructions

    if action == constants.SSHS_OVERRIDE:
        if dry_run:
            logging.info("This is a dry run, not overriding %s", key_file)
        else:
            ssh.OverridePubKeyFile(public_keys, key_file=key_file)
    elif action in [constants.SSHS_ADD, constants.SSHS_REPLACE_OR_ADD]:
        if dry_run:
            logging.info(
                "This is a dry run, not adding or replacing a key to %s",
                key_file)
        else:
            for uuid, keys in public_keys.items():
                if action == constants.SSHS_REPLACE_OR_ADD:
                    ssh.RemovePublicKey(uuid, key_file=key_file)
                for key in keys:
                    ssh.AddPublicKey(uuid, key, key_file=key_file)
    elif action == constants.SSHS_REMOVE:
        if dry_run:
            logging.info("This is a dry run, not removing keys from %s",
                         key_file)
        else:
            for uuid in public_keys.keys():
                ssh.RemovePublicKey(uuid, key_file=key_file)
    elif action == constants.SSHS_CLEAR:
        if dry_run:
            logging.info("This is a dry run, not clearing file %s", key_file)
        else:
            ssh.ClearPubKeyFile(key_file=key_file)
    else:
        raise SshUpdateError("Action '%s' not implemented for public keys." %
                             action)
  def testRemoveNonexistingKey(self):
    pub_key_file = self._CreateTempFile()
    ssh.AddPublicKey(self.UUID_1, self.KEY_B, key_file=pub_key_file)
    self.assertFileContent(pub_key_file,
      "123-456 ssh-dss BAasjkakfa234SFSFDA345462AAAB root@key-b\n")

    ssh.RemovePublicKey(self.UUID_2, key_file=pub_key_file)
    self.assertFileContent(pub_key_file,
      "123-456 ssh-dss BAasjkakfa234SFSFDA345462AAAB root@key-b\n")
  def testRemoveAllExistingKeys(self):
    pub_key_file = self._CreateTempFile()
    ssh.AddPublicKey(self.UUID_1, self.KEY_A, key_file=pub_key_file)
    ssh.AddPublicKey(self.UUID_1, self.KEY_B, key_file=pub_key_file)
    self.assertFileContent(pub_key_file,
      "123-456 ssh-dss AAAAB3NzaC1w5256closdj32mZaQU root@key-a\n"
      "123-456 ssh-dss BAasjkakfa234SFSFDA345462AAAB root@key-b\n")

    ssh.RemovePublicKey(self.UUID_1, key_file=pub_key_file)
    self.assertFileContent(pub_key_file, "")
 def testRemoveKeyFromEmptyFile(self):
     pub_key_file = self._CreateTempFile()
     ssh.RemovePublicKey(self.UUID_2, key_file=pub_key_file)
     self.assertFileContent(pub_key_file, "")