I have a perl script which runs and send out e-mail if duplicates are found.
I would like to run the with option (like -e) so that it will produce the out put only and will not send out e-mail.
How can I achieve it. I would appreciate the help.
Thanks.
Example: ./file1 (sends out e-mail)
./file1 -e (will not send out e-mail just will show the output in the screen).
Here is the script:
use strict;
use warnings;
use MIME::Lite;
my (%ip, %host, $duplicate_ip, $duplicate_host);
my $host_file = '/etc/hosts';
open my $file, '<', $host_file or die "can't open $host_file $!";
while (<$file>) {
if( my ($ip, $host) = /^#?([\d.]+)\s+(\S+)/ ) {
s/\s+\b/\t/g;
push @{$ip{$ip}}, $_;
push @{$host{$host}}, $_;
}
}
close $file;
#print "Duplicate IP's with hostnames\n";
foreach my $ip ( keys %ip ) {
if ( @{$ip{$ip}} > 1 ) {
$duplicate_ip .= join ('', @{$ip{$ip}}) . "\n\n";
}
}
#print "\nDuplicate hostnames with IP's\n";
foreach my $host ( sort keys %host ) {
if ( @{$host{$host}} > 1 ) {
my ($ip) = $host{$host}[0] =~ /^#?([\d.]+)/;
unless ( @{$ip{$ip}} > 1 ) {
$duplicate_host .= join('', @{$host{$host}}) . "\n\n";
}
}
}
my $email_msg = <<EMAIL_MSG;
The following entries in the host file are duplicates
either by IP address or by hostname.
\n
************Duplicate IP addresses**************:
\n
$duplicate_ip
************Duplicate Hostnames*****************:
\n
$duplicate_host
EMAIL_MSG
print $email_msg;
my $email = MIME::Lite->new(
From => 'xxx@xxx.com',
To => 'xxx@xx.com',
Cc => 'xxy@xx.com,xxz@xx.com',
Subject => 'Host file duplicates',
Data => $email_msg
);
if ($duplicate_ip || $duplicate_host) {
$email->send } #send email if duplicate found