ssh-agent.sh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 target="$SSH_AUTH_SOCK"
  32. local link="$HOME/.ssh/authsock"
  33. if [[ -n $target && $target != $link ]]; then
  34. ln -sf $target $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. agent_setup