logging
This commit is contained in:
511
certpusher.py
511
certpusher.py
@@ -1,8 +1,7 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""
|
"""
|
||||||
CertPusher - Automated SSL Certificate Distribution Tool
|
CertPusher - Automated SSL Certificate Distribution Tool
|
||||||
Distributes SSL certificates to remote servers via SSH/SCP
|
Version 1.1 - With unified certificate checking for all host types
|
||||||
Supports standard Linux servers, MikroTik RouterOS, and Proxmox VE
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import configparser
|
import configparser
|
||||||
@@ -21,12 +20,12 @@ from scp import SCPClient
|
|||||||
import requests
|
import requests
|
||||||
from cryptography import x509
|
from cryptography import x509
|
||||||
from cryptography.hazmat.backends import default_backend
|
from cryptography.hazmat.backends import default_backend
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
|
||||||
# Create logs directory if it doesn't exist
|
# Create logs directory
|
||||||
LOG_DIR = Path(__file__).parent / 'logs'
|
LOG_DIR = Path(__file__).parent / 'logs'
|
||||||
LOG_DIR.mkdir(exist_ok=True)
|
LOG_DIR.mkdir(exist_ok=True)
|
||||||
|
|
||||||
# Logging configuration
|
|
||||||
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||||
LOG_FILE = LOG_DIR / f'certpusher_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
|
LOG_FILE = LOG_DIR / f'certpusher_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
|
||||||
|
|
||||||
@@ -43,7 +42,6 @@ def setup_logging(debug: bool = False):
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Reduce paramiko logging noise
|
|
||||||
logging.getLogger('paramiko').setLevel(logging.WARNING)
|
logging.getLogger('paramiko').setLevel(logging.WARNING)
|
||||||
logging.getLogger('paramiko.transport').setLevel(logging.WARNING)
|
logging.getLogger('paramiko.transport').setLevel(logging.WARNING)
|
||||||
|
|
||||||
@@ -93,16 +91,13 @@ class CertificateManager:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def compare_certificates(cert1: x509.Certificate, cert2: x509.Certificate) -> bool:
|
def compare_certificates(cert1: x509.Certificate, cert2: x509.Certificate) -> bool:
|
||||||
"""Compare two certificates by serial number and fingerprint"""
|
"""Compare two certificates by serial number"""
|
||||||
try:
|
try:
|
||||||
same_serial = cert1.serial_number == cert2.serial_number
|
serial1 = format(cert1.serial_number, 'X').upper()
|
||||||
|
serial2 = format(cert2.serial_number, 'X').upper()
|
||||||
|
|
||||||
from cryptography.hazmat.primitives import hashes
|
logger.debug(f"Comparing serials: {serial1} vs {serial2}")
|
||||||
fingerprint1 = cert1.fingerprint(hashes.SHA256())
|
return serial1 == serial2
|
||||||
fingerprint2 = cert2.fingerprint(hashes.SHA256())
|
|
||||||
same_fingerprint = fingerprint1 == fingerprint2
|
|
||||||
|
|
||||||
return same_serial and same_fingerprint
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to compare certificates: {e}")
|
logger.error(f"Failed to compare certificates: {e}")
|
||||||
return False
|
return False
|
||||||
@@ -112,21 +107,14 @@ class CertificateManager:
|
|||||||
"""Get human-readable certificate information"""
|
"""Get human-readable certificate information"""
|
||||||
try:
|
try:
|
||||||
subject = cert.subject.rfc4514_string()
|
subject = cert.subject.rfc4514_string()
|
||||||
issuer = cert.issuer.rfc4514_string()
|
|
||||||
valid_from = cert.not_valid_before_utc
|
|
||||||
valid_to = cert.not_valid_after_utc
|
valid_to = cert.not_valid_after_utc
|
||||||
|
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
days_left = (valid_to - now).days
|
days_left = (valid_to - now).days
|
||||||
|
|
||||||
return f"""
|
return f"""Certificate: {subject}
|
||||||
Certificate Info:
|
Serial: {format(cert.serial_number, 'X').upper()}
|
||||||
Subject: {subject}
|
Expires: {valid_to}
|
||||||
Issuer: {issuer}
|
Days left: {days_left}"""
|
||||||
Valid From: {valid_from}
|
|
||||||
Valid To: {valid_to}
|
|
||||||
Days Until Expiry: {days_left}
|
|
||||||
"""
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Unable to extract certificate info: {e}"
|
return f"Unable to extract certificate info: {e}"
|
||||||
|
|
||||||
@@ -182,13 +170,13 @@ class SSHManager:
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"SSH connection failed to {self.hostname}:{self.port}: {e}")
|
logger.error(f"SSH connection failed: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def upload_file(self, local_path: str, remote_path: str) -> bool:
|
def upload_file(self, local_path: str, remote_path: str) -> bool:
|
||||||
"""Upload file via SCP"""
|
"""Upload file via SCP"""
|
||||||
try:
|
try:
|
||||||
logger.info(f"Uploading to {self.hostname}:{remote_path}")
|
logger.info(f"Uploading to {remote_path}")
|
||||||
|
|
||||||
remote_dir = os.path.dirname(remote_path)
|
remote_dir = os.path.dirname(remote_path)
|
||||||
if remote_dir:
|
if remote_dir:
|
||||||
@@ -215,13 +203,10 @@ class SSHManager:
|
|||||||
stdout_text = stdout.read().decode('utf-8', errors='ignore')
|
stdout_text = stdout.read().decode('utf-8', errors='ignore')
|
||||||
stderr_text = stderr.read().decode('utf-8', errors='ignore')
|
stderr_text = stderr.read().decode('utf-8', errors='ignore')
|
||||||
|
|
||||||
if exit_status == 0:
|
if exit_status != 0 and not ignore_error:
|
||||||
logger.debug(f"Command completed successfully")
|
logger.error(f"Command failed with exit code {exit_status}")
|
||||||
else:
|
if stderr_text:
|
||||||
if not ignore_error:
|
logger.debug(f"Error: {stderr_text}")
|
||||||
logger.error(f"Command failed with exit code {exit_status}")
|
|
||||||
if stderr_text:
|
|
||||||
logger.error(f"Error: {stderr_text}")
|
|
||||||
|
|
||||||
return exit_status == 0, stdout_text, stderr_text
|
return exit_status == 0, stdout_text, stderr_text
|
||||||
|
|
||||||
@@ -229,11 +214,49 @@ class SSHManager:
|
|||||||
logger.error(f"Command execution failed: {e}")
|
logger.error(f"Command execution failed: {e}")
|
||||||
return False, "", str(e)
|
return False, "", str(e)
|
||||||
|
|
||||||
|
def check_remote_certificate(self, remote_cert_path: str, source_cert: x509.Certificate) -> bool:
|
||||||
|
"""
|
||||||
|
Check if remote certificate matches source certificate
|
||||||
|
Returns True if upload needed, False if certificates match
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
logger.info("Checking remote certificate via SSH")
|
||||||
|
|
||||||
|
# Try to read and compare certificate via SSH
|
||||||
|
success, stdout, stderr = self.execute_command(
|
||||||
|
f'openssl x509 -in {remote_cert_path} -noout -serial 2>/dev/null || echo "NOTFOUND"',
|
||||||
|
ignore_error=True
|
||||||
|
)
|
||||||
|
|
||||||
|
if success and stdout and "NOTFOUND" not in stdout:
|
||||||
|
serial_match = re.search(r'serial=([A-F0-9]+)', stdout, re.IGNORECASE)
|
||||||
|
|
||||||
|
if serial_match:
|
||||||
|
remote_serial = serial_match.group(1).upper()
|
||||||
|
source_serial = format(source_cert.serial_number, 'X').upper()
|
||||||
|
|
||||||
|
logger.info(f"Source serial: {source_serial}")
|
||||||
|
logger.info(f"Remote serial: {remote_serial}")
|
||||||
|
|
||||||
|
if source_serial == remote_serial:
|
||||||
|
logger.info("✓ Certificates match. Skipping upload.")
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
logger.info("✗ Certificates differ. Upload needed.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.warning("Could not read remote certificate via SSH")
|
||||||
|
return True # Upload if we can't verify
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Error checking remote certificate: {e}")
|
||||||
|
return True
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
"""Close SSH connection"""
|
"""Close SSH connection"""
|
||||||
if self.ssh_client:
|
if self.ssh_client:
|
||||||
self.ssh_client.close()
|
self.ssh_client.close()
|
||||||
logger.debug(f"Disconnected from {self.hostname}")
|
logger.debug(f"Disconnected")
|
||||||
|
|
||||||
|
|
||||||
class MikroTikManager(SSHManager):
|
class MikroTikManager(SSHManager):
|
||||||
@@ -242,13 +265,9 @@ class MikroTikManager(SSHManager):
|
|||||||
def __init__(self, hostname: str, port: int, username: str, key_path: str):
|
def __init__(self, hostname: str, port: int, username: str, key_path: str):
|
||||||
super().__init__(hostname, port, username, key_path)
|
super().__init__(hostname, port, username, key_path)
|
||||||
self.cert_name = "ssl-cert"
|
self.cert_name = "ssl-cert"
|
||||||
self.key_name = "ssl-key"
|
|
||||||
|
|
||||||
def check_certificate_expiry(self, source_cert: x509.Certificate) -> bool:
|
def check_certificate_expiry(self, source_cert: x509.Certificate) -> bool:
|
||||||
"""
|
"""Check if certificate on MikroTik needs update"""
|
||||||
Check if certificate on MikroTik needs update
|
|
||||||
Returns True if upload needed, False if current cert is OK
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
logger.info("Checking MikroTik certificate")
|
logger.info("Checking MikroTik certificate")
|
||||||
|
|
||||||
@@ -258,13 +277,13 @@ class MikroTikManager(SSHManager):
|
|||||||
)
|
)
|
||||||
|
|
||||||
if not success or not stdout:
|
if not success or not stdout:
|
||||||
logger.info("No certificate found on MikroTik. Upload needed.")
|
logger.info("No certificate found. Upload needed.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
invalid_after_match = re.search(r'invalid-after:\s+([a-zA-Z]{3}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2})', stdout)
|
invalid_after_match = re.search(r'invalid-after:\s+([a-zA-Z]{3}/\d{2}/\d{4}\s+\d{2}:\d{2}:\d{2})', stdout)
|
||||||
|
|
||||||
if not invalid_after_match:
|
if not invalid_after_match:
|
||||||
logger.warning("Could not parse certificate expiry. Proceeding with upload.")
|
logger.warning("Could not parse expiry. Proceeding with upload.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
mikrotik_expiry_str = invalid_after_match.group(1)
|
mikrotik_expiry_str = invalid_after_match.group(1)
|
||||||
@@ -272,44 +291,44 @@ class MikroTikManager(SSHManager):
|
|||||||
try:
|
try:
|
||||||
mikrotik_expiry = datetime.strptime(mikrotik_expiry_str, '%b/%d/%Y %H:%M:%S')
|
mikrotik_expiry = datetime.strptime(mikrotik_expiry_str, '%b/%d/%Y %H:%M:%S')
|
||||||
mikrotik_expiry = mikrotik_expiry.replace(tzinfo=timezone.utc)
|
mikrotik_expiry = mikrotik_expiry.replace(tzinfo=timezone.utc)
|
||||||
except Exception as e:
|
except Exception:
|
||||||
logger.warning(f"Could not parse date: {e}. Proceeding with upload.")
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
source_expiry = source_cert.not_valid_after_utc
|
source_expiry = source_cert.not_valid_after_utc
|
||||||
time_diff = abs((source_expiry - mikrotik_expiry).total_seconds())
|
time_diff = abs((source_expiry - mikrotik_expiry).total_seconds())
|
||||||
|
|
||||||
if time_diff < 86400:
|
if time_diff < 86400:
|
||||||
logger.info("✓ MikroTik certificate is current. Skipping upload.")
|
logger.info("✓ MikroTik certificate is current. Skipping.")
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
logger.info(f"MikroTik certificate differs. Upload needed.")
|
logger.info(f"MikroTik certificate differs. Upload needed.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Error checking certificate: {e}. Proceeding with upload.")
|
logger.warning(f"Error checking: {e}. Proceeding with upload.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def upload_certificate(self, cert_path: str, key_path: str = None, check_first: bool = True, source_cert: x509.Certificate = None) -> bool:
|
def upload_certificate(self, cert_path: str, key_path: str, check_first: bool, source_cert: x509.Certificate) -> Tuple[bool, bool]:
|
||||||
"""Upload and import certificate to MikroTik RouterOS"""
|
"""
|
||||||
|
Upload certificate to MikroTik
|
||||||
|
Returns (success, was_uploaded)
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
logger.info(f"MikroTik certificate deployment")
|
|
||||||
|
|
||||||
if check_first and source_cert:
|
if check_first and source_cert:
|
||||||
if not self.check_certificate_expiry(source_cert):
|
if not self.check_certificate_expiry(source_cert):
|
||||||
return True
|
return True, False # Success but skipped
|
||||||
|
|
||||||
|
logger.info("Deploying MikroTik certificate")
|
||||||
|
|
||||||
logger.debug("Disabling www-ssl service")
|
|
||||||
self.execute_command('/ip service disable www-ssl', ignore_error=True)
|
self.execute_command('/ip service disable www-ssl', ignore_error=True)
|
||||||
|
|
||||||
logger.debug("Removing old certificates")
|
|
||||||
cleanup_commands = [
|
cleanup_commands = [
|
||||||
f'/certificate remove [find name~"{self.cert_name}"]',
|
f'/certificate remove [find name~"{self.cert_name}"]',
|
||||||
f'/file remove "{self.cert_name}.pem"',
|
f'/file remove "{self.cert_name}.pem"',
|
||||||
]
|
]
|
||||||
|
|
||||||
if key_path:
|
if key_path:
|
||||||
cleanup_commands.append(f'/file remove "{self.key_name}.pem"')
|
cleanup_commands.append(f'/file remove "ssl-key.pem"')
|
||||||
|
|
||||||
for cmd in cleanup_commands:
|
for cmd in cleanup_commands:
|
||||||
self.execute_command(cmd, ignore_error=True)
|
self.execute_command(cmd, ignore_error=True)
|
||||||
@@ -321,20 +340,14 @@ class MikroTikManager(SSHManager):
|
|||||||
if key_path:
|
if key_path:
|
||||||
logger.info("Uploading private key")
|
logger.info("Uploading private key")
|
||||||
with SCPClient(self.ssh_client.get_transport()) as scp:
|
with SCPClient(self.ssh_client.get_transport()) as scp:
|
||||||
scp.put(key_path, f'{self.key_name}.pem')
|
scp.put(key_path, 'ssl-key.pem')
|
||||||
|
|
||||||
logger.info("Importing certificate")
|
logger.info("Importing certificate")
|
||||||
import_cmd = f'/certificate import file-name={self.cert_name}.pem passphrase=""'
|
self.execute_command(f'/certificate import file-name={self.cert_name}.pem passphrase=""', timeout=30)
|
||||||
success, stdout, stderr = self.execute_command(import_cmd, timeout=30)
|
|
||||||
|
|
||||||
if not success and "failure" in stderr.lower():
|
|
||||||
logger.error(f"Certificate import failed: {stderr}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
import time
|
import time
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
|
||||||
logger.info("Configuring www-ssl service")
|
|
||||||
config_commands = [
|
config_commands = [
|
||||||
f'/ip service set www-ssl certificate={self.cert_name}_0',
|
f'/ip service set www-ssl certificate={self.cert_name}_0',
|
||||||
'/ip service enable www-ssl',
|
'/ip service enable www-ssl',
|
||||||
@@ -344,136 +357,106 @@ class MikroTikManager(SSHManager):
|
|||||||
self.execute_command(cmd, ignore_error=True)
|
self.execute_command(cmd, ignore_error=True)
|
||||||
|
|
||||||
logger.info(f"✓ MikroTik deployment successful")
|
logger.info(f"✓ MikroTik deployment successful")
|
||||||
return True
|
return True, True # Success and uploaded
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"MikroTik deployment failed: {e}")
|
logger.error(f"MikroTik deployment failed: {e}")
|
||||||
return False
|
return False, False
|
||||||
|
|
||||||
def verify_certificate(self) -> bool:
|
|
||||||
"""Verify certificate is properly installed"""
|
|
||||||
try:
|
|
||||||
success, stdout, stderr = self.execute_command(
|
|
||||||
'/certificate print detail where name~"ssl-cert"'
|
|
||||||
)
|
|
||||||
|
|
||||||
if success and stdout:
|
|
||||||
logger.debug(f"Certificate verified")
|
|
||||||
return True
|
|
||||||
|
|
||||||
return False
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Certificate verification failed: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
class ProxmoxManager(SSHManager):
|
class ProxmoxManager(SSHManager):
|
||||||
"""Specialized manager for Proxmox VE servers"""
|
"""Specialized manager for Proxmox VE servers"""
|
||||||
|
|
||||||
def check_certificate(self, source_cert: x509.Certificate, check_url: str) -> bool:
|
def check_certificate(self, source_cert: x509.Certificate, check_url: str) -> bool:
|
||||||
"""
|
"""Check if certificate on Proxmox needs update"""
|
||||||
Check if certificate on Proxmox needs update
|
|
||||||
Returns True if upload needed, False if current cert is OK
|
|
||||||
"""
|
|
||||||
try:
|
try:
|
||||||
logger.info("Checking Proxmox certificate")
|
logger.info("Checking Proxmox certificate")
|
||||||
|
|
||||||
# Method 1: Check via SSH - read cert file directly
|
# Method 1: Check via SSH
|
||||||
success, stdout, stderr = self.execute_command(
|
success, stdout, stderr = self.execute_command(
|
||||||
'openssl x509 -in /etc/pve/local/pveproxy-ssl.pem -noout -serial -dates',
|
'openssl x509 -in /etc/pve/local/pveproxy-ssl.pem -noout -serial -dates 2>/dev/null',
|
||||||
ignore_error=True
|
ignore_error=True
|
||||||
)
|
)
|
||||||
|
|
||||||
if success and stdout:
|
if success and stdout:
|
||||||
logger.debug(f"Proxmox certificate info:\n{stdout}")
|
serial_match = re.search(r'serial=([A-F0-9]+)', stdout, re.IGNORECASE)
|
||||||
|
|
||||||
# Parse serial number
|
if serial_match:
|
||||||
serial_match = re.search(r'serial=([A-F0-9]+)', stdout)
|
proxmox_serial = serial_match.group(1).upper()
|
||||||
# Parse expiry date
|
source_serial = format(source_cert.serial_number, 'X').upper()
|
||||||
notAfter_match = re.search(r'notAfter=(.+)', stdout)
|
|
||||||
|
|
||||||
if serial_match and notAfter_match:
|
|
||||||
proxmox_serial = serial_match.group(1)
|
|
||||||
source_serial = format(source_cert.serial_number, 'X')
|
|
||||||
|
|
||||||
logger.debug(f"Source serial: {source_serial}")
|
logger.info(f"Source serial: {source_serial}")
|
||||||
logger.debug(f"Proxmox serial: {proxmox_serial}")
|
logger.info(f"Proxmox serial: {proxmox_serial}")
|
||||||
|
|
||||||
if source_serial == proxmox_serial:
|
if source_serial == proxmox_serial:
|
||||||
logger.info("✓ Proxmox certificate is current. Skipping upload.")
|
logger.info("✓ Certificates match. Skipping upload.")
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
logger.info("Proxmox certificate differs. Upload needed.")
|
logger.info("✗ Certificates differ. Upload needed.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Method 2: Fallback - try URL check
|
# Method 2: Fallback to URL check
|
||||||
if check_url:
|
if check_url:
|
||||||
|
logger.info("Trying URL-based check")
|
||||||
cert_manager = CertificateManager()
|
cert_manager = CertificateManager()
|
||||||
remote_cert = cert_manager.get_cert_from_url(check_url)
|
remote_cert = cert_manager.get_cert_from_url(check_url)
|
||||||
|
|
||||||
if remote_cert:
|
if remote_cert and cert_manager.compare_certificates(source_cert, remote_cert):
|
||||||
if cert_manager.compare_certificates(source_cert, remote_cert):
|
logger.info("✓ Certificates match via URL. Skipping.")
|
||||||
logger.info("✓ Certificate verified via URL. Skipping upload.")
|
return False
|
||||||
return False
|
|
||||||
|
|
||||||
# If we can't verify, proceed with upload
|
logger.warning("Could not verify. Proceeding with upload.")
|
||||||
logger.warning("Could not verify certificate. Proceeding with upload.")
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Error checking certificate: {e}. Proceeding with upload.")
|
logger.warning(f"Error checking: {e}. Proceeding with upload.")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def upload_certificate(self, cert_path: str, key_path: str, check_first: bool = True,
|
def upload_certificate(self, cert_path: str, key_path: str, check_first: bool,
|
||||||
source_cert: x509.Certificate = None, check_url: str = None) -> bool:
|
source_cert: x509.Certificate, check_url: str) -> Tuple[bool, bool]:
|
||||||
"""Upload certificate to Proxmox VE"""
|
"""
|
||||||
|
Upload certificate to Proxmox
|
||||||
|
Returns (success, was_uploaded)
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
logger.info(f"Proxmox certificate deployment")
|
|
||||||
|
|
||||||
# Check if upload is needed
|
|
||||||
if check_first and source_cert:
|
if check_first and source_cert:
|
||||||
if not self.check_certificate(source_cert, check_url):
|
if not self.check_certificate(source_cert, check_url):
|
||||||
return True # Certificate is current, skip upload
|
return True, False # Success but skipped
|
||||||
|
|
||||||
|
logger.info("Deploying Proxmox certificate")
|
||||||
|
|
||||||
logger.info("Uploading certificate")
|
|
||||||
if not self.upload_file(cert_path, '/etc/pve/local/pveproxy-ssl.pem'):
|
if not self.upload_file(cert_path, '/etc/pve/local/pveproxy-ssl.pem'):
|
||||||
return False
|
return False, False
|
||||||
|
|
||||||
logger.info("Uploading private key")
|
|
||||||
if not self.upload_file(key_path, '/etc/pve/local/pveproxy-ssl.key'):
|
if not self.upload_file(key_path, '/etc/pve/local/pveproxy-ssl.key'):
|
||||||
return False
|
return False, False
|
||||||
|
|
||||||
logger.debug("Setting permissions")
|
|
||||||
commands = [
|
commands = [
|
||||||
'chmod 640 /etc/pve/local/pveproxy-ssl.key',
|
'chmod 640 /etc/pve/local/pveproxy-ssl.key',
|
||||||
'chown root:www-data /etc/pve/local/pveproxy-ssl.key',
|
'chown root:www-data /etc/pve/local/pveproxy-ssl.key',
|
||||||
]
|
]
|
||||||
|
|
||||||
for cmd in commands:
|
for cmd in commands:
|
||||||
self.execute_command(cmd, ignore_error=False)
|
self.execute_command(cmd)
|
||||||
|
|
||||||
logger.info("Restarting pveproxy")
|
logger.info("Restarting pveproxy")
|
||||||
success, stdout, stderr = self.execute_command('systemctl restart pveproxy', timeout=30)
|
self.execute_command('systemctl restart pveproxy', timeout=30)
|
||||||
|
|
||||||
if not success:
|
|
||||||
logger.error(f"Failed to restart pveproxy")
|
|
||||||
return False
|
|
||||||
|
|
||||||
import time
|
import time
|
||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
|
|
||||||
success, stdout, stderr = self.execute_command('systemctl is-active pveproxy')
|
success, stdout, _ = self.execute_command('systemctl is-active pveproxy')
|
||||||
if success and 'active' in stdout:
|
if success and 'active' in stdout:
|
||||||
logger.info(f"✓ Proxmox deployment successful")
|
logger.info(f"✓ Proxmox deployment successful")
|
||||||
return True
|
return True, True
|
||||||
else:
|
else:
|
||||||
logger.error("pveproxy service is not active")
|
logger.error("pveproxy not active")
|
||||||
return False
|
return False, False
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Proxmox deployment failed: {e}")
|
logger.error(f"Proxmox deployment failed: {e}")
|
||||||
return False
|
return False, False
|
||||||
|
|
||||||
|
|
||||||
class CertPusher:
|
class CertPusher:
|
||||||
"""Main application class"""
|
"""Main application class"""
|
||||||
@@ -482,61 +465,52 @@ class CertPusher:
|
|||||||
self.config_file = config_file
|
self.config_file = config_file
|
||||||
self.config = configparser.ConfigParser()
|
self.config = configparser.ConfigParser()
|
||||||
self.cert_manager = CertificateManager()
|
self.cert_manager = CertificateManager()
|
||||||
self.stats = {
|
self.stats = {'total': 0, 'uploaded': 0, 'skipped': 0, 'failed': 0}
|
||||||
'total': 0,
|
|
||||||
'uploaded': 0,
|
|
||||||
'skipped': 0,
|
|
||||||
'failed': 0
|
|
||||||
}
|
|
||||||
|
|
||||||
def load_config(self) -> bool:
|
def load_config(self) -> bool:
|
||||||
"""Load configuration from INI file"""
|
"""Load configuration"""
|
||||||
try:
|
try:
|
||||||
logger.info(f"Loading configuration from {self.config_file}")
|
logger.info(f"Loading config: {self.config_file}")
|
||||||
self.config.read(self.config_file)
|
self.config.read(self.config_file)
|
||||||
|
|
||||||
if 'global' not in self.config:
|
if 'global' not in self.config:
|
||||||
logger.error("Missing [global] section in config file")
|
logger.error("Missing [global] section")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
required_global = ['source_cert_path', 'default_ssh_key']
|
required = ['source_cert_path', 'default_ssh_key']
|
||||||
for key in required_global:
|
for key in required:
|
||||||
if not self.config.has_option('global', key):
|
if not self.config.has_option('global', key):
|
||||||
logger.error(f"Missing required global option: {key}")
|
logger.error(f"Missing: {key}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
logger.info(f"✓ Configuration loaded")
|
logger.info(f"✓ Config loaded ({len(self.config.sections()) - 1} hosts)")
|
||||||
logger.info(f"Found {len(self.config.sections()) - 1} host(s)")
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to load configuration: {e}")
|
logger.error(f"Config load failed: {e}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_key_path(self, section: str, cert_path: str) -> str:
|
def get_key_path(self, section: str, cert_path: str) -> str:
|
||||||
"""Get private key path for certificate"""
|
"""Get private key path"""
|
||||||
if self.config.has_option(section, 'source_key_path'):
|
if self.config.has_option(section, 'source_key_path'):
|
||||||
return self.config.get(section, 'source_key_path')
|
return self.config.get(section, 'source_key_path')
|
||||||
|
|
||||||
if self.config.has_option('global', 'source_key_path'):
|
if self.config.has_option('global', 'source_key_path'):
|
||||||
return self.config.get('global', 'source_key_path')
|
return self.config.get('global', 'source_key_path')
|
||||||
|
return cert_path.replace('fullchain.pem', 'privkey.pem').replace('cert.pem', 'privkey.pem')
|
||||||
key_path = cert_path.replace('fullchain.pem', 'privkey.pem').replace('cert.pem', 'privkey.pem')
|
|
||||||
return key_path
|
|
||||||
|
|
||||||
def process_mikrotik(self, section: str, hostname: str, port: int,
|
def process_mikrotik(self, section: str, hostname: str, port: int, username: str, ssh_key: str, source_cert_path: str) -> bool:
|
||||||
username: str, ssh_key: str, source_cert_path: str) -> bool:
|
"""Process MikroTik device"""
|
||||||
"""Process MikroTik device specifically"""
|
|
||||||
try:
|
try:
|
||||||
logger.info("Using MikroTik deployment method")
|
|
||||||
|
|
||||||
source_key_path = self.get_key_path(section, source_cert_path)
|
source_key_path = self.get_key_path(section, source_cert_path)
|
||||||
|
|
||||||
if not os.path.exists(source_key_path):
|
if not os.path.exists(source_key_path):
|
||||||
logger.error(f"Private key not found: {source_key_path}")
|
logger.error(f"Key not found: {source_key_path}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
source_cert = self.cert_manager.get_cert_from_file(source_cert_path)
|
source_cert = self.cert_manager.get_cert_from_file(source_cert_path)
|
||||||
|
if not source_cert:
|
||||||
|
return False
|
||||||
|
|
||||||
check_first = self.config.getboolean(section, 'check_before_upload', fallback=True)
|
check_first = self.config.getboolean(section, 'check_before_upload', fallback=True)
|
||||||
|
|
||||||
mikrotik = MikroTikManager(hostname, port, username, ssh_key)
|
mikrotik = MikroTikManager(hostname, port, username, ssh_key)
|
||||||
@@ -545,98 +519,73 @@ class CertPusher:
|
|||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
result = mikrotik.upload_certificate(source_cert_path, source_key_path, check_first, source_cert)
|
success, was_uploaded = mikrotik.upload_certificate(source_cert_path, source_key_path, check_first, source_cert)
|
||||||
|
mikrotik.disconnect()
|
||||||
|
|
||||||
if not result:
|
if success:
|
||||||
mikrotik.disconnect()
|
if was_uploaded:
|
||||||
|
self.stats['uploaded'] += 1
|
||||||
|
else:
|
||||||
|
self.stats['skipped'] += 1
|
||||||
|
logger.info("✓ MikroTik processed")
|
||||||
|
return True
|
||||||
|
else:
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
mikrotik.verify_certificate()
|
|
||||||
mikrotik.disconnect()
|
|
||||||
self.stats['uploaded'] += 1
|
|
||||||
logger.info(f"✓ MikroTik processed successfully")
|
|
||||||
return True
|
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"MikroTik processing failed: {e}")
|
logger.error(f"MikroTik failed: {e}")
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def process_proxmox(self, section: str, hostname: str, port: int,
|
def process_proxmox(self, section: str, hostname: str, port: int, username: str, ssh_key: str, source_cert_path: str) -> bool:
|
||||||
username: str, ssh_key: str, source_cert_path: str) -> bool:
|
"""Process Proxmox server"""
|
||||||
"""Process Proxmox VE server specifically"""
|
|
||||||
try:
|
try:
|
||||||
logger.info("Using Proxmox deployment method")
|
|
||||||
|
|
||||||
source_key_path = self.get_key_path(section, source_cert_path)
|
source_key_path = self.get_key_path(section, source_cert_path)
|
||||||
|
|
||||||
# Show which certificate we're using
|
|
||||||
logger.info(f"Source certificate: {source_cert_path}")
|
|
||||||
logger.info(f"Source key: {source_key_path}")
|
|
||||||
|
|
||||||
if not os.path.exists(source_key_path):
|
if not os.path.exists(source_key_path):
|
||||||
logger.error(f"Private key not found: {source_key_path}")
|
logger.error(f"Key not found: {source_key_path}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Load source certificate for comparison
|
|
||||||
source_cert = self.cert_manager.get_cert_from_file(source_cert_path)
|
source_cert = self.cert_manager.get_cert_from_file(source_cert_path)
|
||||||
|
if not source_cert:
|
||||||
if source_cert:
|
|
||||||
# Show source cert details
|
|
||||||
source_serial = format(source_cert.serial_number, 'X').upper()
|
|
||||||
logger.info(f"Source cert serial: {source_serial}")
|
|
||||||
logger.info(f"Source cert expires: {source_cert.not_valid_after_utc}")
|
|
||||||
else:
|
|
||||||
logger.error("Failed to load source certificate")
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Get check URL if available
|
logger.info(f"Using cert: {source_cert_path}")
|
||||||
|
logger.info(self.cert_manager.get_certificate_info(source_cert))
|
||||||
|
|
||||||
check_url = self.config.get(section, 'check_url', fallback=None)
|
check_url = self.config.get(section, 'check_url', fallback=None)
|
||||||
|
|
||||||
# Check if we should verify before upload
|
|
||||||
check_first = self.config.getboolean(section, 'check_before_upload', fallback=True)
|
check_first = self.config.getboolean(section, 'check_before_upload', fallback=True)
|
||||||
|
|
||||||
logger.info(f"Check before upload: {check_first}")
|
|
||||||
if check_url:
|
|
||||||
logger.info(f"Check URL: {check_url}")
|
|
||||||
|
|
||||||
proxmox = ProxmoxManager(hostname, port, username, ssh_key)
|
proxmox = ProxmoxManager(hostname, port, username, ssh_key)
|
||||||
|
|
||||||
if not proxmox.connect():
|
if not proxmox.connect():
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Upload with optional checking
|
success, was_uploaded = proxmox.upload_certificate(source_cert_path, source_key_path, check_first, source_cert, check_url)
|
||||||
result = proxmox.upload_certificate(source_cert_path, source_key_path,
|
|
||||||
check_first, source_cert, check_url)
|
|
||||||
|
|
||||||
proxmox.disconnect()
|
proxmox.disconnect()
|
||||||
|
|
||||||
if result:
|
if success:
|
||||||
# Check if it was actually uploaded or skipped
|
if was_uploaded:
|
||||||
# This is a bit tricky - we need to track this in upload_certificate
|
self.stats['uploaded'] += 1
|
||||||
self.stats['uploaded'] += 1
|
else:
|
||||||
logger.info(f"✓ Proxmox processed successfully")
|
self.stats['skipped'] += 1
|
||||||
|
logger.info("✓ Proxmox processed")
|
||||||
return True
|
return True
|
||||||
else:
|
else:
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Proxmox processing failed: {e}")
|
logger.error(f"Proxmox failed: {e}")
|
||||||
import traceback
|
|
||||||
logger.debug(traceback.format_exc())
|
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def process_host(self, section: str) -> bool:
|
def process_host(self, section: str) -> bool:
|
||||||
"""Process certificate deployment for a single host"""
|
"""Process standard host"""
|
||||||
try:
|
try:
|
||||||
logger.info(f"\n{'='*60}")
|
logger.info(f"\n{'='*60}\nProcessing: {section}\n{'='*60}")
|
||||||
logger.info(f"Processing: {section}")
|
|
||||||
logger.info(f"{'='*60}")
|
|
||||||
|
|
||||||
self.stats['total'] += 1
|
self.stats['total'] += 1
|
||||||
|
|
||||||
@@ -645,49 +594,33 @@ class CertPusher:
|
|||||||
username = self.config.get(section, 'username', fallback='root')
|
username = self.config.get(section, 'username', fallback='root')
|
||||||
device_type = self.config.get(section, 'type', fallback='standard')
|
device_type = self.config.get(section, 'type', fallback='standard')
|
||||||
|
|
||||||
if self.config.has_option(section, 'ssh_key_path'):
|
ssh_key = self.config.get(section, 'ssh_key_path', fallback=None) or self.config.get('global', 'default_ssh_key')
|
||||||
ssh_key = self.config.get(section, 'ssh_key_path')
|
source_cert_path = self.config.get(section, 'source_cert_path', fallback=None) or self.config.get('global', 'source_cert_path')
|
||||||
else:
|
|
||||||
ssh_key = self.config.get('global', 'default_ssh_key')
|
|
||||||
|
|
||||||
if self.config.has_option(section, 'source_cert_path'):
|
|
||||||
source_cert_path = self.config.get(section, 'source_cert_path')
|
|
||||||
logger.info(f"Using host-specific certificate")
|
|
||||||
else:
|
|
||||||
source_cert_path = self.config.get('global', 'source_cert_path')
|
|
||||||
|
|
||||||
if not os.path.exists(source_cert_path):
|
if not os.path.exists(source_cert_path):
|
||||||
logger.error(f"Certificate not found: {source_cert_path}")
|
logger.error(f"Certificate not found: {source_cert_path}")
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
logger.info(f"Host: {hostname}:{port}")
|
logger.info(f"Host: {hostname}:{port} ({device_type})")
|
||||||
logger.info(f"Type: {device_type}")
|
|
||||||
logger.info(f"User: {username}")
|
logger.info(f"User: {username}")
|
||||||
|
|
||||||
|
# Route to specialized handlers
|
||||||
if device_type.lower() == 'mikrotik':
|
if device_type.lower() == 'mikrotik':
|
||||||
return self.process_mikrotik(section, hostname, port, username, ssh_key, source_cert_path)
|
return self.process_mikrotik(section, hostname, port, username, ssh_key, source_cert_path)
|
||||||
elif device_type.lower() == 'proxmox':
|
elif device_type.lower() == 'proxmox':
|
||||||
return self.process_proxmox(section, hostname, port, username, ssh_key, source_cert_path)
|
return self.process_proxmox(section, hostname, port, username, ssh_key, source_cert_path)
|
||||||
|
|
||||||
|
# Standard host processing
|
||||||
remote_cert_path = self.config.get(section, 'remote_cert_path')
|
remote_cert_path = self.config.get(section, 'remote_cert_path')
|
||||||
post_upload_command = self.config.get(section, 'post_upload_command', fallback='')
|
post_upload_command = self.config.get(section, 'post_upload_command', fallback='')
|
||||||
check_url = self.config.get(section, 'check_url', fallback='')
|
check_url = self.config.get(section, 'check_url', fallback='')
|
||||||
|
check_first = self.config.getboolean(section, 'check_before_upload', fallback=True)
|
||||||
|
|
||||||
if check_url:
|
source_cert = self.cert_manager.get_cert_from_file(source_cert_path)
|
||||||
logger.info(f"Checking certificate at {check_url}")
|
if not source_cert:
|
||||||
source_cert = self.cert_manager.get_cert_from_file(source_cert_path)
|
self.stats['failed'] += 1
|
||||||
remote_cert = self.cert_manager.get_cert_from_url(check_url)
|
return False
|
||||||
|
|
||||||
if source_cert and remote_cert:
|
|
||||||
if self.cert_manager.compare_certificates(source_cert, remote_cert):
|
|
||||||
logger.info(f"✓ Certificate is up to date. Skipping.")
|
|
||||||
self.stats['skipped'] += 1
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
logger.info(f"Certificate is outdated. Uploading.")
|
|
||||||
else:
|
|
||||||
logger.warning(f"Could not compare certificates. Proceeding.")
|
|
||||||
|
|
||||||
ssh = SSHManager(hostname, port, username, ssh_key)
|
ssh = SSHManager(hostname, port, username, ssh_key)
|
||||||
|
|
||||||
@@ -695,65 +628,71 @@ class CertPusher:
|
|||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Check if upload needed
|
||||||
|
upload_needed = True
|
||||||
|
|
||||||
|
if check_first:
|
||||||
|
# Try SSH check first
|
||||||
|
if not ssh.check_remote_certificate(remote_cert_path, source_cert):
|
||||||
|
upload_needed = False
|
||||||
|
# Try URL check if SSH check failed
|
||||||
|
elif check_url:
|
||||||
|
logger.info(f"Checking via URL: {check_url}")
|
||||||
|
remote_cert = self.cert_manager.get_cert_from_url(check_url)
|
||||||
|
if remote_cert and self.cert_manager.compare_certificates(source_cert, remote_cert):
|
||||||
|
logger.info("✓ Certificate up to date via URL. Skipping.")
|
||||||
|
upload_needed = False
|
||||||
|
|
||||||
|
if not upload_needed:
|
||||||
|
ssh.disconnect()
|
||||||
|
self.stats['skipped'] += 1
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Upload certificate
|
||||||
if not ssh.upload_file(source_cert_path, remote_cert_path):
|
if not ssh.upload_file(source_cert_path, remote_cert_path):
|
||||||
ssh.disconnect()
|
ssh.disconnect()
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# Upload key if specified
|
||||||
if self.config.has_option(section, 'remote_key_path'):
|
if self.config.has_option(section, 'remote_key_path'):
|
||||||
remote_key_path = self.config.get(section, 'remote_key_path')
|
remote_key_path = self.config.get(section, 'remote_key_path')
|
||||||
source_key_path = self.get_key_path(section, source_cert_path)
|
source_key_path = self.get_key_path(section, source_cert_path)
|
||||||
|
|
||||||
logger.info(f"Uploading private key")
|
if os.path.exists(source_key_path):
|
||||||
|
ssh.upload_file(source_key_path, remote_key_path)
|
||||||
if not os.path.exists(source_key_path):
|
|
||||||
logger.error(f"Private key not found: {source_key_path}")
|
|
||||||
ssh.disconnect()
|
|
||||||
self.stats['failed'] += 1
|
|
||||||
return False
|
|
||||||
|
|
||||||
if not ssh.upload_file(source_key_path, remote_key_path):
|
|
||||||
logger.warning(f"Failed to upload private key")
|
|
||||||
|
|
||||||
|
# Additional files
|
||||||
if self.config.has_option(section, 'additional_files'):
|
if self.config.has_option(section, 'additional_files'):
|
||||||
additional_files = self.config.get(section, 'additional_files')
|
for file_pair in self.config.get(section, 'additional_files').split(','):
|
||||||
for file_pair in additional_files.split(','):
|
|
||||||
if ':' in file_pair:
|
if ':' in file_pair:
|
||||||
local, remote = file_pair.strip().split(':', 1)
|
local, remote = file_pair.strip().split(':', 1)
|
||||||
logger.info(f"Uploading additional: {os.path.basename(local)}")
|
ssh.upload_file(local, remote)
|
||||||
if not ssh.upload_file(local, remote):
|
|
||||||
logger.warning(f"Failed to upload additional file")
|
|
||||||
|
|
||||||
|
# Post-upload command
|
||||||
if post_upload_command:
|
if post_upload_command:
|
||||||
logger.info(f"Executing post-upload command")
|
logger.info("Executing post-upload command")
|
||||||
success, stdout, stderr = ssh.execute_command(post_upload_command)
|
ssh.execute_command(post_upload_command)
|
||||||
|
|
||||||
if not success:
|
|
||||||
logger.warning(f"Post-upload command failed")
|
|
||||||
else:
|
|
||||||
logger.info(f"✓ Post-upload command completed")
|
|
||||||
|
|
||||||
ssh.disconnect()
|
ssh.disconnect()
|
||||||
self.stats['uploaded'] += 1
|
self.stats['uploaded'] += 1
|
||||||
logger.info(f"✓ Host processed successfully")
|
logger.info("✓ Host processed")
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to process host: {e}")
|
logger.error(f"Failed: {e}")
|
||||||
self.stats['failed'] += 1
|
self.stats['failed'] += 1
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
"""Main execution method"""
|
"""Main execution"""
|
||||||
logger.info("="*60)
|
logger.info("="*60)
|
||||||
logger.info(" CertPusher - SSL Certificate Distribution")
|
logger.info(" CertPusher - SSL Certificate Distribution")
|
||||||
logger.info("="*60)
|
logger.info("="*60)
|
||||||
logger.info(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
logger.info(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||||
logger.info(f"Log file: {LOG_FILE}")
|
logger.info(f"Log: {LOG_FILE}\n")
|
||||||
logger.info("")
|
|
||||||
|
|
||||||
if not self.load_config():
|
if not self.load_config():
|
||||||
logger.error("Configuration loading failed")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
source_cert = self.config.get('global', 'source_cert_path')
|
source_cert = self.config.get('global', 'source_cert_path')
|
||||||
@@ -761,31 +700,21 @@ class CertPusher:
|
|||||||
logger.error(f"Source certificate not found: {source_cert}")
|
logger.error(f"Source certificate not found: {source_cert}")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
logger.info(f"Source certificate: {source_cert}")
|
logger.info(f"Global certificate: {source_cert}\n")
|
||||||
|
|
||||||
cert = self.cert_manager.get_cert_from_file(source_cert)
|
|
||||||
if cert:
|
|
||||||
logger.info(self.cert_manager.get_certificate_info(cert))
|
|
||||||
|
|
||||||
for section in self.config.sections():
|
for section in self.config.sections():
|
||||||
if section == 'global':
|
if section == 'global':
|
||||||
continue
|
continue
|
||||||
|
self.process_host(section)
|
||||||
try:
|
|
||||||
self.process_host(section)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Unexpected error: {e}")
|
|
||||||
self.stats['failed'] += 1
|
|
||||||
|
|
||||||
logger.info("\n" + "="*60)
|
logger.info("\n" + "="*60)
|
||||||
logger.info(" SUMMARY")
|
logger.info(" SUMMARY")
|
||||||
logger.info("="*60)
|
logger.info("="*60)
|
||||||
logger.info(f"Total hosts: {self.stats['total']}")
|
logger.info(f"Total: {self.stats['total']}")
|
||||||
logger.info(f"✓ Uploaded: {self.stats['uploaded']}")
|
logger.info(f"✓ Uploaded: {self.stats['uploaded']}")
|
||||||
logger.info(f"○ Skipped: {self.stats['skipped']}")
|
logger.info(f"○ Skipped: {self.stats['skipped']}")
|
||||||
logger.info(f"✗ Failed: {self.stats['failed']}")
|
logger.info(f"✗ Failed: {self.stats['failed']}")
|
||||||
logger.info("="*60)
|
logger.info("="*60)
|
||||||
logger.info(f"Finished: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
|
||||||
|
|
||||||
if self.stats['failed'] > 0:
|
if self.stats['failed'] > 0:
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -793,42 +722,30 @@ class CertPusher:
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Entry point"""
|
"""Entry point"""
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(description='CertPusher - SSL Certificate Distribution')
|
||||||
description='CertPusher - SSL Certificate Distribution Tool',
|
parser.add_argument('config', help='Configuration file')
|
||||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
||||||
epilog="""
|
|
||||||
Examples:
|
|
||||||
%(prog)s config.ini # Normal operation
|
|
||||||
%(prog)s config.ini --debug # Debug mode with verbose logging
|
|
||||||
%(prog)s config.ini -d # Same as above
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
parser.add_argument('config', help='Path to configuration file')
|
|
||||||
parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging')
|
parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging')
|
||||||
parser.add_argument('-v', '--version', action='version', version='CertPusher 1.0')
|
parser.add_argument('-v', '--version', action='version', version='CertPusher 1.1')
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
# Setup logging based on debug flag
|
|
||||||
setup_logging(debug=args.debug)
|
setup_logging(debug=args.debug)
|
||||||
|
|
||||||
print("""
|
print("""
|
||||||
╔═══════════════════════════════════════════════════════════╗
|
╔═══════════════════════════════════════════════════════════╗
|
||||||
║ CertPusher v1.0 ║
|
║ CertPusher v1.1 ║
|
||||||
║ Automated SSL Certificate Distribution Tool ║
|
║ Automated SSL Certificate Distribution Tool ║
|
||||||
╚═══════════════════════════════════════════════════════════╝
|
╚═══════════════════════════════════════════════════════════╝
|
||||||
""")
|
""")
|
||||||
|
|
||||||
if not os.path.exists(args.config):
|
if not os.path.exists(args.config):
|
||||||
print(f"Error: Configuration file '{args.config}' not found")
|
print(f"Error: Config file '{args.config}' not found")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
pusher = CertPusher(args.config)
|
pusher = CertPusher(args.config)
|
||||||
pusher.run()
|
pusher.run()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
print("\n\nInterrupted by user. Exiting...")
|
print("\n\nInterrupted. Exiting...")
|
||||||
sys.exit(130)
|
sys.exit(130)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Fatal error: {e}", exc_info=True)
|
logger.error(f"Fatal error: {e}", exc_info=True)
|
||||||
|
|||||||
Reference in New Issue
Block a user