我们需要通过FTP获取远程服务器上的SSL证书,域名列表保存在本地的domain.txt文件中,我们可以使用Python的ftplib库来连接FTP服务器,然后遍历域名列表,为每个域名创建对应的目录并下载SSL证书文件。下载完这些证书后,存放到指定的目录,并且重命名为nginx配置文件中的文件名,最后一步就是重启我们的nginx,具体的实现过程如下:

首先确保你的环境中安装了Python,然后创建一个Python脚本,比如命名为download_ssl_certificates.py

from ftplib import FTP
import os
import subprocess

# FTP服务器信息
ftp_server = "xx.xx.xx.xxx"
ftp_username = "ftpuser"
ftp_password = "xxxxx"

# 本地保存证书的目录
local_cert_dir = "/root/python"

# 确保本地目录存在
if not os.path.exists(local_cert_dir):
    os.makedirs(local_cert_dir)

# 读取域名列表
with open("domain.txt", "r") as file:
    domains = file.readlines()
domains = [domain.strip() for domain in domains]

def download_and_rename_certificate(domain):
    """为给定域名下载SSL证书并重命名"""
    remote_dir = f"/home/ftpuser/{domain}/"
    files_to_download = {"fullchain1.pem": f"{domain}.pem", "privkey1.pem": f"{domain}.key"}

    for remote_filename, new_filename in files_to_download.items():
        remote_path = os.path.join(remote_dir, remote_filename)
        local_path = os.path.join(local_cert_dir, new_filename)
        
        try:
            with FTP(ftp_server) as ftp:
                ftp.login(user=ftp_username, passwd=ftp_password)
                print(f"Downloading {remote_filename} for {domain}")
                
                with open(local_path, 'wb') as local_file:
                    ftp.retrbinary(f'RETR {remote_path}', local_file.write)
                
                print(f"{remote_filename} for {domain} downloaded and renamed to {new_filename} successfully.")
        except Exception as e:
            print(f"Error downloading {remote_filename} for {domain}: {e}")

def reload_nginx():
    """重新加载Nginx配置"""
    try:
        subprocess.run(['nginx', '-s', 'reload'], check=True)
        print("Nginx reloaded successfully.")
    except subprocess.CalledProcessError as e:
        print(f"Failed to reload Nginx: {e}")

if __name__ == "__main__":
    for domain in domains:
        download_and_rename_certificate(domain)
    
    # 下载并重命名完成后重新加载Nginx
    reload_nginx()

在运行此脚本之前,请确保你已经按照你的实际情况替换了脚本中的ftp_serverftp_usernameftp_password, 和local_cert_dir变量的值。此外,请确保domain.txt文件位于脚本同一目录下,并且列出了所有你想下载SSL证书的域名,每个域名占一行。

运行这个脚本,它将会为domain.txt中列出的每个域名连接到FTP服务器,尝试进入对应的域名目录并下载SSL证书文件到本地指定目录。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐