01_ssh_agent.sh 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Ref: https://stackoverflow.com/a/34332776
  2. # https://docs.github.com/en/authentication/connecting-to-github-with-ssh/working-with-ssh-key-passphrases#auto-launching-ssh-agent-on-git-for-windows
  3. # https://web.archive.org/web/20210506080335/https://mah.everybody.org/docs/ssh
  4. SSH_ENV="${HOME}/.ssh/.agent_env"
  5. function start_agent {
  6. echo -n "Initialising new SSH agent..."
  7. eval `/usr/bin/ssh-agent`
  8. echo 'export SSH_AUTH_SOCK'=${SSH_AUTH_SOCK} > ${SSH_ENV}
  9. echo 'export SSH_AGENT_PID'=${SSH_AGENT_PID} >> ${SSH_ENV}
  10. echo "succeeded"
  11. chmod 600 "${SSH_ENV}"
  12. . "${SSH_ENV}" > /dev/null
  13. add_key
  14. }
  15. function add_key {
  16. /usr/bin/ssh-add -t 86400 $(list_keys)
  17. }
  18. function list_keys {
  19. PRIV_KEYS=""
  20. for file in ${HOME}/.ssh/id_*
  21. do
  22. if grep -q 'PRIVATE' ${file}; then
  23. PRIV_KEYS="${PRIV_KEYS} ${file}"
  24. fi
  25. done
  26. echo "${PRIV_KEYS}"
  27. }
  28. # Source SSH settings, if applicable
  29. if [ -f "${SSH_ENV}" ]; then
  30. . "${SSH_ENV}" > /dev/null
  31. # agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
  32. agent_run_state=$(/usr/bin/ssh-add -l &> /dev/null; echo $?)
  33. if [ $agent_run_state -eq 2 ]; then
  34. start_agent
  35. elif [ $agent_run_state -eq 1 ]; then
  36. add_key
  37. fi
  38. else
  39. start_agent;
  40. fi
  41. # Create our own hardlink to the socket (with random name)
  42. MYSOCK=/tmp/ssh_agent.${RANDOM}.sock
  43. ln --no-target-directory ${SSH_AUTH_SOCK} ${MYSOCK}
  44. export SSH_AUTH_SOCK=${MYSOCK}
  45. end_agent()
  46. {
  47. # if we are the last holder of a hardlink, then kill the agent
  48. nhard=$(ls -l ${SSH_AUTH_SOCK} | awk '{print $2}')
  49. if [[ "${nhard}" -eq 2 ]]; then
  50. rm ${SSH_ENV}
  51. /usr/bin/ssh-agent -k
  52. fi
  53. rm ${SSH_AUTH_SOCK}
  54. }
  55. trap end_agent EXIT