前言
Let’s Encrypt颁发的证书的有效期只有90天,每次快过期的时候就需要手动更新SSL证书。
如果项目只有你一个人维护,刚好你休假了,休假前你也忘记手动更新证书了,那么就没法了,想想在外面玩,遇到这事还得找个网吧紧急处理的心情。😞😞😞
如果你看了我写的上一篇文章看了就会使用Linux定时任务crontab
,我相信你已经想到了使用crontab来创建一个任务定时自动更新证书。
没错,这篇文章就是要讲这个。
操作步骤:
1. 查看证书信息
$ sudo certbot certificates
[sudo] password for admin:
Saving debug log to /var/log/letsencrypt/letsencrypt.log
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Found the following certs:
Certificate Name: api.xxx.com
Serial Number: 347c6f791cc3703d6dd475aedd6201253b8
Key Type: RSA
Domains: api.xxx.com
Expiry Date: 2021-08-03 01:22:38+00:00 (VALID: 82 days)
Certificate Path: /etc/letsencrypt/live/api.xxx.com/fullchain.pem
Private Key Path: /etc/letsencrypt/live/api.xxx.com/privkey.pem
Certificate Name: cnapi.xxx.com
Serial Number: 39628b88c7639e157e0d4c266bad5ec9457
Key Type: RSA
Domains: cnapi.xxx.com
Expiry Date: 2019-05-02 11:46:07+00:00 (INVALID: EXPIRED)
Certificate Path: /etc/letsencrypt/live/cnapi.xxx.com/fullchain.pem
Private Key Path: /etc/letsencrypt/live/cnapi.xxx.com/privkey.pem
Certificate Name: repo.xxx.com
Serial Number: 3c0afafad7e521dcaaf89c3aa9f51b61724
Key Type: RSA
Domains: repo.xxx.com
Expiry Date: 2017-12-19 06:59:00+00:00 (INVALID: EXPIRED)
Certificate Path: /etc/letsencrypt/live/repo.xxx.com/fullchain.pem
Private Key Path: /etc/letsencrypt/live/repo.xxx.com/privkey.pem
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
通过证书信息,我们知道证书过期时间为2021-08-03 01:22:38
。
2. 使用强制更新证书命令
为什么要强制更新呢?
因为crontab是不能直接按天数定时执行任务的。而且当证书还有效时,并不会更新证书。当证书离过期时间很接近时,执行更新才会真正更新SSL证书。所以直接定时强制更证书了。
当然如果你要想按天数定时执行,也是可以间接实现的。
这些对我来说不是重点,如果你需要实现按天执行,可以参考crontab中如何实现每隔多少天执行一次脚本
。
certbot 强制更新证书只用加上 --force-renewal
参数, 执行命令 certbot renew --force-renewal
即可。如果是想更新指定的证书使用参数--cert-name
。
如:
sudo certbot renew --cert-name api.xxx.com --force-renewal
3. 编写更新证书脚本
对于要执行的命令比较长时,写成脚本更加方便。
sudo vim certbot-renew.sh
脚本文件写入如下内容:
#!/bin/bash
# author gan
#service tomcat restart
echo "==================Certbot Renew====================="
echo "==================`date`============================"
# 更新TLS证书
/usr/bin/certbot renew --cert-name api.kingtingtech.com --force-renewal
# 重启Web服务器
systemctl restart httpd
echo "==================End==============================="
4. 创建crontab任务
- 进入编辑crontab任务列表
sudo crontab -e
- 添加定时执行更新证书脚本的任务
0 3 1 * * /ktt/crons/certbot-renew.sh &>> /ktt/crons/certbot-renew.log
0 3 1 * *
指每个月1号3点0分执行任务&>>
&
指将标准输出和标准错误输出都重定向到certbot-renew.log文件;
>
指覆盖写入到文件;
>>
指追加写入到文件。
bash手册:
standard error: &>word and >&word Of the two forms, the first is preferred. This is semantically equiva- lent to >word 2>&1
- 保存
支持🤟
- 🎸 [关注❤️我吧],我会持续更新的。
- 🎸 [点个👍赞吧],码字不易麻烦了。