cron_key.sh 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/usr/bin/env bash
  2. ##### My (demuredemeanor) cron_key script
  3. # The purpose of this script is to provide an easy wrapper for cron scripts
  4. # to be able to use your ssh-agent's stored key or gpg auth key.
  5. # This is assuming that your key is already sourced like:
  6. # https://notabug.org/demure/dotfiles/src/master/subbash/sshagent
  7. # https://notabug.org/demure/dotfiles/src/master/subbash/sshgpgagent
  8. #
  9. # Uses tabstop=4; shiftwidth=4 tabs; foldmarker={{{,}}};
  10. # https://notabug.org/demure/scripts
  11. ## Started by daemoneye
  12. # https://github.com/kwolter/home_scripts/blob/master/ssh_key_fix.sh
  13. SSH_ENV="${HOME}/.ssh/environment"
  14. WRAPPED="$@"
  15. SSH_FAIL=0 ## Initialize
  16. GPG_FAIL=0 ## Initialize
  17. ## Check that augment is given, exit for non for help
  18. if [ $# -eq 0 ] || [ $1 = "-h" ] || [ $1 = "--help" ]; then
  19. echo "Useage: $0 \"<command_to_run>\""
  20. exit 1
  21. fi
  22. ## Test if ssh environment exists
  23. if [ -s "${SSH_ENV}" ]; then
  24. . "${SSH_ENV}" > /dev/null ## Source ssh env
  25. ps "${SSH_AGENT_PID}" > /dev/null || SSH_FAIL=1 ## Make sure pid is good
  26. else
  27. SSH_FAIL=1
  28. fi
  29. ## Assume that GPG is only desired if SSH key fails
  30. if [ "${SSH_FAIL}" -eq 1 ]; then
  31. ## Test if a gpg auth key is in the key ring
  32. if [ "$(gpg -K | awk 'BEGIN {AK=0} /^ssb>?\s/ {if($4=="[A]"){AK=1}} END {print AK}')" -eq 1 ]; then
  33. ## Test that a gpg key is in cache (presumably you only have one keyring)
  34. GPG_CACHE="$({ gpg-connect-agent 'keyinfo --list' /bye 2>/dev/null; gpg-connect-agent 'scd getinfo card_list' /bye 2>/dev/null; } | awk 'BEGIN{CH=0} /^S/ {if($7==1){CH=1}; if($2=="SERIALNO"){CH=1}} END{if($0!=""){print CH} else {print "none"}}')"
  35. if [ "${GPG_CACHE}" -eq 1 ]; then
  36. unset SSH_AGENT_PID
  37. export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
  38. else
  39. GPG_FAIL=1
  40. fi
  41. else
  42. GPG_FAIL=1
  43. fi
  44. fi
  45. ## If both fail, print error and exit
  46. if [ "${SSH_FAIL}" -eq 1 ] && [ "${GPG_FAIL}" -eq 1 ]; then
  47. echo "SSH key and GPG key failures."
  48. exit 1
  49. fi
  50. ## Run passed command and exit
  51. exec ${WRAPPED}
  52. exit 0