Perl scripts are a sysadmin’s best friend

As shown previously, I use a Perl script to generate my post keywords. But I got tired of having to pop open a terminal window, login to the machine where the script lives, and paste in the document to analyze, then copy the keywords back over. And what if I don’t have shell access from where I am? So I decided to take advantage of Sendmail’s flexibility to deliver mail to programs via anonymous pipes. I wrote a Perl script that accepts an e-mail message on stdin, saves the content to a temp file, calls the keyword script on the tempfile, parses the SMTP headers, and returns the keywords in e-mail back to the sender. Here’s the code:

use warnings;
use strict;
use Data::Dumper;

local $/ = undef;
my $msg = <>;
open (FILE, '>/tmp/mail') or die $!;
my $m_content = $msg;

if ($msg =~ /\n\n/) {
        $m_content = $';

print FILE $m_content;
close FILE;
my $keywords = `/usr/local/bin/ /tmp/mail`;
#unlink "/tmp/mail";
my $return_address = "";
my $subject = "";

if ($msg =~ m/^From: .+$/m) {
        $return_address = $&;
        $return_address =~ s/From: //;
        print "Found From: header\n";

if ($msg =~ m/^Reply-to: .+$/m) {
        $return_address = $&;
        $return_address =~ s/Reply-to: //;
        print "Found Reply-to: header\n";

if ($msg =~ m/^Subject: .+$/m) {
        $subject = $&;
        $subject =~ s/Subject: //;
        print "Found Subject: header\n";

my $sendmail = "/usr/sbin/sendmail -t";
my $reply_to = "Reply-to: mailer-daemon\\n";
$subject = "Subject: $subject\n";
my $from = "From: "."mailer-daemon\\n";
my $to = "To: "."$return_address\n";

open (SENDMAIL, "|$sendmail") or die $!;
print $reply_to;
print SENDMAIL $reply_to;
print $subject;
print SENDMAIL $subject;
print $from;
print SENDMAIL $from;
print $to;
print SENDMAIL $to;
print SENDMAIL "Content-type: text/plain\n\n";
print SENDMAIL "$keywords\n\n.\n";
close (SENDMAIL);

  1. #1 by Joshua on January 8, 2011 - 4:18 PM

    The beauty is that any output to stdout is ignored unless the script errors, then it gets sent back to the sender in the DSN.

  2. #2 by Joshua on January 10, 2011 - 7:37 AM

    I’d like to have it just pass the content to the keyword script but that would require modifying the keyword script to accept the option terminator string (–, which is two dashes for those whose font makes it look like only one) and take input from stdin, which it currently does not.

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: