12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- # Ref: https://stackoverflow.com/a/34332776
- # https://docs.github.com/en/authentication/connecting-to-github-with-ssh/working-with-ssh-key-passphrases#auto-launching-ssh-agent-on-git-for-windows
- # https://web.archive.org/web/20210506080335/https://mah.everybody.org/docs/ssh
- SSH_ENV="${HOME}/.ssh/.agent_env"
- function start_agent {
- echo -n "Initialising new SSH agent..."
- eval `/usr/bin/ssh-agent`
- echo 'export SSH_AUTH_SOCK'=${SSH_AUTH_SOCK} > ${SSH_ENV}
- echo 'export SSH_AGENT_PID'=${SSH_AGENT_PID} >> ${SSH_ENV}
- echo "succeeded"
- chmod 600 "${SSH_ENV}"
- . "${SSH_ENV}" > /dev/null
- add_key
- }
- function add_key {
- /usr/bin/ssh-add -t 86400 $(list_keys)
- }
- function list_keys {
- PRIV_KEYS=""
- for file in ${HOME}/.ssh/id_*
- do
- if grep -q 'PRIVATE' ${file}; then
- PRIV_KEYS="${PRIV_KEYS} ${file}"
- fi
- done
- echo "${PRIV_KEYS}"
- }
- # Source SSH settings, if applicable
- if [ -f "${SSH_ENV}" ]; then
- . "${SSH_ENV}" > /dev/null
- # agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2=agent not running
- agent_run_state=$(/usr/bin/ssh-add -l &> /dev/null; echo $?)
- if [ $agent_run_state -eq 2 ]; then
- start_agent
- elif [ $agent_run_state -eq 1 ]; then
- add_key
- fi
- else
- start_agent;
- fi
- # Create our own hardlink to the socket (with random name)
- MYSOCK=/tmp/ssh_agent.${RANDOM}.sock
- ln --no-target-directory ${SSH_AUTH_SOCK} ${MYSOCK}
- export SSH_AUTH_SOCK=${MYSOCK}
- end_agent()
- {
- # if we are the last holder of a hardlink, then kill the agent
- nhard=$(ls -l ${SSH_AUTH_SOCK} | awk '{print $2}')
- if [[ "${nhard}" -eq 2 ]]; then
- rm ${SSH_ENV}
- /usr/bin/ssh-agent -k
- fi
- rm ${SSH_AUTH_SOCK}
- }
- trap end_agent EXIT
|