ssh-agent.sh 2.0 KB

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