| Current File : //proc/24011/root/usr/local/scripts/changemx.pl |
#!/usr/local/cpanel/3rdparty/bin/perl
use Net::DNS;
use JSON qw( decode_json );
use Data::Dumper;
use Getopt::Long;
$force = "";
$domain = "";
$local = "";
$configFileName = "/usr/local/scripts/changemx.conf";
GetOptions ('f' => \$force, 'd=s' => \$domain );
my %configParamHash = ();
open ( _FH, $configFileName ) or die "Unable to open config file: $!";
while ( <_FH> ) {
chomp;
s/#.*//; # ignore comments
s/^\s+//; # trim leading spaces if any
s/\s+$//; # trim leading spaces if any
next unless length;
my ($_configParam, $_paramValue) = split(/\s*=\s*/, $_, 2);
$configParamHash{$_configParam} = $_paramValue;
}
close _FH;
$mx1 = $configParamHash{mx1};
$mx2 = $configParamHash{mx2};
$ttl= $configParamHash{ttl};
#Let's do some checks before proceeding:
if ($mx1 eq "") {
print "Missing mx1 variable from config file. Please add \"mx1=some.host\" to $configFileName \n";
exit;
}
if ($mx2 eq "") {
print "Missing mx2 variable from config file. Please add \"mx2=some.host\" to $configFileName \n";
exit;
}
if ($ttl eq "") {
print "Missing ttl variable from config file. Please add \"ttl=somevalue\" to $configFileName \n";
exit;
}
if ($domain eq "") {
print "Missing domain. Please specify with -d \n";
exit;
}
$local = `grep $domain /etc/localdomains`;
chomp($local);
if ($local eq "") {
print "$domain is not local \n";
exit;
}
# We only check the actual MX records if -f wasn't specified :
if ($force eq "") {
$dns = new Net::DNS::Resolver(nameservers => [qw(1.1.1.1)]);
$mx = $dns->query( $domain, 'MX' );
if (defined $mx) {
foreach my $rr ($mx->answer) {
if ($rr->type eq "MX") {
$mx=$rr->exchange;
if (lc($rr->exchange) =~ "cleanmx" || lc($rr->exchange) =~ "microsoft" || lc($rr->exchange) =~ "google") {
print "\tMX already set to antispam or external = ".$rr->exchange." . To override specify -f \n";
$cleanmx = 1;
exit;
}
}
print "\t", $rr->exchange, ' (', $rr->preference, ")\n";
}
}
}
#Stupid loop of 10 cycles -just to be sure- because lines get renumbered everytime we whapi1 removezonerecord ...
$loop = 0;
while ($loop < 10 ) {
$zone = `whmapi1 dumpzone domain=$domain --output=jsonpretty`;
$text = decode_json($zone);
$cnt = 0;
while ($cnt < 500 ){
$linha = $text->{data}->{zone}[0]->{record}[$cnt]->{Line};
$registo = $text->{data}->{zone}[0]->{record}[$cnt]->{name};
$type = $text->{data}->{zone}[0]->{record}[$cnt]->{type};
if ( lc($type) eq "mx") {
$cmd = "whmapi1 removezonerecord zone=\'$domain\' line='$linha'";
system($cmd);
#print $cmd."\n";
last;
}
$cnt++;
}
$loop++;
}
$cmd = "whmapi1 addzonerecord domain=$domain name=$domain. exchange=$mx1 class=IN ttl=$ttl type=MX preference=10";
system($cmd);
#print $cmd."\n";
$cmd = "whmapi1 addzonerecord domain=$domain name=$domain. exchange=$mx2 class=IN ttl=$ttl type=MX preference=20";
system($cmd);
#print $cmd."\n";