logoSpectreAlan's blogs
Certbot创建免费SSL证书
标签:
Linux
Nginx
Centos
类别:服务器
创建时间: 2023-12-26 11:17:09
字数总计: 2.38 k
建议阅读时长: 3 分钟
阅读量: 1060

安装snapd

1yum install snapd -y 2# 如果提示没有可用软件包 snapd则安装EPEL存储库 3# sudo yum install epel-release

启用snap的systemd

systemctl enable --now snapd.socket

启用快照支持

sudo ln -s /var/lib/snapd/snap /snap

卸载旧的certbot

yum remove certbot

安装certbot

sudo snap install --classic certbot

创建软链接

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

创建证书

一、NGINX模式

certbot certonly --nginx -d example.com

二、webroot模式

certbot certonly --webroot -w /www/example -d example.com -d www.example.com

使用 --webroot 模式会在 /www/example 中创建 .well-known 文件夹,这个文件夹里面包含了一些验证文件,certbot 会通过访问 example.com/.well-known/acme-challenge 来验证你的域名是否绑定的这个服务器

三、standalone模式

certbot certonly --standalone -d example.com -d www.example.com

standalone模式不需要指定网站根目录,他会自动启用服务器的443端口,来验证域名的归属。我们有其他服务(例如nginx)占用了443端口,就必须先停止这些服务,在证书生成完毕后,再启用

自动更新 SSL 证书

certbot提供的证书只有90天的有效期,于是需要更新证书

certbot renew --dry-run

如果使用standalone模式报如下错,则先停止占用80/443的服务即可

Attempting to renew cert from /etc/letsencrypt/renewal/api.diamondfsd.com.conf produced an unexpected error: At least one of the required ports is already taken.. Skipping.

每次都手动更新显得很麻烦,于是创建一个定时任务

crontab -e

在新开的窗口键入

30 3 * */2 * certbot renew --pre-hook "service nginx stop" --post-hook "service nginx start"

每隔 两个月的 凌晨 3:30 执行更新操作

1# 列出当前用户的计划任务 2crontab -l

制作一个批量脚本

  • 创建一个目录 /home/ssl

    1 mkdir -p /home/ssl 2 cd /home/ssl
  • 创建一个脚本run.sh

    1#!/bin/bash 2 3# 检查 domains.txt 文件是否存在 4if [ ! -f "domains.txt" ]; then 5 echo "Error: domains.txt file not found." 6 exit 1 7fi 8 9# 从 domains.txt 文件中读取域名到数组 10readarray -t domains < domains.txt 11 12# 循环遍历域名数组 13for domain in "${domains[@]}" 14do 15 # 去除域名前后的空格和换行符 16 domain=$(echo "$domain" | tr -d '[:space:]') 17 18 # 执行 certbot 命令,并将输出保存到日志文件 19 certbot certonly --nginx -d "$domain" >> certbot.log 2>&1 20 21 # 检查 certbot 命令的返回状态 22 if [ $? -eq 0 ]; then 23 echo "Certificate for $domain successfully obtained." 24 else 25 echo "Error obtaining certificate for $domain. See certbot.log for details." 26 fi 27done
  • 创建一个domains.txt

    1example1.com 2example2.com 3example3.com
  • 执行脚本

    bash run.sh
吐槽一下
copyright