Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- """
- nat_manager.py - NAT Port Forwarding Manager for Proxmox
- This script was developed with assistance from OpenAI's ChatGPT.
- For more information, visit https://www.openai.com/chatgpt
- """
- import sys
- import sqlite3
- import subprocess
- import os
- import re
- import shutil
- import argparse
- import json
- from datetime import datetime
- # Constants
- PORT_START = 50000
- DB_FILE = '/etc/port_mappings.db'
- NETWORK_INTERFACE = 'vmbr0' # Adjust if using a different interface
- BACKUP_DIR = '/etc/nat_manager_backups'
- # Ensure script is run as root
- if os.geteuid() != 0:
- print("Please run as root.")
- sys.exit(1)
- # Check if iptables-persistent is installed and enabled
- def check_iptables_persistent():
- # Check if the package is installed
- iptables_persistent_installed = False
- try:
- result = subprocess.run(['dpkg-query', '-W', '-f=${Status}', 'iptables-persistent'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- if 'install ok installed' in result.stdout:
- iptables_persistent_installed = True
- except Exception:
- pass
- # Check if the netfilter-persistent service is enabled
- netfilter_service_enabled = False
- try:
- result = subprocess.run(['systemctl', 'is-enabled', 'netfilter-persistent'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- if 'enabled' in result.stdout.strip():
- netfilter_service_enabled = True
- except Exception:
- pass
- # Display warning if not installed or not enabled
- if not iptables_persistent_installed:
- print("WARNING: 'iptables-persistent' is not installed.")
- print("The iptables rules will not be loaded on the next reboot unless 'iptables-persistent' is installed and enabled.")
- elif not netfilter_service_enabled:
- print("WARNING: 'netfilter-persistent' service is not enabled.")
- print("The iptables rules will not be loaded on the next reboot unless 'netfilter-persistent' is enabled.")
- # Run the check
- check_iptables_persistent()
- # Command-line argument parsing
- parser = argparse.ArgumentParser(description='NAT Manager Script')
- subparsers = parser.add_subparsers(dest='action', help='Available actions')
- # Add action
- add_parser = subparsers.add_parser('add', help='Add port mappings for a container')
- add_parser.add_argument('container_ip', help='IP address of the container')
- add_parser.add_argument('--mode', choices=['automatic', 'manual'], default='automatic', help='Mode of operation')
- add_parser.add_argument('--num-ports', type=int, default=6, help='Number of ports to forward (default 6)')
- add_parser.add_argument('--internal-ports', nargs='*', type=int, help='List of internal ports for manual mode')
- add_parser.add_argument('--temporary', action='store_true', help='Create temporary NAT rules that are not saved')
- add_parser.add_argument('--external-ports', nargs='*', type=int, help='Specify external ports (advanced)')
- add_parser.add_argument('--protocols', nargs='*', choices=['tcp', 'udp'], help='Protocols for the ports (tcp or udp)')
- # Remove action
- remove_parser = subparsers.add_parser('remove', help='Remove port mappings for a container')
- remove_parser.add_argument('container_ip', help='IP address of the container')
- # List action
- list_parser = subparsers.add_parser('list', help='List port mappings')
- list_parser.add_argument('container_ip', nargs='?', help='IP address of the container to list')
- # Update action
- update_parser = subparsers.add_parser('update', help='Update port mappings for a container')
- update_parser.add_argument('container_ip', help='IP address of the container')
- update_parser.add_argument('--internal-ports', nargs='*', type=int, help='New internal ports')
- update_parser.add_argument('--external-ports', nargs='*', type=int, help='External ports to update')
- update_parser.add_argument('--protocols', nargs='*', choices=['tcp', 'udp'], help='Protocols for the ports (tcp or udp)')
- # Reserve action
- reserve_parser = subparsers.add_parser('reserve', help='Reserve ports for the host machine')
- reserve_parser.add_argument('ports', nargs='+', type=int, help='Ports to reserve')
- # Unreserve action
- unreserve_parser = subparsers.add_parser('unreserve', help='Unreserve ports')
- unreserve_parser.add_argument('ports', nargs='+', type=int, help='Ports to unreserve')
- # List-reserved action
- list_reserved_parser = subparsers.add_parser('list-reserved', help='List reserved ports')
- # Export action
- export_parser = subparsers.add_parser('export', help='Export port mappings to a JSON file')
- export_parser.add_argument('file', help='File to export port mappings to')
- # Import action
- import_parser = subparsers.add_parser('import', help='Import port mappings from a JSON file')
- import_parser.add_argument('file', help='File to import port mappings from')
- # Backup action
- backup_parser = subparsers.add_parser('backup', help='Backup current configuration')
- # Restore action
- restore_parser = subparsers.add_parser('restore', help='Restore configuration from backup')
- restore_parser.add_argument('timestamp', help='Timestamp of the backup to restore')
- # Rebuild Database action
- rebuild_db_parser = subparsers.add_parser('rebuild-db', help='Rebuild the database from existing iptables rules')
- args = parser.parse_args()
- ACTION = args.action
- CONTAINER_IP = getattr(args, 'container_ip', None)
- # Database setup
- def init_db():
- conn = sqlite3.connect(DB_FILE)
- cursor = conn.cursor()
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS port_mappings (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- container_ip TEXT NOT NULL,
- external_port INTEGER NOT NULL,
- internal_port INTEGER NOT NULL,
- protocol TEXT NOT NULL DEFAULT 'tcp',
- temporary INTEGER NOT NULL DEFAULT 0
- )
- ''')
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS reserved_ports (
- port INTEGER PRIMARY KEY
- )
- ''')
- conn.commit()
- return conn
- def validate_ip(ip):
- pattern = re.compile(
- r'^(\d{1,3}\.){3}\d{1,3}$'
- )
- return pattern.match(ip)
- conn = init_db()
- cursor = conn.cursor()
- # Function to check if port is in use
- def is_port_in_use(port):
- result = subprocess.run(
- ['ss', '-tulpn'],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- text=True
- )
- return f":{port} " in result.stdout or f":{port}\n" in result.stdout
- # Function to assign ports automatically
- def assign_ports(num_ports):
- cursor.execute('SELECT external_port FROM port_mappings')
- assigned_ports = [row[0] for row in cursor.fetchall()]
- cursor.execute('SELECT port FROM reserved_ports')
- reserved_ports = [row[0] for row in cursor.fetchall()]
- next_port = PORT_START
- while True:
- conflict = False
- for i in range(num_ports):
- port = next_port + i
- if port in assigned_ports or is_port_in_use(port) or port in reserved_ports:
- conflict = True
- break
- if not conflict:
- break
- else:
- next_port += num_ports
- assigned_ports_to_container = [next_port + i for i in range(num_ports)]
- return assigned_ports_to_container
- # Function to check if an iptables rule exists
- def iptables_rule_exists(protocol, external_port, container_ip, internal_port):
- cmd = [
- 'iptables', '-t', 'nat', '-C', 'PREROUTING', '-i', NETWORK_INTERFACE,
- '-p', protocol, '--dport', str(external_port),
- '-j', 'DNAT', '--to-destination', f'{container_ip}:{internal_port}'
- ]
- result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- return result.returncode == 0
- # Function to set up iptables rules
- def setup_iptables_rules(container_ip, external_ports, internal_ports, protocols, save_rules=True):
- for external_port, internal_port, protocol in zip(external_ports, internal_ports, protocols):
- if not iptables_rule_exists(protocol, external_port, container_ip, internal_port):
- subprocess.run([
- 'iptables', '-t', 'nat', '-A', 'PREROUTING', '-i', NETWORK_INTERFACE,
- '-p', protocol, '--dport', str(external_port),
- '-j', 'DNAT', '--to-destination', f'{container_ip}:{internal_port}'
- ])
- else:
- print(f"Iptables rule for external port {external_port}/{protocol} already exists. Skipping.")
- # Enable IP forwarding
- subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'])
- if save_rules:
- # Save iptables rules
- subprocess.run(['iptables-save'], stdout=open('/etc/iptables/rules.v4', 'w'))
- # Function to remove iptables rules
- def remove_iptables_rules(container_ip, external_ports, internal_ports, protocols, save_rules=True):
- for external_port, internal_port, protocol in zip(external_ports, internal_ports, protocols):
- subprocess.run([
- 'iptables', '-t', 'nat', '-D', 'PREROUTING', '-i', NETWORK_INTERFACE,
- '-p', protocol, '--dport', str(external_port),
- '-j', 'DNAT', '--to-destination', f'{container_ip}:{internal_port}'
- ])
- if save_rules:
- # Save iptables rules
- subprocess.run(['iptables-save'], stdout=open('/etc/iptables/rules.v4', 'w'))
- # Function to add port mappings
- def add_container(container_ip, mode, num_ports, internal_ports_input, external_ports_input, protocols_input, temporary=False):
- if not validate_ip(container_ip):
- print("Invalid IP address.")
- sys.exit(1)
- # Check if the specific container_ip already exists in the database
- cursor.execute('SELECT COUNT(*) FROM port_mappings WHERE container_ip = ?', (container_ip,))
- if cursor.fetchone()[0] > 0:
- print(f"IP {container_ip} is already assigned ports in the database.")
- sys.exit(1)
- else:
- # Check iptables directly for any existing rules for the IP
- existing_rules = get_iptables_rules_for_ip(container_ip)
- if existing_rules:
- print(f"IP {container_ip} has existing iptables rules.")
- print("Please remove them before adding new mappings or rebuild the database using 'rebuild-db'.")
- sys.exit(1)
- if external_ports_input:
- assigned_ports = external_ports_input
- num_ports = len(assigned_ports)
- else:
- assigned_ports = assign_ports(num_ports)
- internal_ports = []
- protocols = []
- if mode == 'automatic':
- # Predefined internal ports for the first 4 ports
- INTERNAL_PORTS_DEFAULT = [22, 80, 443, 8080]
- PROTOCOLS_DEFAULT = ['tcp', 'tcp', 'tcp', 'tcp']
- for i in range(num_ports):
- if i < len(INTERNAL_PORTS_DEFAULT):
- internal_ports.append(INTERNAL_PORTS_DEFAULT[i])
- protocols.append(PROTOCOLS_DEFAULT[i])
- else:
- internal_ports.append(assigned_ports[i]) # External port equals internal port
- protocols.append('tcp')
- elif mode == 'manual':
- if internal_ports_input:
- if len(internal_ports_input) != num_ports:
- print("Number of internal ports provided does not match num-ports.")
- sys.exit(1)
- internal_ports = internal_ports_input
- else:
- print("Internal ports are required in manual mode.")
- sys.exit(1)
- if protocols_input:
- if len(protocols_input) != num_ports:
- print("Number of protocols provided does not match num-ports.")
- sys.exit(1)
- protocols = protocols_input
- else:
- protocols = ['tcp'] * num_ports # Default to tcp if not specified
- else:
- print("Invalid mode.")
- sys.exit(1)
- # Set up iptables rules
- save_rules = not temporary
- setup_iptables_rules(container_ip, assigned_ports, internal_ports, protocols, save_rules=save_rules)
- if not temporary:
- # Insert mappings into database
- for external_port, internal_port, protocol in zip(assigned_ports, internal_ports, protocols):
- cursor.execute('''
- INSERT INTO port_mappings (container_ip, external_port, internal_port, protocol)
- VALUES (?, ?, ?, ?)
- ''', (container_ip, external_port, internal_port, protocol))
- conn.commit()
- print(f"Assigned ports to {container_ip}:")
- for external_port, internal_port, protocol in zip(assigned_ports, internal_ports, protocols):
- print(f"External port {external_port}/{protocol} -> {container_ip}:{internal_port}")
- def remove_container(container_ip):
- # Step 1: Remove rules from iptables
- cursor.execute('SELECT external_port, internal_port, protocol FROM port_mappings WHERE container_ip = ?', (container_ip,))
- port_mappings = cursor.fetchall()
- if not port_mappings:
- print(f"No port mappings found for IP {container_ip}.")
- sys.exit(1)
- for external_port, internal_port, protocol in port_mappings:
- # Remove the corresponding iptables rule
- remove_iptables_rule(container_ip, external_port, internal_port, protocol)
- # Step 2: Remove the entries from the database
- cursor.execute('DELETE FROM port_mappings WHERE container_ip = ?', (container_ip,))
- conn.commit()
- # Step 3: Save iptables rules to make changes persistent
- save_iptables_rules()
- print(f"Port mappings for IP {container_ip} have been successfully removed.")
- def remove_iptables_rule(container_ip, external_port, internal_port, protocol):
- """
- Removes a specific iptables rule.
- """
- command = f"iptables -t nat -D PREROUTING -i {NETWORK_INTERFACE} -p {protocol} --dport {external_port} -j DNAT --to-destination {container_ip}:{internal_port}"
- result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- if result.returncode == 0:
- print(f"Removed iptables rule: {command}")
- else:
- print(f"Failed to remove iptables rule: {command}. Error: {result.stderr.decode()}")
- def save_iptables_rules():
- """
- Saves the current iptables rules to the rules file.
- """
- try:
- result = subprocess.run(['iptables-save'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- if result.returncode == 0:
- with open('/etc/iptables/rules.v4', 'wb') as f:
- f.write(result.stdout)
- print("iptables rules have been saved successfully.")
- else:
- print(f"Failed to save iptables rules. Error: {result.stderr.decode()}")
- except Exception as e:
- print(f"Error saving iptables rules: {e}")
- # Function to get iptables rules for a specific container IP
- def get_iptables_rules_for_ip(container_ip):
- result = subprocess.run(['iptables-save'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- rules = []
- for line in result.stdout.splitlines():
- if '-A PREROUTING' in line and f'--to-destination {container_ip}' in line:
- protocol_match = re.search(r'-p (\w+)', line)
- dport_match = re.search(r'--dport (\d+)', line)
- to_dest_match = re.search(r'--to-destination ([^:]+):(\d+)', line)
- if protocol_match and dport_match and to_dest_match:
- protocol = protocol_match.group(1)
- external_port = int(dport_match.group(1))
- internal_port = int(to_dest_match.group(2))
- rules.append({
- 'protocol': protocol,
- 'external_port': external_port,
- 'internal_port': internal_port,
- 'container_ip': container_ip
- })
- return rules
- # Function to rebuild the database from existing iptables rules
- def rebuild_database():
- print("Rebuilding database from existing iptables rules...")
- existing_rules = get_all_iptables_rules()
- for rule in existing_rules:
- container_ip = rule['container_ip']
- external_port = rule['external_port']
- internal_port = rule['internal_port']
- protocol = rule['protocol']
- # Check if the mapping already exists in the database
- cursor.execute('''
- SELECT COUNT(*) FROM port_mappings WHERE container_ip = ? AND external_port = ? AND protocol = ?
- ''', (container_ip, external_port, protocol))
- if cursor.fetchone()[0] == 0:
- # Insert into database
- cursor.execute('''
- INSERT INTO port_mappings (container_ip, external_port, internal_port, protocol)
- VALUES (?, ?, ?, ?)
- ''', (container_ip, external_port, internal_port, protocol))
- conn.commit()
- print(f"Added mapping: External port {external_port}/{protocol} -> {container_ip}:{internal_port}")
- print("Database rebuild complete.")
- # Function to get all relevant iptables rules
- def get_all_iptables_rules():
- result = subprocess.run(['iptables-save'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
- rules = []
- for line in result.stdout.splitlines():
- if '-A PREROUTING' in line and '-j DNAT' in line and f'-i {NETWORK_INTERFACE}' in line:
- protocol_match = re.search(r'-p (\w+)', line)
- dport_match = re.search(r'--dport (\d+)', line)
- to_dest_match = re.search(r'--to-destination ([^:]+):(\d+)', line)
- if protocol_match and dport_match and to_dest_match:
- protocol = protocol_match.group(1)
- external_port = int(dport_match.group(1))
- container_ip = to_dest_match.group(1)
- internal_port = int(to_dest_match.group(2))
- rules.append({
- 'protocol': protocol,
- 'external_port': external_port,
- 'internal_port': internal_port,
- 'container_ip': container_ip
- })
- return rules
- # Function to list port mappings
- def list_mappings(container_ip=None):
- cursor.execute('SELECT container_ip, external_port, internal_port, protocol, temporary FROM port_mappings ORDER BY container_ip')
- rows = cursor.fetchall()
- if not rows:
- print("No port mappings found.")
- return
- if container_ip:
- print(f"Port mappings for {container_ip}:")
- for row in rows:
- ip, external_port, internal_port, protocol, temporary = row
- if ip == container_ip:
- temp_str = " (Temporary)" if temporary else ""
- print(f"External port {external_port}/{protocol} -> {ip}:{internal_port}{temp_str}")
- else:
- print("All port mappings:")
- current_ip = None
- for row in rows:
- ip, external_port, internal_port, protocol, temporary = row
- temp_str = " (Temporary)" if temporary else ""
- if ip != current_ip:
- current_ip = ip
- print(f"\nContainer IP: {ip}")
- print(f" External port {external_port}/{protocol} -> {ip}:{internal_port}{temp_str}")
- # Function to update port mappings
- def update_container(container_ip, internal_ports_input=None, external_ports_input=None, protocols_input=None):
- cursor.execute('SELECT external_port, internal_port, protocol FROM port_mappings WHERE container_ip = ?', (container_ip,))
- rows = cursor.fetchall()
- if not rows:
- print(f"No existing port mappings found for {container_ip}.")
- sys.exit(1)
- if external_ports_input:
- # Update only specified external ports
- external_ports = external_ports_input
- old_mappings = {row[0]: (row[1], row[2]) for row in rows if row[0] in external_ports}
- if not old_mappings:
- print(f"No existing port mappings found for the specified external ports.")
- sys.exit(1)
- else:
- external_ports = [row[0] for row in rows]
- old_mappings = {row[0]: (row[1], row[2]) for row in rows}
- # Prepare lists for new internal ports and protocols
- new_internal_ports = []
- new_protocols = []
- if internal_ports_input is not None and protocols_input is not None:
- # Non-interactive mode: both internal ports and protocols are provided
- if len(internal_ports_input) != len(external_ports):
- print("Number of internal ports provided does not match number of external ports.")
- sys.exit(1)
- if len(protocols_input) != len(external_ports):
- print("Number of protocols provided does not match number of external ports.")
- sys.exit(1)
- new_internal_ports = internal_ports_input
- new_protocols = protocols_input
- else:
- # Interactive mode
- print("Updating port mappings. Leave input empty to keep the same mapping.")
- for ext_port in external_ports:
- old_internal_port, old_protocol = old_mappings[ext_port]
- internal_port = input(f"External port {ext_port} -> Internal port (current: {old_internal_port}): ").strip()
- if internal_port == '':
- internal_port = old_internal_port
- else:
- if not internal_port.isdigit():
- print("Invalid port number.")
- sys.exit(1)
- internal_port = int(internal_port)
- protocol = input(f"External port {ext_port} -> Protocol (current: {old_protocol}): ").strip()
- if protocol == '':
- protocol = old_protocol
- elif protocol not in ['tcp', 'udp']:
- print("Invalid protocol. Please enter 'tcp' or 'udp'.")
- sys.exit(1)
- new_internal_ports.append(internal_port)
- new_protocols.append(protocol)
- # Remove existing iptables rules for specified ports
- old_internal_ports = [old_mappings[ext_port][0] for ext_port in external_ports]
- old_protocols = [old_mappings[ext_port][1] for ext_port in external_ports]
- remove_iptables_rules(container_ip, external_ports, old_internal_ports, old_protocols)
- # Update database entries and set up new iptables rules
- for external_port, internal_port, protocol in zip(external_ports, new_internal_ports, new_protocols):
- cursor.execute('''
- UPDATE port_mappings
- SET internal_port = ?, protocol = ?
- WHERE container_ip = ? AND external_port = ?
- ''', (internal_port, protocol, container_ip, external_port))
- conn.commit()
- setup_iptables_rules(container_ip, external_ports, new_internal_ports, new_protocols)
- print(f"Updated port mappings for {container_ip}:")
- for external_port, internal_port, protocol in zip(external_ports, new_internal_ports, new_protocols):
- print(f"External port {external_port}/{protocol} -> {container_ip}:{internal_port}")
- def reserve_ports(ports):
- for port in ports:
- cursor.execute('INSERT OR IGNORE INTO reserved_ports (port) VALUES (?)', (port,))
- conn.commit()
- print(f"Reserved ports: {', '.join(map(str, ports))}")
- def unreserve_ports(ports):
- for port in ports:
- cursor.execute('DELETE FROM reserved_ports WHERE port = ?', (port,))
- conn.commit()
- print(f"Unreserved ports: {', '.join(map(str, ports))}")
- def list_reserved_ports():
- cursor.execute('SELECT port FROM reserved_ports ORDER BY port')
- rows = cursor.fetchall()
- if not rows:
- print("No reserved ports.")
- return
- ports = [str(row[0]) for row in rows]
- print("Reserved ports:")
- print(', '.join(ports))
- def export_mappings(file_path):
- cursor.execute('SELECT container_ip, external_port, internal_port, protocol FROM port_mappings')
- rows = cursor.fetchall()
- data = []
- for row in rows:
- data.append({
- 'container_ip': row[0],
- 'external_port': row[1],
- 'internal_port': row[2],
- 'protocol': row[3]
- })
- with open(file_path, 'w') as f:
- json.dump(data, f, indent=4)
- print(f"Port mappings exported to {file_path}")
- def import_mappings(file_path):
- if not os.path.exists(file_path):
- print(f"File {file_path} does not exist.")
- sys.exit(1)
- with open(file_path, 'r') as f:
- data = json.load(f)
- for entry in data:
- container_ip = entry['container_ip']
- external_port = entry['external_port']
- internal_port = entry['internal_port']
- protocol = entry.get('protocol', 'tcp')
- # Check if the mapping already exists
- cursor.execute('SELECT COUNT(*) FROM port_mappings WHERE container_ip = ? AND external_port = ?', (container_ip, external_port))
- if cursor.fetchone()[0] == 0:
- # Set up iptables rule
- setup_iptables_rules(container_ip, [external_port], [internal_port], [protocol])
- # Insert into database
- cursor.execute('''
- INSERT INTO port_mappings (container_ip, external_port, internal_port, protocol)
- VALUES (?, ?, ?, ?)
- ''', (container_ip, external_port, internal_port, protocol))
- conn.commit()
- print(f"Port mappings imported from {file_path}")
- def backup_configuration():
- timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
- backup_path = os.path.join(BACKUP_DIR, f'backup_{timestamp}')
- os.makedirs(backup_path, exist_ok=True)
- # Backup database
- shutil.copy(DB_FILE, os.path.join(backup_path, 'port_mappings.db'))
- # Backup iptables rules
- subprocess.run(['iptables-save'], stdout=open(os.path.join(backup_path, 'rules.v4'), 'w'))
- print(f"Backup created at {backup_path}")
- def restore_configuration(timestamp):
- backup_path = os.path.join(BACKUP_DIR, f'backup_{timestamp}')
- if not os.path.exists(backup_path):
- print(f"Backup with timestamp {timestamp} does not exist.")
- sys.exit(1)
- # Restore database
- shutil.copy(os.path.join(backup_path, 'port_mappings.db'), DB_FILE)
- # Restore iptables rules
- subprocess.run(['iptables-restore'], stdin=open(os.path.join(backup_path, 'rules.v4'), 'r'))
- print(f"Configuration restored from backup {backup_path}")
- # Main execution
- if ACTION == 'add':
- container_ip = args.container_ip
- mode = args.mode
- num_ports = args.num_ports
- internal_ports_input = args.internal_ports
- external_ports_input = args.external_ports
- protocols_input = args.protocols
- temporary = args.temporary
- add_container(container_ip, mode, num_ports, internal_ports_input, external_ports_input, protocols_input, temporary=temporary)
- elif ACTION == 'remove':
- container_ip = args.container_ip
- remove_container(container_ip)
- elif ACTION == 'list':
- container_ip = args.container_ip
- list_mappings(container_ip)
- elif ACTION == 'update':
- container_ip = args.container_ip
- internal_ports_input = args.internal_ports
- external_ports_input = args.external_ports
- protocols_input = args.protocols
- update_container(container_ip, internal_ports_input, external_ports_input, protocols_input)
- elif ACTION == 'reserve':
- ports = args.ports
- reserve_ports(ports)
- elif ACTION == 'unreserve':
- ports = args.ports
- unreserve_ports(ports)
- elif ACTION == 'list-reserved':
- list_reserved_ports()
- elif ACTION == 'export':
- file_path = args.file
- export_mappings(file_path)
- elif ACTION == 'import':
- file_path = args.file
- import_mappings(file_path)
- elif ACTION == 'backup':
- backup_configuration()
- elif ACTION == 'restore':
- timestamp = args.timestamp
- restore_configuration(timestamp)
- elif ACTION == 'rebuild-db':
- rebuild_database()
- else:
- print("Invalid action.")
- sys.exit(1)
- conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement