用Certbot 獲取和自動更新SSL證書

Tim_Pan發表於2018-04-26

前言

之前寫過一篇「HTTPS時代,免費SSL獲取與配置(Apache版)」, 使用的是sslforfree.org 服務,這個服務比較傻瓜,按照步驟一步一步就可以得到證照,但是因為證照最長的過期時間是3個月,每次都需要苦逼得重新去操作一遍。雖然 sslforfree.org 也會發郵件提醒,每3個月操作一下真的很麻煩(終於知道大姨媽的感覺了)。

自動化?

作為 Geeker ,能自動化肯定要自動化,於是搜尋了很多資料,看看怎麼樣可以實現 sslforfree 證照的自動申請,搜尋結果終於找到了真相,原來 sslforfree.org 用的是 letsencrypt.org 的服務。裡面詳細寫明瞭為什麼證照只有3個月的原因——為了安全,就是要讓你們(自)折(動)騰(化)!

Certbot

官方推薦使用 CertBot的服務。開啟網站,按照提示一步一步選擇伺服器作業系統,網頁服務就會自動提示命令列,無腦複製貼上即可。下面以CentOS 6.x + Apache為例。

wget https://dl.eff.org/certbot-auto
chmod a+x certbot-auto
sudo ./certbot-auto --manual certonly

根據提示輸入郵箱和域名,然後再在相應的目錄下面建立檔案,即可生成證照檔案

修改 httpd.conf

SSLCertificateKeyFile /etc/letsencrypt/live/www.yourdomain.com/privkey.pem
SSLCertificateFile /etc/letsencrypt/live/www.yourdomain.com/cert.pem
SSLCertificateChainFile /etc/letsencrypt/live/www.yourdomain.com/chain.pem

設定 crontab實現自動更新證照

0 0,12 * * * python -c `import random; import time; time.sleep(random.random() * 3600)` && /path/to/certbot-auto renew 

如果生成證照的是用 manual 模式,那麼一定概要設定 –manual-auth-hook 設定驗證指令碼,否則無法自動更新

#!/bin/bash
echo $CERTBOT_VALIDATION > /usr/share/nginx/html/mimvp_home/.well-known/acme-challenge/$CERTBOT_TOKEN
/path/to/certbot-auto renew   --manual-auth-hook  /etc/letsencrypt/renewal/mimji.com.sh

One more thing — wildcard

./certbot-auto certonly --agree-tos --manual --preferred-challenges dns --server https://acme-v02.api.letsencrypt.org/directory -d "*.<your host>"

參考資料

相關文章