ssh-agent.sh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. # Run if ssh is installed.
  14. command -v ssh >/dev/null || return
  15. # Make sure the folder for the symlink exists.
  16. mkdir -p ~/.ssh
  17. # Try to symlink an auth socket, to connect any existing agent.
  18. link_socket
  19. # Check for an agent:
  20. # 0 = agent running, has keys.
  21. # 1 = agent running, has no keys.
  22. # 2 = agent not running.
  23. ssh-add -l &>/dev/null
  24. case $? in
  25. 1) has_key_files && add_keys ;;
  26. 2) has_key_files && start_agent && add_keys ;;
  27. esac
  28. }
  29. # Create a symlink to an existing auth socket.
  30. function link_socket() {
  31. local link="$HOME/.ssh/authsock"
  32. if [[ -n $SSH_AUTH_SOCK && $SSH_AUTH_SOCK != $link ]]; then
  33. ln -sf $SSH_AUTH_SOCK $link &>/dev/null
  34. export SSH_AUTH_SOCK=$link
  35. fi
  36. }
  37. # Check if there are keys to load on this machine.
  38. # 0 = found a key file.
  39. # 1 = did not find any key files.
  40. function has_key_files() {
  41. for file in $KEY_FILES; do
  42. [[ -f $file ]] && return 0
  43. done
  44. return 1
  45. }
  46. # Add keys to an agent.
  47. function add_keys() {
  48. ssh-add $KEY_FILES 2>/dev/null
  49. }
  50. # Start a new agent.
  51. function start_agent() {
  52. echo "Starting a new SSH Agent."
  53. eval `ssh-agent` &>/dev/null
  54. link_socket
  55. }
  56. # Go!
  57. agent_setup