File: //lib64/nagios/plugins/check_ipaliases.py
#!/usr/bin/env python3
"""
This script checks additional IPs listed in /etc/ips on a cPanel/WHM server to ensure they are configured and active.
If any IPs are missing, it attempts to restart the 'ipaliases' service via /scripts/restartsrv_ipaliases.
- If all IPs are up: exits OK (code 0)
- If IPs are restored after restart: exits OK (code 0)
- If IPs are still missing after restart: exits CRITICAL (code 2)
- If /etc/ips is empty: exits OK with a message indicating no additional IPs found
- If any error occurs: exits UNKNOWN (code 3)
"""
import subprocess
import sys
import time
IP_FILE = "/etc/ips"
def read_ips(file_path=IP_FILE):
try:
with open(file_path, 'r') as f:
return [line.strip().split(':')[0] for line in f if line.strip() and not line.startswith('#')]
except Exception as e:
print(f"UNKNOWN - Failed to read {file_path}: {e}")
sys.exit(3)
def check_ip_up(ip):
try:
output = subprocess.check_output(['ip', 'addr'], encoding='utf-8')
return ip in output
except subprocess.CalledProcessError as e:
print(f"UNKNOWN - Failed to execute 'ip addr': {e}")
sys.exit(3)
def restart_ipaliases():
try:
subprocess.check_call(['/scripts/restartsrv_ipaliases'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
time.sleep(5) # Allow time for interface setup
except subprocess.CalledProcessError:
# Fail silently, outcome is rechecked by the caller
pass
def main():
expected_ips = read_ips()
if not expected_ips:
print("OK - No additional IPs found.")
sys.exit(0)
down_ips = [ip for ip in expected_ips if not check_ip_up(ip)]
if not down_ips:
print(f"OK - All {len(expected_ips)} additional IPs are up.")
sys.exit(0)
# Attempt to fix by restarting
restart_ipaliases()
still_down = [ip for ip in down_ips if not check_ip_up(ip)]
if still_down:
print(f"CRITICAL - IPs still down after restart: {', '.join(still_down)}")
sys.exit(2)
else:
print(f"OK - IPs were down, recovered after restart.")
sys.exit(0)
if __name__ == "__main__":
main()