Change relay routing and postfix parameter perl script for postfix (failover relay)

change_relay.pl

#!/usr/bin/perl

use Term::ANSIColor;

my $relay_04_gw = "10.24.0.1";
my $relay_03_gw = "10.24.25.1";
my $relay_04_gw_interface = "eth0";
my $relay_03_gw_interface = "eth1";
my @file = split( " ", qx+cat /etc/postfix/main.cf | grep ^myhostname+);
my $hostname = $file[2];
chomp $hostname;

print color("green"), "Estado: ".$hostname."\n", color("reset");
print "Escoja la opción:\n";
print "1. Cambiar a relay-03.xxx.com\n";
print "2. Cambiar a relay-04.xxx.com\n";
my $answer = <>;
chomp $answer;

if ( $answer eq "1" ){
 my $new_hostname = "relay-03.xxx.com";
 check_hostname($new_hostname);
 change_iptables("25", "tcp", "drop");
 change_routing("delete", $relay_04_gw, $relay_04_gw_interface);
 change_routing("add", $relay_03_gw, $relay_03_gw_interface);
 system("sed -i s/$hostname/$new_hostname/g /etc/postfix/main.cf");
 system("/etc/init.d/postfix restart");
 change_iptables("25", "tcp", "accept");
 print color("red"), "Cambiado a ".$new_hostname."\n", color("reset");
}

if ( $answer eq "2" ){
 my $new_hostname = "relay-04.xxx.com";
 check_hostname($new_hostname);
 change_iptables("25", "tcp", "drop");
 change_routing("delete", $relay_03_gw, $relay_03_gw_interface);
 change_routing("add", $relay_04_gw, $relay_04_gw_interface);
 system("sed -i s/$hostname/$new_hostname/g /etc/postfix/main.cf");
 system("/etc/init.d/postfix restart");
 change_iptables("25", "tcp", "accept");
 print color("red"), "Cambiado a ".$new_hostname."\n", color("reset");
}

sub change_routing() {
 my $action = $_[0];
 my $gateway = $_[1];
 my $interface = $_[2];
 if ( $action eq "add" ){
 system("ip route add default via $gateway dev $interface");
 }
 if ( $action eq "delete" ){
 system("ip route del default via $gateway dev $interface");
 }
}

sub change_iptables() {
 my $port = $_[0];
 my $protocol = $_[1];
 my $action = $_[2];
 if ( $action eq "drop" ){
 system("iptables -I INPUT -p $protocol --dport $port -j DROP");
 }
 if ( $action eq "accept"){
 system("iptables -D INPUT -p $protocol --dport $port -j DROP");
 }
}

sub check_hostname() {
 my $new_hostname = $_[0];
 if ( $new_hostname eq $hostname ){
 die "$hostname ya se encuentra asignado\n";
 }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s