配置块
#!/bin/bash
# 询问用户输入多个 SSL 证书目录
read -p "请输入 SSL 证书目录(多个目录请用空格分隔): " -a ssl_dirs
# 检查目录是否存在
for dir in "${ssl_dirs[@]}"; do
if [ ! -d "$dir" ]; then
echo "错误:目录 $dir 不存在,请检查路径是否正确。"
exit 1
fi
done
# 设置 unit 文件的路径
path_unit_file="/etc/systemd/system/nginx-cert-monitor.path"
service_unit_file="/etc/systemd/system/nginx-cert-restart.service"
# 创建 Path Unit 文件
echo "创建 Path Unit 文件..."
sudo tee $path_unit_file > /dev/null <<EOL
[Unit]
Description=Monitor Nginx SSL certificates for changes
[Path]
EOL
# 为每个输入的目录添加 PathModified 条目
for dir in "${ssl_dirs[@]}"; do
echo "PathModified=$dir" | sudo tee -a $path_unit_file > /dev/null
done
# 继续添加关联的 Service Unit
sudo tee -a $path_unit_file > /dev/null <<EOL
Unit=nginx-cert-restart.service
[Install]
WantedBy=multi-user.target
EOL
echo "Path Unit 文件已创建:$path_unit_file"
# 创建 Service Unit 文件
echo "创建 Service Unit 文件..."
sudo tee $service_unit_file > /dev/null <<EOL
[Unit]
Description=Restart Nginx when SSL certificates change
Wants=nginx-cert-monitor.path
[Service]
ExecStart=/bin/systemctl restart nginx
[Install]
WantedBy=multi-user.target
EOL
echo "Service Unit 文件已创建:$service_unit_file"
# 重新加载 systemd 守护进程
echo "重新加载 systemd 守护进程..."
sudo systemctl daemon-reload
# 启用并启动 Path Unit
echo "启用并启动 Nginx 证书监控..."
sudo systemctl enable nginx-cert-monitor.path
sudo systemctl start nginx-cert-monitor.path
# 检查 Path Unit 状态
echo "Nginx 证书监控已启用。当前状态:"
sudo systemctl status nginx-cert-monitor.path