ssh-agent.plugin.zsh 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 not_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. # add default keys if no identities were set up via zstyle
  20. # this is to mimic the call to ssh-add with no identities
  21. if [[ ${#identities} -eq 0 ]]; then
  22. # key list found on `ssh-add` man page's DESCRIPTION section
  23. for id in id_rsa id_dsa id_ecdsa id_ed25519 identity; do
  24. # check if file exists
  25. [[ -f "$HOME/.ssh/$id" ]] && identities+=$id
  26. done
  27. fi
  28. # get list of loaded identities' signatures
  29. for line in ${(f)"$(ssh-add -l)"}; do loaded+=${${(z)line}[2]}; done
  30. # get signatures of private keys
  31. for id in $identities; do
  32. signatures+="$(ssh-keygen -lf "$HOME/.ssh/$id" | awk '{print $2}') $id"
  33. done
  34. # add identities if not already loaded
  35. for sig in $signatures; do
  36. id="$(cut -f2 <<< $sig)"
  37. sig="$(cut -f1 <<< $sig)"
  38. [[ ${loaded[(I)$sig]} -le 0 ]] && not_loaded+="$HOME/.ssh/$id"
  39. done
  40. [[ -n "$not_loaded" ]] && ssh-add ${^not_loaded}
  41. }
  42. # Get the filename to store/lookup the environment from
  43. _ssh_env_cache="$HOME/.ssh/environment-$SHORT_HOST"
  44. # test if agent-forwarding is enabled
  45. zstyle -b :omz:plugins:ssh-agent agent-forwarding _agent_forwarding
  46. if [[ $_agent_forwarding == "yes" && -n "$SSH_AUTH_SOCK" ]]; then
  47. # Add a nifty symlink for screen/tmux if agent forwarding
  48. [[ -L $SSH_AUTH_SOCK ]] || ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USER-screen
  49. elif [[ -f "$_ssh_env_cache" ]]; then
  50. # Source SSH settings, if applicable
  51. . $_ssh_env_cache > /dev/null
  52. if [[ $USER == "root" ]]; then
  53. FILTER="ax"
  54. else
  55. FILTER="x"
  56. fi
  57. ps $FILTER | grep ssh-agent | grep -q $SSH_AGENT_PID || {
  58. _start_agent
  59. }
  60. else
  61. _start_agent
  62. fi
  63. _add_identities
  64. # tidy up after ourselves
  65. unset _agent_forwarding _ssh_env_cache
  66. unfunction _start_agent _add_identities