Redirecting database traffic with iptables

To temporally redirect traffic from one port to another use the following iptables rules
export source=3306 
export destination=13306 
export host=`hostname` 
iptables -t nat -A PREROUTING -p tcp –dport $source -j REDIRECT –to-port $destination 
iptables -t nat -A OUTPUT -p tcp -d 127.0.0.1 –dport $source -j REDIRECT –to-port $destination 
iptables -t nat -A OUTPUT -p tcp -d $host –dport $source -j REDIRECT –to-port $destination
To check them
iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target prot opt source destination 
REDIRECT tcp — anywhere anywhere tcp dpt:mysql redir ports 13306 
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination 

Chain OUTPUT (policy ACCEPT)
target prot opt source destination 
REDIRECT tcp — anywhere localhost tcp dpt:mysql redir ports 13306 
REDIRECT tcp — anywhere db2.example.com tcp dpt:mysql redir ports 13306
To remove them
iptables -t nat -D PREROUTING -p tcp –dport $source -j REDIRECT –to-port $destination 
iptables -t nat -D OUTPUT -p tcp -d 127.0.0.1 –dport $source -j REDIRECT –to-port $destination 
iptables -t nat -D OUTPUT -p tcp -d $host –dport $source -j REDIRECT –to-port $destination
Advertisements
Redirecting database traffic with iptables