前几天发现我的 letsencrypt 通配符证书 (simplehttps.com,newyingyong.cn 两个域名) 快过期了, 想为这两张证书续期(renew), 但遇到了问题, 所以研究了下, 写了个小工具解决了问题, 相信能给大家带来帮助.
如果你从来没有申请过 letsencrypt 通配符证书, 那么可以参考我的这篇文章Let's Encrypt 终于支持通配符证书了, 否则下列的内容可能会看不明白.
首先运行命令查看我的所有证书:
$ certbot-auto certificates
输出如下:
- Found the following certs:
- Certificate Name: simplehttps.com
- Domains: *.simplehttps.com
- Expiry Date: 2018-07-17 08:03:52+00:00 (VALID: 11 days)
- Certificate Path: /etc/letsencrypt/live/simplehttps.com/fullchain.pem
- Private Key Path: /etc/letsencrypt/live/simplehttps.com/privkey.pem
- Certificate Name: newyingyong.cn
- Domains: *.newyingyong.cn
- Expiry Date: 2018-08-03 21:29:55+00:00 (VALID: 29 days)
- Certificate Path: /etc/letsencrypt/live/newyingyong.cn/fullchain.pem
- Private Key Path: /etc/letsencrypt/live/newyingyong.cn/privkey.pem
其中证书名 simplehttps.com,newyingyong.cn 都是需要续期的(renew).
接下来运行 renew 命令:
$ certbot-auto renew --cert-name simplehttps.com
运行出现如图错误:
renew 错误
意思就是通配符证书申请, 续期的时候只能通过 DNS 验证, 而 DNS 添加记录只能手动, 整个 cerbot 操作无法做到自动化, 所以 renew 就失败了.
那如何解决呢, 幸亏 cerbot 提供了一个 manual-auth-hook hook, 什么意思呢? 可以编写一个脚本, 由这个脚本来先完成 DNS 验证, 然后再进行 renew. 对应的脚本会自动添加 DNS 记录, 从而完成 DNS 校验, 并自动 renew 证书.
根据这个解决思路:
可以使用 certbot 插件, 比如 certbot-dns-cloudflare 插件(还有其他的), 就是自动更新 cloudflare 等 DNS 的记录.
手动编写脚本, cerbot 官方提供了 cloudflare 的样例.
可惜的是这两种脚本都不支持阿里云的 DNS(我的域名全部由阿里云 DNS 提供).
为解决这问题, 我写了个脚本, 并放在 github 上, 可以自取.
$ git clone "https://github.com/ywdblog/certbot-letencrypt-wildcardcertificates-alydns-au"
脚本就两个文件:
au.sh:--manual-auth-hook 对应的脚本, 主要就是执行 hook 操作, 会调用一些 certbot 内部变量.
alydns.php:au.sh 会调用该脚本, 完成 DNS 记录的更新操作.
首先看下 au.sh 的代码:
- #!/bin/bash
- #!/bin/bash
- #PHP 脚本位置
- PHPPROGRAM="/root/"
- DOMAIN="simplehttps.com"
- PATH=$(cd `dirname $0`; pwd)
- # 要为那个 DNS RR 添加 TXT 记录
- CREATE_DOMAIN="_acme-challenge"
- # $CERTBOT_VALIDATION 是 Certbot 的内置变量, 代表需要为 DNS TXT 记录设置的值
- echo $PATH"/alydns.php"
- # 调用 PHP 脚本, 自动设置 DNS TXT 记录.
- /usr/bin/php $PATH"/alydns.php" $DOMAIN $CREATE_DOMAIN $CERTBOT_VALIDATION>/var/log/certdebug.log
- # DNS TXT 记录刷新时间
- #sleep 30
如果用户要使用该脚本:
au.sh, 修改 PHPPROGRAM(au.sh 脚本的目录),DOMAIN(你的域名).
alydns.php, 修改 accessKeyId,accessSecrec, 需要去阿里云申请 API key 和 Secrec, 用于调用阿里云 DNS API.
配置好后, 执行下列测试命令:
$ certbot-auto renew --cert-name newyingyong.cn --manual-auth-hook / 你的脚本目录 / au.sh --dry-run
重要提醒: 为避免遇到操作次数的限制, 加入 dry-run 参数, 能够避免操作限制, 等执行无误后, 再进行真实的 renew 操作.
输出如下:
- Congratulations, all renewals succeeded. The following certs have been renewed:
- /etc/letsencrypt/live/newyingyong.cn/fullchain.pem (success)
确保无误后, 再进行真实的 renew 操作:
$ certbot-auto renew --cert-name newyingyong.cn --manual-auth-hook / 你的脚本目录 / au.sh
renew 成功
证书更新成功后, 运行如下命令查看证书:
$ openssl x509 -in /etc/letsencrypt/live/newyingyong.cn/fullchain.pem -noout -text
关键输出如下:
- Issuer: C = US, O = Let's Encrypt, CN = Let's Encrypt Authority X3
- Validity
- Not Before: Jul 5 21:29:55 2018 GMT
- Not After : Oct 3 21:29:55 2018 GMT
- Subject: CN = *.newyingyong.cn
顺利完成.
来源: http://www.jianshu.com/p/d318321b93a1