Linux SSH: key, agent, keychain

以前遇到过一个问题,在用有些 Linux 发行版时,用 ssh-keygen 产生好了密钥对并上传到了目标服务器,但每次登录都要重新输入。

这与 ssh-agent 有关,看如下 man ssh-agent 的输出:

ssh-agent is a program to hold private keys used for public key authentication (RSA, DSA). The idea is
that ssh-agent is started in the beginning of an X-session or a login session, and all other windows or
programs are started as clients to the ssh-agent program. Through use of environment variables the agent
can be located and automatically used for authentication when logging in to other machines using ssh(1).

所以快速的解决办法是启动 ssh-agent 并且导入 key 文件:

# eval `ssh-agent -s`       # ssh-agent 依赖于特殊环境变量,使用 eval 以正确产生环境变量
/id_rsa__or__id_dsa

这样就可以使用密钥自动登录 ssh。

但这样会有个问题,当退出运行 ssh-agent 的会话后,ssh-agent 会被关闭,这样一来会影响后续密钥认证过程,导致自动 ssh 失败、ssh 脚本运行出错…

对于这些问题,stackexchange 上的这篇文章给出了详细全面的回答:

对于 Gnome,GNOME SSH Keyring Agent 较好地处理了 ssh-key 的使用问题。

对于非 gnome 的 bash 环境,可以将如下命令添加到 ~/.bash_profile 中来加载无密码的 ssh-key:

if [ -z "$SSH_AUTH_SOCK" ] ; then     # -z means not null string
  eval `ssh-agent -s`
  ssh-add
fi

如果 ssh-key 有密码,可以考虑在脚本中使用 expect 自动交互加载 key files,这点在文章中有提及。

如果想让 ssh-agent 在后台一直工作,可以考虑使用 keychain,keychain 能让 cron 等工作顺利进行。

安全性与便利性不可兼得,以上方式中,最不方便使用的是每次会话开始都调用 ssh-agent 并为 key 输入密码,但这种方式安全性最好。最方便的是 keychain,但安全性最差。