这是一套我常用搭建网站时生成90天证书的代码
每次运行都会检测证书有效期然后自动续时到90天
超级实用
首先Linux中python的方法就不多说了
以下操作方式是在debian进行的
看完感觉好别忘了点个赞 谢谢
直接安装环境
sudo apt update
sudo apt install certbot
如果你的linux没有pip请安装pip
sudo apt install python3-pip -y
接下来实用这个祖传的神秘代码
把这里填写你的域名
domain = "你购买的域名" # 替换为你自己的域名
别忘了设置你域名的DNS指向IP
其他的地方就不用改了
最后很重要一点:关闭Nginx,因为证书需要验证80端口,Nginx占用时会失败
下面是完整代码
import subprocess
import os
import time
# 设置域名
domain = "你购买的域名" # 替换为你自己的域名
# 证书存储目录(标准 Let’s Encrypt 路径)
cert_directory = f"/etc/letsencrypt/live/{domain}"
# 生成证书的函数
def generate_certificate(domain):
try:
# 确保证书目录存在
os.makedirs(cert_directory, exist_ok=True)
# 执行 certbot 生成证书
print(f"正在为 {domain} 生成 Let's Encrypt 证书...")
subprocess.run(
["sudo", "certbot", "certonly", "--standalone", "-d", domain,
"--agree-tos", "--non-interactive", "--email", "[email protected]"],
check=True
)
print("证书生成成功!")
except subprocess.CalledProcessError as e:
print(f"生成证书失败: {e}")
# 查询证书是否生成
def check_certificate():
cert_path = cert_directory
if os.path.exists(cert_path):
print(f"证书已生成,存储路径:{cert_path}")
return True
else:
print("证书未生成,请确保证书生成过程成功")
return False
# 获取证书路径
def get_certificate_files():
if check_certificate():
cert_path = f"{cert_directory}/fullchain.pem"
key_path = f"{cert_directory}/privkey.pem"
print(f"证书文件路径:{cert_path}")
print(f"私钥文件路径:{key_path}")
return cert_path, key_path
else:
return None, None
# 检查证书有效期
def check_certificate_expiry(cert_path):
try:
result = subprocess.run(
["openssl", "x509", "-enddate", "-noout", "-in", cert_path],
capture_output=True, text=True
)
expiry_date_str = result.stdout.strip().split("=")[-1]
expiry_date = time.strptime(expiry_date_str, "%b %d %H:%M:%S %Y GMT")
expiry_timestamp = time.mktime(expiry_date)
current_timestamp = time.time()
days_until_expiry = (expiry_timestamp - current_timestamp) / (60 * 60 * 24)
print(f"证书到期剩余天数:{days_until_expiry:.2f}天")
return days_until_expiry
except Exception as e:
print(f"获取证书有效期失败: {e}")
return None
# 自动续费证书
def renew_certificate():
try:
print("证书即将到期,正在进行自动续费...")
subprocess.run(
["sudo", "certbot", "renew", "--non-interactive", "--quiet"],
check=True
)
print("证书续费成功!")
except subprocess.CalledProcessError as e:
print(f"证书续费失败: {e}")
# 主函数
def main():
generate_certificate(domain)
cert_path, _ = get_certificate_files()
if cert_path:
days_until_expiry = check_certificate_expiry(cert_path)
if days_until_expiry is not None and days_until_expiry < 30:
renew_certificate()
print(f"证书路径: {cert_path}")
else:
print("证书生成失败")
if __name__ == "__main__":
main()