在git-bash启动时启用SSH Agent

在Windows平台上做后端开发中,发版本或者查看日志经常要上传文件或者登录服务器。如果没有使用SSH Agent管理私钥,每次都需要输入私钥的密码,很是麻烦特别是有时会卡住shell脚本的执行。

下面的脚本,可以在git-bash启动时,使用SSH Agent管理私钥,只需要启动时输入一次密码就可以了。

  1. 在Home目录下创建文件.bash_profile,并在里面加入以下代码:
test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc
  1. 在Home目录下创建文件.bashrc
# Start SSH Agent
# ----------------------------

SSH_ENV="$HOME/.ssh/environment"

function run_ssh_env {
  . "${SSH_ENV}" > /dev/null
}

function start_ssh_agent {
  echo "Initializing new SSH agent..."
  ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
  echo "succeeded"
  chmod 600 "${SSH_ENV}"

  run_ssh_env;

  ssh-add ~/.ssh/id_rsa;
}

if [ -f "${SSH_ENV}" ]; then
  run_ssh_env;
  ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    start_ssh_agent;
  }
else
  start_ssh_agent;
fi
  1. 重启下git-bash或者使用ssh-add /path/to/private/key就可以把key加到ssh-agent中管理。