ssh-agent.sh 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Start ssh-agent and load available identities. Standardize location of the
  2. # ssh-agent authentication socket.
  3. #
  4. # `$SSH_AUTH_SOCK` is an environment variable set by `ssh-agent`, that points to
  5. # a socket that allows users to connect to it. This script symlinks the socket
  6. # to a predefined location (in a user's `.ssh` folder) so that a user's
  7. # different shell instances (e.g. in screen or tmux) can be automatically
  8. # connected to that same agent.
  9. # Override `$KEY_FILES` before this script is loaded to specify which identities
  10. # to load. Defaults to `ssh-add`'s standard files.
  11. [[ ${#KEY_FILES[@]} = 0 ]] && KEY_FILES=(~/.ssh/id_rsa ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/identity)
  12. function agent_setup() {
  13. echo 'Running `agent_setup` ...'
  14. # Run if ssh is installed.
  15. command -v ssh >/dev/null || return
  16. # Try to symlink an auth socket, to connect any existing agent.
  17. link_socket
  18. # Check for an agent:
  19. # 0 = agent running, has keys.
  20. # 1 = agent running, has no keys.
  21. # 2 = agent not running.
  22. ssh-add -l &>/dev/null
  23. case $? in
  24. 1) has_key_files && add_keys ;;
  25. 2) has_key_files && start_agent && add_keys ;;
  26. esac
  27. }
  28. # Create a symlink to an existing auth socket.
  29. function link_socket() {
  30. # Make sure the folder for the symlink exists.
  31. mkdir -p ~/.ssh
  32. local link="$HOME/.ssh/authsock"
  33. if [[ -n $SSH_AUTH_SOCK && $SSH_AUTH_SOCK != $link ]]; then
  34. ln -sf $SSH_AUTH_SOCK $link &>/dev/null
  35. export SSH_AUTH_SOCK=$link
  36. fi
  37. }
  38. # Check if there are keys to load on this machine.
  39. # 0 = found a key file.
  40. # 1 = did not find any key files.
  41. function has_key_files() {
  42. for file in $KEY_FILES; do
  43. [[ -f $file ]] && return 0
  44. done
  45. return 1
  46. }
  47. # Add keys to an agent.
  48. function add_keys() {
  49. ssh-add $KEY_FILES 2>/dev/null
  50. }
  51. # Start a new agent.
  52. function start_agent() {
  53. echo "Starting a new SSH Agent."
  54. eval `ssh-agent` &>/dev/null
  55. link_socket
  56. }
  57. # Go!
  58. # Automatic key loading can be disabled by setting `$DISABLE_SSH_AGENT_AUTOADD`
  59. # to `1` (running `agent_setup` manually would still work).
  60. [[ $DISABLE_SSH_AGENT_AUTOADD == 1 ]] && link_socket || agent_setup