ssh-agent.plugin.zsh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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
  13. local -a identities ids
  14. zstyle -a :omz:plugins:ssh-agent identities identities
  15. # get list of loaded identities
  16. for line in ${(f)"$(ssh-add -l)"}; do ids+=${${(z)line}[3]}; done
  17. # add identities if not already loaded
  18. for id in ${^identities}; do
  19. [[ ${ids[(I)$HOME/.ssh/$id]} -le 0 ]] && ssh-add $HOME/.ssh/$id
  20. done
  21. }
  22. # Get the filename to store/lookup the environment from
  23. _ssh_env_cache="$HOME/.ssh/environment-$SHORT_HOST"
  24. # test if agent-forwarding is enabled
  25. zstyle -b :omz:plugins:ssh-agent agent-forwarding _agent_forwarding
  26. if [[ $_agent_forwarding == "yes" && -n "$SSH_AUTH_SOCK" ]]; then
  27. # Add a nifty symlink for screen/tmux if agent forwarding
  28. [[ -L $SSH_AUTH_SOCK ]] || ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USER-screen
  29. elif [[ -f "$_ssh_env_cache" ]]; then
  30. # Source SSH settings, if applicable
  31. . $_ssh_env_cache > /dev/null
  32. if [[ $USER == "root" ]]; then
  33. FILTER="ax"
  34. else
  35. FILTER="x"
  36. fi
  37. ps $FILTER | grep ssh-agent | grep -q $SSH_AGENT_PID || {
  38. _start_agent
  39. }
  40. else
  41. _start_agent
  42. fi
  43. _add_identities
  44. # tidy up after ourselves
  45. unset _agent_forwarding _ssh_env_cache
  46. unfunction _start_agent _add_identities