inwx-api-tool/inwx_dns_functions.py

140 lines
4.8 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from inwx_config import api_call # Import the base API calling function
def get_dns_info(domain):
"""Fetches and displays all DNS records for a given domain in a formatted table."""
print(f"\n--- Fetching DNS records for {domain}...")
result = api_call("nameserver.info", {"domain": domain})
if result and result.get('code') == 1000 and 'record' in result.get('resData', {}):
print(f"[SUCCESS] DNS Records for **{domain}**:")
records = result['resData']['record']
# Output the table header
print("-" * 100)
print(f"| {'ID':<10} | {'Name/Host':<15} | {'Type':<5} | {'TTL':<5} | {'Content':<50} |")
print("-" * 100)
for record in records:
# Truncate Name and Content for clean table output
name_short = record.get('name', '')[:14].ljust(15)
content_short = record.get('content', '')[:49].ljust(50)
# Note: record['id'] is handled as string input/output now (API change)
print(f"| {str(record['id']):<10} | {name_short} | {record['type']:<5} | {str(record['ttl']):<5} | {content_short} |")
print("-" * 100)
return True
elif result and 'msg' in result:
print(f"[ERROR] Failed to fetch records: {result.get('msg', 'Unknown error.')}")
else:
print("[ERROR] Failed to fetch records (Unexpected API response).")
return False
def add_record():
"""Adds a new DNS record using the nameserver.createRecord API method."""
print("\n--- ADD NEW DNS RECORD ---")
domain = input("Domain (e.g., example.com): ").strip()
name = input("Host/Subdomain (leave blank for main domain '@'): ").strip()
record_type = input("Type (A, CNAME, TXT, MX, etc.): ").strip().upper()
content = input("Content (IP address, target, text): ").strip()
# Optional: TTL with default value 3600
try:
ttl = int(input("TTL (seconds, default: 3600): ") or 3600)
except ValueError:
print("[WARNING] Invalid TTL. Using default value 3600.")
ttl = 3600
params = {
"domain": domain,
"name": name,
"type": record_type,
"content": content,
"ttl": ttl
}
print(f"\n--- Sending request to add record {name}.{domain}...")
result = api_call("nameserver.createRecord", params)
if result and result.get('code') == 1000:
new_id = result.get('resData', {}).get('id', 'N/A')
print(f"[SUCCESS] Record successfully added! ID: **{new_id}**")
else:
print(f"[ERROR] Failed to add record: {result.get('msg', 'Unknown error.')}")
def update_record():
"""Modifies an existing DNS record using the nameserver.updateRecord API method."""
print("\n--- MODIFY EXISTING DNS RECORD ---")
record_id = input("ID of the record to modify (see Option 1): ").strip()
if not record_id.isdigit():
print("[ERROR] Invalid ID.")
return
# Prompt for values to change
new_content = input("New Content (leave blank to skip): ").strip()
new_ttl = input("New TTL (seconds, leave blank to skip): ").strip()
# Pass ID as string (INWX API change compliance)
params = {"id": record_id}
if new_content:
params["content"] = new_content
if new_ttl:
try:
params["ttl"] = int(new_ttl)
except ValueError:
print("[ERROR] Invalid TTL. Modification aborted.")
return
if len(params) <= 1:
print("No changes specified. Operation aborted.")
return
print(f"\n--- Sending request to modify ID **{record_id}**...")
result = api_call("nameserver.updateRecord", params)
if result and result.get('code') == 1000:
print(f"[SUCCESS] Record ID **{record_id}** successfully updated.")
else:
print(f"[ERROR] Failed to modify record: {result.get('msg', 'Unknown error.')}")
def delete_record():
"""Deletes a DNS record using the nameserver.deleteRecord API method."""
print("\n--- DELETE DNS RECORD ---")
record_id = input("ID of the record to delete (see Option 1): ").strip()
if not record_id.isdigit():
print("[ERROR] Invalid ID.")
return
confirm = input(f"Are you sure you want to delete record ID **{record_id}**? (Y/N): ").strip().upper()
if confirm != 'Y':
print("Deletion aborted.")
return
# Pass ID as string (INWX API change compliance)
params = {"id": record_id}
print(f"\n--- Sending request to delete ID **{record_id}**...")
result = api_call("nameserver.deleteRecord", params)
if result and result.get('code') == 1000:
print(f"[SUCCESS] Record ID **{record_id}** successfully deleted.")
else:
print(f"[ERROR] Failed to delete record: {result.get('msg', 'Unknown error.')}")