From Kromonos, 7 Months ago, written in Bash.
Embed
  1. #!/bin/bash
  2.  
  3. DOM="example.com"
  4. CERTFILE="/etc/letsencrypt/live/${DOM}/cert.pem"
  5. CERTBOT="/usr/local/bin/certbot-auto"
  6. MY_PATH="$(dirname \"$0\")"
  7. HEALTHSERVER="https://health.error.cf"
  8. HEALTHID="00000000-0000-0000-0000-000000000000"
  9. MAIL="hab@ich.net"
  10. HOST=$(uname -n)
  11. LOGGER=$(which logger)
  12. CURL=$(which curl)
  13. DAYSTORENEW=25
  14. DAYSTOALERT=10
  15. DAYS=0
  16. WEBROOT="/usr/share/nginx/tmp/"
  17. SCRIPTPATH=$(dirname "$0")
  18. RENEWED=false
  19. LOG=""
  20. WEBSERVER="nginx"
  21.  
  22. if [[ ! -z ${HEALTHID} ]] && [[ ! -z ${HEALTHSERVER} ]]; then
  23.     ${CURL} -fsS --retry 3 -X POST --data "Renewalcheck for ${DOM}" "${HEALTHSERVER}/ping/${HEALTHID}/start"
  24. fi
  25.  
  26. if [[ ! -f ${CERTBOT} ]]; then
  27.     wget https://dl.eff.org/certbot-auto
  28.     mv certbot-auto ${CERTBOT}
  29.     chown root ${CERTBOT}
  30.     chmod 0755 ${CERTBOT}
  31. fi
  32.  
  33. cd ${SCRIPTPATH}
  34. if [[ -f ${CERTFILE} ]]; then
  35.     d1=$(date -d "`openssl x509 -in ${CERTFILE} -text -noout | grep "Not After" | cut -c 25-`" +%s)
  36.     d2=$(date -d "now" +%s)
  37.     DAYS=$(echo \( ${d1} -  ${d2} \)  / 86400 |bc)
  38.     ${LOGGER} -d -t letsencrypt "Certificate (${CERTFILE}) will expire in ${DAYS} days"
  39. fi
  40.  
  41. if [[ ${DAYS} -lt ${DAYSTORENEW} ]] ; then
  42.     LOG=$(${CERTBOT} certonly --agree-tos --renew-by-default --email ${MAIL} --webroot -w ${WEBROOT} --rsa-key-size 4096 -d ${DOM} 2>&1)
  43.     if [[ ! -z ${HEALTHID} ]] && [[ ! -z ${HEALTHSERVER} ]]; then
  44.         ${CURL} -fsS --retry 3 -X POST --data "${LOG}" "${HEALTHSERVER}/ping/${HEALTHID}$([ $? -ne 0 ] && echo -n /fail)"
  45.     fi
  46.     systemctl daemon-reload
  47.     systemctl reload ${WEBSERVER}.service
  48.     ${LOGGER} -d -t letsencrypt "Certificate for domain ${DOM} renewed"
  49.     RENEWED=true
  50. else
  51.     if [[ ! -z ${HEALTHID} ]] && [[ ! -z ${HEALTHSERVER} ]]; then
  52.         ${CURL} -fsS --retry 3 -X POST --data "Renewalcheck for ${DOM} done. No renewal needed. Certificate (${CERTFILE}) will expire in ${DAYS} days" "${HEALTHSERVER}/ping/${HEALTHID}"
  53.     fi
  54. fi
  55.  
  56. if [[ ${DAYS} -lt ${DAYSTOALERT} ]]; then
  57.     if [[ -z ${HEALTHID} ]] || [[ -z ${HEALTHSERVER} ]]; then
  58.         echo "ALERT! CERTIFICATE RENEWAL PROBLEM! (${HOST})\n\nProblem while renew in script ${0} with certfile ${CERTFILE}" | mail -s "${HOST} - letsencrypt" ${MAIL}
  59.     else
  60.         ${CURL} -fsS --retry 3 -X POST --data "${LOG}" "${HEALTHSERVER}/ping/${HEALTHID}/fail"
  61.     fi
  62.     LOG="ALERT! CERTIFICATE RENEWAL PROBLEM! (${HOST})\n\nProblem while renew in script ${0} with certfile ${CERTFILE}\nCertificate still not renewed"
  63. fi