certbot命令申请免费的SSL证书并自动续期

申请证书

安装snap命令(大部分系统自带无需安装)

sudo apt-get install snapd

确保snap版本是最新的

sudo snap install core; sudo snap refresh core

删除Certbot -auto和任何Certbot操作系统包(如果安装了任何Certbot包)

sudo apt-get remove certbot

安装Certbot

sudo snap install --classic certbot

创建certbot软连接

sudo ln -s /snap/bin/certbot /usr/bin/certbot

申请证书

1
2
3
4
5
6
#执行命令根据提示完成申请
certbot certonly --webroot -w /home/ubuntu/code/www/blog_server/html/blog -d inktea.xyz -d www.inktea.xyz

#如果没有server执行(Certbot会自动启用网站的443/80端口来进行验证,确保443/80端口未被占用)
#建议使用上面命令申请,避免续费占用80端口
certbot certonly --standalone -d inktea.xyz -d www.inktea.xyz

命令说明

1
2
3
4
5
6
7
8
certonly        	#获取或更新证书,但是不安装
--webroot #通过访问网站目录中的验证并生成证书
--standalone #运行一个独立的网页服务器用于身份认证
-d #指定证书对应的域名列表
-w #指定网站目录

#默认证书路径: /etc/letsencrypt/live/inktea.xyz/fullchain.pem
#默认密钥路径: /etc/letsencrypt/live/inktea.xyz/privkey.pem

自动续期证书

系统上的Certbot包附带一个cron作业和systemd计时器

检查cron服务状态(保证服务处于运行状态)

1
2
3
4
5
6
service cron status

#如果未安装,执行命令:
#sudo apt-get crontabs
#如果未启动,执行命令:
#service cron start

创建并编辑用户任务(cron文件)

crontab -e

加入续期命令

1
2
3
4
5
6
7
8
#每隔10天18点整自动执行检查续期命令一次,续费成功后运行hook命令刷新nginx配置
# --deploy-hook 续费成功后执行命令(测试好像无效)
# --pre-hook 每次续费前执行命令(测试好像无效)
# --post-hook 每次续费后执行命令 (测试好像无效)
# 0 18 */10 * * /bin/certbot renew --deploy-hook "/usr/local/openresty/nginx/sbin/nginx -s reload"

# 每隔10天18点整自动执行检查续期命令一次,并重启nginx
0 18 */10 * * /bin/certbot renew | /usr/local/openresty/nginx/sbin/nginx -s reload

重新加载服务

service cron reload

测试自动续期(如果使用–standalone申请证书确保80端口未被占用)

sudo certbot renew --dry-run

详细cron服务
Ubuntu定时任务Crontab
Certbot的官网
https://certbot.eff.org/
Certbot指南
https://eff-certbot.readthedocs.io/en/stable/using.html


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!