用certbot申请免费的域名证书
Certbot是一个由Electronic Frontier Foundation(EFF)赞助的开源工具,用于自动化管理和部署SSL/TLS证书。SSL/TLS证书是用于加密网站与用户之间传输的数据的一种安全协议。Certbot的主要目的是使网站管理员能够轻松获取、部署和更新这些证书,以确保网站的安全性。
Certbot支持许多常见的Web服务器,包括但不限于Apache、Nginx、Certbot还提供了一个通用的插件系统,使其能够与其他Web服务器和环境集成。
Certbot的工作原理是通过与Let's Encrypt通信来获取免费的SSL/TLS证书。Let's Encrypt是一个非营利性的证书颁发机构,致力于提供免费、自动化和开放的SSL/TLS证书服务,以推动互联网上更广泛的加密使用。Certbot与Let's Encrypt的结合使得网站管理员能够方便地为他们的网站启用HTTPS,提高网站的安全性和用户隐私。
SSL证书可以让数据加密进行通信,常用于网站客户端和服务端之间通信使用,免费证书Let's Encrypt机构利于推进所有网站创建SSL证书安全通信。
安全通信443端口,目前TLS 1.3是最新版本。
Debian/Ubuntu安装certbot
apt update -y && apt install -y certbot
CentOS安装certbot
yum -y update && yum -y install certbot
Alpine Linux安装certbot
apk update && apk add certbot
申请证书
确认80和443未被占用
curl -s ipv4.ip.sb #查看主机ip
certbot certonly --standalone -d 自己的域名 --email chn.shilei@outlook.com --agree-tos --no-eff-email --force-renewal
证书存放目录
/etc/letsencrypt/live/
自动续签脚本
vim auto_cert_renewal.sh
# 定义证书存储目录
certs_directory="/etc/letsencrypt/live/"
days_before_expiry=5 # 设置在证书到期前几天触发续签
# 遍历所有证书文件
for cert_dir in $certs_directory*; do
# 获取域名
domain=$(basename "$cert_dir")
# 忽略 README 目录
if [ "$domain" = "README" ]; then
continue
fi
# 输出正在检查的证书信息
echo "检查证书过期日期: ${domain}"
# 获取fullchain.pem文件路径
cert_file="${cert_dir}/fullchain.pem"
# 获取证书过期日期
expiration_date=$(openssl x509 -enddate -noout -in "${cert_file}" | cut -d "=" -f 2-)
# 输出证书过期日期
echo "过期日期: ${expiration_date}"
# 将日期转换为时间戳
expiration_timestamp=$(date -d "${expiration_date}" +%s)
current_timestamp=$(date +%s)
# 计算距离过期还有几天
days_until_expiry=$(( ($expiration_timestamp - $current_timestamp) / 86400 ))
# 检查是否需要续签(在满足续签条件的情况下)
if [ $days_until_expiry -le $days_before_expiry ]; then
echo "证书将在${days_before_expiry}天内过期,正在进行自动续签。"
# 停止 Nginx
systemctl stop nginx
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F
ip6tables -P INPUT ACCEPT
ip6tables -P FORWARD ACCEPT
ip6tables -P OUTPUT ACCEPT
ip6tables -F
# 续签证书
certbot certonly --standalone -d $domain --email chn.shilei@outlook.com --agree-tos --no-eff-email --force-renewal
# 启动 Nginx
systemctl start nginx
echo "证书已成功续签。"
else
# 若未满足续签条件,则输出证书仍然有效
echo "证书仍然有效,距离过期还有 ${days_until_expiry} 天。"
fi
# 输出分隔线
echo "--------------------------"
done
chmod +x auto_cert_renewal.sh #赋予权限
./auto_cert_renewal.sh #执行脚本
定时执行
echo "0 0 * * * cd ~ && ./auto_cert_renewal-1.sh" | crontab - #写入定时任务
crontab -e #查看定时任务
DNS方式申请(国内申请可用)
certbot certonly --manual --preferred-challenges dns -d example.com
#example.com改成自己的域名
到域名后台解析一个TXT记录
填写名称和值
解析后5分钟
回到SSH终端回车继续申请
评论区