Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Shells Virtual Desktop
BMail.ag - Secure Email Service
Server.net
CPLicense.net
VPS Server
Buy VPN
Vultr
VMs for AI
HostDare
ReliableSite White-Label Dedicated Hosting for Resellers
InterServer VPS
BMail.ag - Secure Email Service
Best VPN
High-Performance Bare Metal Server Solutions
Karvl.com
Server Mania Cloud Hosting
DataWagon Hosting
AlphaVPS Hosting
Evoxt.com
Clouvider
VPS Hosting with NVMe
Residential IPs in the US & 4G Mobile Proxies in EU & US with Unlimited Bandwidth
ReliableSite White-Label Dedicated Hosting for Resellers
Rabisu - Hosting Solutions
Shells Virtual Desktop
New on LowEndTalk? Please Register and read our Community Rules.

All new Registrations are manually reviewed and approved, so a short delay after registration may occur before your account becomes active.

nat_manager.py - manage NAT port forwarding for Proxmox VMs and containers

The following code and its documentation were generated using ChatGPT model (o1-preview). I had considered writing this code myself some time ago but hadn’t found the time to do so. Here is the code along with an overview written by ChatGPT. I would appreciate any feedback on how it can be further improved or if there are any mistakes.

Code available at:
https://pastebin.com/cdrxhUSU

nat_manager.py Quick Start Guide

nat_manager.py is a Python script designed to manage NAT (Network Address Translation) and port forwarding rules for VMs and containers in a Proxmox environment. The script utilizes iptables to configure NAT rules and allows for easy addition, removal, listing, updating, exporting, and importing of port mappings.

This guide provides step-by-step instructions for setting up the network, using the script, and provides examples for common operations.


Network Setup in Proxmox

To use nat_manager.py effectively, you need to set up a bridge network (vmbr1) on your Proxmox server. This bridge will use a private IP range and manage the NAT and port forwarding for your VMs and containers.

1. Configure the Bridge Network (vmbr1)

Edit the /etc/network/interfaces file to configure the bridge network interface vmbr1:

sudo nano /etc/network/interfaces

Add the following configuration:

auto vmbr1
iface vmbr1 inet static
    address 10.0.0.1/24
    bridge-ports none
    bridge-stp off
    bridge-fd 0

    post-up iptables -t nat -A POSTROUTING -s 10.0.0.0/24 -o <YOUR_PUBLIC_INTERFACE> -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s 10.0.0.0/24 -o <YOUR_PUBLIC_INTERFACE> -j MASQUERADE
  • <YOUR_PUBLIC_INTERFACE>: Replace this with your network interface that has a public IP (e.g., enp0s3).

2. Enable IP Forwarding

To ensure IP forwarding is enabled permanently, add the following line to /etc/sysctl.conf:

net.ipv4.ip_forward = 1

Apply the changes:

sudo sysctl -p

3. Restart Networking Service

Restart the networking service to apply the changes:

sudo systemctl restart networking

4. Install Required Packages

To ensure iptables rules persist across reboots, install iptables-persistent and other required packages:

sudo apt-get update
sudo apt-get install iptables-persistent python3 python3-pip sqlite3 -y
  • iptables-persistent: Allows iptables rules to be saved and restored on boot.
  • python3 and sqlite3: Required for running the nat_manager.py script.

Using nat_manager.py

Run nat_manager.py using Python3. Below are the various usage instructions for managing NAT and port forwarding rules for your VMs and containers.

python3 nat_manager.py -h
usage: nat_manager.py [-h]
                      {add,remove,list,update,reserve,unreserve,list-reserved,export,import,backup,restore,rebuild-db}
                      ...

NAT Manager Script

positional arguments:
  {add,remove,list,update,reserve,unreserve,list-reserved,export,import,backup,restore,rebuild-db}
                        Available actions
    add                 Add port mappings for a container
    remove              Remove port mappings for a container
    list                List port mappings
    update              Update port mappings for a container
    reserve             Reserve ports for the host machine
    unreserve           Unreserve ports
    list-reserved       List reserved ports
    export              Export port mappings to a JSON file
    import              Import port mappings from a JSON file
    backup              Backup current configuration
    restore             Restore configuration from backup
    rebuild-db          Rebuild the database from existing iptables rules

options:
  -h, --help            show this help message and exit

1. Add Port Mappings

To add NAT port forwarding rules for a VM or container with an internal IP address (e.g., 10.0.0.5):

sudo python3 nat_manager.py add <container_ip> --mode <automatic|manual> --num-ports <N>
  • Parameters:
    • <container_ip>: Internal IP address of the VM/container (e.g., 10.0.0.5).
    • --mode: Mode for adding ports, automatic (default) or manual.
    • --num-ports <N>: Number of ports to forward (default: 6).

Examples:

  • Automatic Mode:

    sudo python3 nat_manager.py add 10.0.0.5 --mode automatic --num-ports 4
    

    This command automatically assigns 4 external ports (starting from 50000) to forward traffic to standard internal ports (e.g., 22, 80, 443, 8080) on 10.0.0.5.

  • Manual Mode:

    sudo python3 nat_manager.py add 10.0.0.5 --mode manual --external-ports 50000 50001 --internal-ports 22 80 --protocols tcp udp
    

    This command manually assigns external ports 50000 (TCP) and 50001 (UDP) to forward to internal ports 22 (SSH) and 80 (HTTP) on 10.0.0.5.

2. Remove Port Mappings

To remove all port forwarding rules associated with a specific container IP:

sudo python3 nat_manager.py remove <container_ip>
  • Example:

    sudo python3 nat_manager.py remove 10.0.0.5
    

    This command removes all port mappings associated with the IP 10.0.0.5.

3. List Current Port Mappings

To list all current port mappings or those for a specific container IP:

sudo python3 nat_manager.py list [container_ip]
  • Examples:

    • List All Mappings:
    sudo python3 nat_manager.py list
    

    Lists all port mappings currently configured on the Proxmox server.

    • List Mappings for a Specific Container:
    sudo python3 nat_manager.py list 10.0.0.5
    

    Lists the port mappings for the container with IP 10.0.0.5.

4. Update Port Mappings

To update existing port mappings for a VM or container:

sudo python3 nat_manager.py update <container_ip>
  • Examples:

    • Interactive Mode:
    sudo python3 nat_manager.py update 10.0.0.5
    

    This command will prompt you to update the internal ports or protocols for each external port currently mapped to 10.0.0.5. Leave input blank to keep the current mapping.

    • Non-Interactive Mode:
    sudo python3 nat_manager.py update 10.0.0.5 --external-ports 50000 50001 --internal-ports 2222 8081 --protocols tcp udp
    

    This command updates the external port 50000 to forward to internal port 2222 (TCP) and 50001 to forward to 8081 (UDP) on 10.0.0.5.

5. Export and Import Port Mappings

You can export current port mappings to a JSON file for backup purposes or import them from a JSON file.

  • Export Port Mappings:

    sudo python3 nat_manager.py export /path/to/export.json
    

    This command exports the current port mappings to export.json.

  • Import Port Mappings:

    sudo python3 nat_manager.py import /path/to/export.json
    

    This command imports port mappings from export.json.

6. Backup and Restore Configuration

You can backup the current configuration of iptables and port mappings or restore from a backup.

  • Backup Current Configuration:

    sudo python3 nat_manager.py backup
    

    This creates a backup of the current iptables rules and port mappings database.

  • Restore Configuration from Backup:

    sudo python3 nat_manager.py restore <timestamp>
    

    Replace <timestamp> with the desired backup timestamp (e.g., backup_20230917123045).

7. Rebuild the Database from Existing iptables Rules

If the SQLite database is lost or out of sync with iptables rules, you can rebuild it:

sudo python3 nat_manager.py rebuild-db

This command scans existing iptables rules and reconstructs the database for consistency.

Important Notes

  • IP Forwarding: Ensure IP forwarding is enabled by adding net.ipv4.ip_forward = 1 to /etc/sysctl.conf and running sudo sysctl -p.
  • Save iptables Rules: To ensure the rules persist after reboot, use iptables-save > /etc/iptables/rules.v4 and iptables-restore < /etc/iptables/rules.v4.
  • Check iptables-persistent: Ensure iptables-persistent is installed and enabled to manage rule persistence:

    sudo apt-get install iptables-persistent -y
    sudo netfilter-persistent save
    

Network Configuration for VM/Container in Proxmox

When creating a VM or container in Proxmox that will use NAT:

  1. Assign an Internal IP Address:

    • Assign an IP within the vmbr1 subnet, such as 10.0.0.5.
    • This IP will be used for internal communication and NAT port forwarding.
  2. Connect to vmbr1 Network Bridge:

    • Ensure the VM/container network interface is attached to vmbr1 to use the internal network managed by NAT.
    • In Proxmox, select vmbr1 as the network bridge when creating or configuring the VM/container.
  3. Configure Gateway (Optional):

    • Set the gateway to 10.0.0.1 (the vmbr1 address) to route all outbound traffic through the Proxmox host.

This setup allows VMs/containers to communicate internally using 10.0.0.x IPs and be accessed externally via port forwarding rules defined by nat_manager.py.

Comments

  • Useful

    Thanked by 1loay
  • YmpkerYmpker Member
    edited September 2024

    This looks amazing. Thanks :)
    Always wanted to play around with NAT. Maybe if someday I get a ZAP Hosting Lifetime Dedi it's time to create lots and lots of (free) NAT vms on it as per @Neoon suggestion a looong while ago iirc.

    Thanked by 1loay
  • @Ympker said:
    This looks amazing. Thanks :)
    Always wanted to play around with NAT. Maybe if someday I get a ZAP Hosting Lifetime Dedi it's time to create lots and lots of (free) NAT vms on it as per @Neoon suggestion a looong while ago iirc.

    or ks-a :D

    Thanked by 1Ympker
  • @loay said:

    @Ympker said:
    This looks amazing. Thanks :)
    Always wanted to play around with NAT. Maybe if someday I get a ZAP Hosting Lifetime Dedi it's time to create lots and lots of (free) NAT vms on it as per @Neoon suggestion a looong while ago iirc.

    or ks-a :D

    If it comes back :X

  • Will try this soon
    Unsure how to deal with ipv6....

    I hate networking...

  • @DeadlyChemist said: Unsure how to deal with ipv6....

    Me too. It's different per provider.

  • good for people who wanna run proxmox off of just one public ip

    Thanked by 1loay
  • good reference! Thanks for writing this up.

    Thanked by 1loay
  • ChillBirdChillBird Member
    edited December 2024

    this is great. however too complicated for me when it comes to networking. is there nay easy way to run proxmox vms with just one public ip?

    Thanked by 1loay
  • ChillBirdChillBird Member
    edited December 2024

    i got my own manual setup working, @loay does this script not need a network refresh using ifreload -a ?

  • @aryanraj said:
    i got my own manual setup working, @loay does this script not need a network refresh using ifreload -a ?

    No, iptables rules are independent of interface files.

    Thanked by 1ChillBird
  • AWESOME! I'm trying this. Anyone want a free low end nat box on my server to test out?

  • @loay Thanks for this amazing script. It does exactly what it says on the tin. However, I do have one question:

    Isn't this:

    To ensure the rules persist after reboot, use iptables-save > /etc/iptables/rules.v4 and iptables-restore < /etc/iptables/rules.v4.

    The same as this?

    sudo netfilter-persistent save
    

    Thank you :)

  • loayloay Member
    edited November 2025

    @Freek said:
    @loay Thanks for this amazing script. It does exactly what it says on the tin. However, I do have one question:

    Isn't this:

    To ensure the rules persist after reboot, use iptables-save > /etc/iptables/rules.v4 and iptables-restore < /etc/iptables/rules.v4.

    The same as this?

    sudo netfilter-persistent save

    Thank you :)

    Yes, they do the same thing except for the IPv6. I have actually updated this code since this post, I will review it and publish the new version. Let me know if you have any features requests or improvements :)

  • @loay said:

    @Freek said:
    @loay Thanks for this amazing script. It does exactly what it says on the tin. However, I do have one question:

    Isn't this:

    To ensure the rules persist after reboot, use iptables-save > /etc/iptables/rules.v4 and iptables-restore < /etc/iptables/rules.v4.

    The same as this?

    sudo netfilter-persistent save

    Thank you :)

    Yes, they do the same thing except for the IPv6. I have actually updated this code since this post, I will review it and publish the new version. Let me know if you have any features requests or improvements :)

    Great, thank you :) I don't have any feature requests, but perhaps you could share the code via Github. That way it'll be easier to update and maintain the code :) Thanks!

    Thanked by 2barbarza loay
  • I made something similar using a bash (😂😂😂) script. Yours looks good.

  • Cool stuff! Wish I would have had it when I was setting up proxmox and nat on my ovh box.

  • @loay is the new version of the script backwards compatible with the current one? I'm debating whether I should wait to set up my OVH box, as I'd prefer not to redo everything :)

    Thanks!

  • @Freek said:
    @loay is the new version of the script backwards compatible with the current one? I'm debating whether I should wait to set up my OVH box, as I'd prefer not to redo everything :)

    Thanks!

    No, sorry. It is not backwards compatible. Current script will work fine with only Proxmox on the server with no conflicting ports. This subprocess.run(['iptables-save'], stdout=open('/etc/iptables/rules.v4', 'w')) dumps the entire system iptables rules including those by pve-firewall.

    Thanked by 1Freek
Sign In or Register to comment.