管理多个 ssh 密钥

管理多个 ssh 密钥

我有很多 ssh 密钥,它们都受密码保护并由 ssh-agent 管理。因此,我现在在某些连接上收到“身份验证失败次数过多”的提示。

正如之前在此网站上所解释的那样,这是因为 ssh 将尝试代理向其抛出的所有密钥。

建议的解决方案是在配置中使用 IdentitiesOnly,以及 IdentityFile。虽然这确实可以避免提供错误密钥,但它似乎完全禁用了代理,所以现在我必须在每次连接时输入密码。

我找不到关于此问题的明确信息。IdentitiesOnly 是否完全禁用从 ssh-agent 获取密钥?还是应该仅屏蔽未提及的密钥?

谢谢,Mathijs

# here's my config
~% cat .ssh/config
Host bluemote
  HostName some.host.com
  IdentitiesOnly yes
  IdentityFile /home/mathijs/.ssh/keys/bluebook_ecdsa

# I had the key loaded into the agent, shown here
~% ssh-add -L
ecdsa-sha2-nistp521 SOME_LONG_BASE64_NUMBER== /home/mathijs/.ssh/keys/bluebook_ecdsa

# but it doesn't seem to get used
~% ssh bluemote
Enter passphrase for key '/home/mathijs/.ssh/keys/bluebook_ecdsa':

答案1

IdentitiesOnly 是否完全禁用从 ssh-agent 获取密钥?还是应该仅屏蔽未提及的密钥?

&

似乎它完全禁用了代理

这是手册页中描述的预期行为ssh_config(5)

 IdentitiesOnly
         Specifies that ssh(1) should only use the authentication identity
         files configured in the ssh_config files, even if ssh-agent(1)
         offers more identities.  The argument to this keyword must be
         “yes” or “no”.  This option is intended for situations where ssh-
         agent offers many different identities.  The default is “no”.

 IdentityFile
         Specifies a file from which the user's DSA, ECDSA or DSA authen‐
         tication identity is read.  The default is ~/.ssh/identity for
         protocol version 1, and ~/.ssh/id_dsa, ~/.ssh/id_ecdsa and
         ~/.ssh/id_rsa for protocol version 2.  Additionally, any identi‐
         ties represented by the authentication agent will be used for
         authentication.  ssh(1) will try to load certificate information
         from the filename obtained by appending -cert.pub to the path of
         a specified IdentityFile.

有一个解决方法:ssh-add。虽然使用 似乎禁用了常规 SSH 密钥代理IdentitiesOnly,但我使用 添加的代理ssh-add仍然可用。

答案2

我也有很多钥匙,今天晚上我才找到一种方法来做到这一点:

#!/bin/bash
remove_public () { # remove the public key after 2 seconds
  sleep 2
  rm -f $HOME/.ssh/public_key $HOME/.ssh/config
}

get_public () { # get the public key from ssh-add
  ssh-add -L | grep "$1" > $HOME/.ssh/public_key
  if [ ! -s "$HOME/.ssh/public_key" ] #identity hasn't yet been loaded
  then
    export KEY="$1" #use the private key it'll be added to the agent for next time assuming agent is configured.
  else
    export KEY="$HOME/.ssh/public_key" #use the public key
    ( remove_public & ) >/dev/null 2>&1
  fi
  chmod 700 "$KEY"
  echo "IdentitiesOnly=yes" > "$HOME/.ssh/config"
  echo "IdentityFile $KEY" >> "$HOME/.ssh/config"
}

ssh_connect () {
  chmod -R 700 $HOME/.ssh
  if [[ -z "$1" || -z "$2" ]]
  then
    echo "Username or server not specified!"
    exit 1;
  else
    get_public "$HOME/.ssh/$2"
    ssh "$2@$1" -i "$HOME/.ssh/$2"
  fi
}

连接使用:

ssh_connect "server" "user"

这假设您的私钥是 $HOME/.ssh/{username},但当然可以进行调整。

它从代理导出公钥并使用它。如果尚未将其添加到代理,则它使用私钥。

请注意,它将删除您的 ssh 配置,因此如果您需要保留其中的任何内容,则应该修改它以重写您的配置,而不是删除它。

相关内容