ssh-agent.plugin.zsh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. typeset _agent_forwarding _ssh_env_cache
  2. function _start_agent() {
  3. local lifetime
  4. zstyle -s :omz:plugins:ssh-agent lifetime lifetime
  5. # start ssh-agent and setup environment
  6. echo starting ssh-agent...
  7. ssh-agent -s ${lifetime:+-t} ${lifetime} | sed 's/^echo/#echo/' >! $_ssh_env_cache
  8. chmod 600 $_ssh_env_cache
  9. . $_ssh_env_cache > /dev/null
  10. }
  11. function _add_identities() {
  12. local id line sig
  13. local -a identities loaded signatures
  14. zstyle -a :omz:plugins:ssh-agent identities identities
  15. # check for .ssh folder presence
  16. if [[ ! -d $HOME/.ssh ]]; then
  17. return
  18. fi
  19. # get list of loaded identities' signatures
  20. for line in ${(f)"$(ssh-add -l)"}; do loaded+=${${(z)line}[2]}; done
  21. # get signatures of private keys
  22. for id in $identities; do
  23. signatures+="$(ssh-keygen -lf "$HOME/.ssh/$id" | awk '{print $2}') $id"
  24. done
  25. # add identities if not already loaded
  26. for sig in $signatures; do
  27. id="$(cut -f2 <<< $sig)"
  28. sig="$(cut -f1 <<< $sig)"
  29. [[ ${loaded[(I)$sig]} -le 0 ]] && ssh-add $HOME/.ssh/$id
  30. done
  31. }
  32. # Get the filename to store/lookup the environment from
  33. _ssh_env_cache="$HOME/.ssh/environment-$SHORT_HOST"
  34. # test if agent-forwarding is enabled
  35. zstyle -b :omz:plugins:ssh-agent agent-forwarding _agent_forwarding
  36. if [[ $_agent_forwarding == "yes" && -n "$SSH_AUTH_SOCK" ]]; then
  37. # Add a nifty symlink for screen/tmux if agent forwarding
  38. [[ -L $SSH_AUTH_SOCK ]] || ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USER-screen
  39. elif [[ -f "$_ssh_env_cache" ]]; then
  40. # Source SSH settings, if applicable
  41. . $_ssh_env_cache > /dev/null
  42. if [[ $USER == "root" ]]; then
  43. FILTER="ax"
  44. else
  45. FILTER="x"
  46. fi
  47. ps $FILTER | grep ssh-agent | grep -q $SSH_AGENT_PID || {
  48. _start_agent
  49. }
  50. else
  51. _start_agent
  52. fi
  53. _add_identities
  54. # tidy up after ourselves
  55. unset _agent_forwarding _ssh_env_cache
  56. unfunction _start_agent _add_identities