Linux 登陆用户时启动 ssh-agent 并复用
该文章根据 CC-BY-4.0 协议发表,转载请遵循该协议。
本文地址:https://fenying.net/post/2017/12/20/auto-init-ssh-agent/
使用 Git/SSH/SCP 之类操作的时候,一般都是用 ssh 密钥的,但是每次都要先启动 ssh-agent 才能注册密钥,挺烦的,于是尝试了一下,能不能在登陆终端的时候自动启动 ssh-agent,并在下次启动终端时复用该 ssh-agent。
自动启动的原理很简单,就是在 ~/.bashrc
里面加入
成功了,现在登陆会自动启动 ssh-agent,并且退出的时候自动kill掉了。
然而,其实上面的还是有问题的,比如说,SCP命令无效,SFTP(使用FlashFXP)无法登陆等等。
原因是 ssh-agent 在启动和退出的时候都会在终端吼一嗓子,输出一句话……
所以,不让它输出即可:
1eval $(ssh-agent -s) > /dev/null
2trap 'test -n "$SSH_AGENT_PID" && eval `/usr/bin/ssh-agent -k` > /dev/null' 0
bash
那么改造一下,允许它复用,就变成了如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add following code at the end of ~/.bashrc | |
# Check if ~/.pid_ssh_agent exists. | |
if [ -f ~/.pid_ssh_agent ]; then | |
source ~/.pid_ssh_agent | |
# Check process of ssh-agent still exists. | |
TEST=$(ssh-add -l) | |
if [ -z "$TEST" ]; then # Reinit if not. | |
NEED_INIT=1 | |
fi | |
else | |
NEED_INIT=1 # PID file doesm't exist, reinit it. | |
fi | |
# Try start ssh-agent. | |
if [ ! -z "$NEED_INIT" ]; then | |
echo $(ssh-agent -s) | sed -e 's/echo[ A-Za-z0-9]*;//g' > ~/.pid_ssh_agent # save the PID to file. | |
source ~/.pid_ssh_agent | |
fi |