Simple perl script to remove unused IP addresses from a Plesk server

This script requires perl’s DBI and DBD-MySQL modules.  If you’re on RHEL/CentOS 6, just run the following if you get an error about those not being present:  yum install perl-DBD-MySQL perl-DBI -y

Here’s the script:


#!/usr/bin/perl
use DBI;
use strict;
use warnings;

# Connect to Plesk 'psa' database
open PSAPASS, "</etc/psa/.psa.shadow";
my $psaDBAdminPass = <PSAPASS>;
close PSAPASS;
chomp $psaDBAdminPass;
my $psaDatabase = DBI->connect("DBI:mysql:psa","admin","$psaDBAdminPass") or die "Mysql connection to psa database failed.\n";

my $deadIPQuery = $psaDatabase->prepare(q~ SELECT IP_Addresses.id, IP_Addresses.ip_address FROM IP_Addresses WHERE IP_Addresses.default_domain_id = '0' AND IP_Addresses.id NOT IN ( SELECT DISTINCT ipAddressId FROM IpAddressesCollections) ORDER BY INET_ATON(IP_Addresses.ip_address) ASC ~);

$deadIPQuery->execute() or die "Mysql query to psa database failed.\n";

open ( REMOVEFILE, ">remove-ips.sh" );

while (my $IP_Addresses = $deadIPQuery->fetchrow_hashref()) {
my $currentIP = $IP_Addresses->{'ip_address'};
print( "$currentIP\n" );
print REMOVEFILE ( "/usr/local/psa/bin/ipmanage -r $currentIP\n" );
}

close REMOVEFILE;

When you run it, it will output every IP it feels you should remove, in sorted order, and will write out a file called remove-ips.sh which will have the necessary Plesk commands to remove them.

The way it works is by looking at the ipAddressId from the IpAddressesCollections table in the psa database.  That table maps every domain to the ip address it has services on.  If there’s an IP in the IP_Addresses table whose id does not appear in the IpAddressesCollections table, then it’s not being used.

Leave a Reply

Your email address will not be published. Required fields are marked *