02_ssh_agent.sh 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 list_not_loaded_keys {
  16. KEYS=$(list_keys)
  17. KEYS_LOADED=$(ssh-add -l | awk '{ print $3}')
  18. KEYS_NOT_LOADED=""
  19. for key in ${KEYS}
  20. do
  21. if ! grep -q "${key}" <<< ${KEYS_LOADED}; then
  22. KEYS_NOT_LOADED="${KEYS_NOT_LOADED} ${key}"
  23. fi
  24. done
  25. echo "${KEYS_NOT_LOADED}"
  26. }
  27. function add_key {
  28. /usr/bin/ssh-add -t 86400 $(list_keys)
  29. }
  30. function update_keys {
  31. KEYS=$(list_not_loaded_keys)
  32. [[ -n ${KEYS} ]] && /usr/bin/ssh-add -t 86400 ${KEYS}
  33. }
  34. function list_keys {
  35. PRIV_KEYS=""
  36. for file in ${HOME}/.ssh/id_*
  37. do
  38. if grep -q 'PRIVATE' ${file}; then
  39. PRIV_KEYS="${PRIV_KEYS} ${file}"
  40. fi
  41. done
  42. echo "${PRIV_KEYS}"
  43. }
  44. # Source SSH settings, if applicable
  45. if [ -f "${SSH_ENV}" ]; then
  46. . "${SSH_ENV}" > /dev/null
  47. # agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
  48. agent_run_state=$(/usr/bin/ssh-add -l &> /dev/null; echo $?)
  49. if [ $agent_run_state -eq 2 ]; then
  50. start_agent
  51. elif [ $agent_run_state -eq 1 ]; then
  52. add_key
  53. elif [ $agent_run_state -eq 0 ]; then
  54. update_keys
  55. fi
  56. else
  57. start_agent;
  58. fi
  59. # Create our own hardlink to the socket (with random name)
  60. MYSOCK=/tmp/ssh_agent.${RANDOM}.sock
  61. ln --force --no-target-directory ${SSH_AUTH_SOCK} ${MYSOCK}
  62. export SSH_AUTH_SOCK=${MYSOCK}
  63. end_agent()
  64. {
  65. # if we are the last holder of a hardlink, then kill the agent
  66. nhard=$(ls -l ${SSH_AUTH_SOCK} | awk '{print $2}')
  67. if [[ "${nhard}" -eq 2 ]]; then
  68. rm ${SSH_ENV}
  69. /usr/bin/ssh-agent -k
  70. fi
  71. rm ${SSH_AUTH_SOCK}
  72. }
  73. trap end_agent EXIT SIGKILL SIGTERM