2

I to write a bash script to send an email when local host connection is refused and when the connection is open, it should not write an email. For example:

netcat -z localhost 8287
if [ $? -ne 0 ]; then
  echo " Connection refused" |/usr/lib/sendmail -s "Port  doesn't function "  [email protected]
else
  echo "open"
fi

When I fire this bash scriptit does't work. I replaced sendmail by mail, sendEmail also, but every time I am getting different errors.

4
  • 1
    use /usr/bin/mail. You are not supposed to use sendmail (and anything in /usr/lib/) Commented Nov 30, 2016 at 10:14
  • @thanks Giacomo Catenazzi, I tried that way also but it doesn't give any error and i am not receiving an email as well. I have searched a lot but didn't get any concrete idea.
    – M. Thakur
    Commented Nov 30, 2016 at 10:21
  • So I think your system is not configured to send email outside your host. Check in /var/spool/mail for undelivered mails, or the logs. Install nullmailer or ssmtp (or a complete mta system) Commented Nov 30, 2016 at 10:25
  • Add content of your /var/log/maillog to your initial post Commented Nov 30, 2016 at 11:42

2 Answers 2

2

The following works on my systems:

if ! nc -z $host $port; then
    echo "This message intentionally left blank" | mail -s "TCP port $port is not open on $host" $emailaddress
else
    : Do whatever you wanted to do
fi

If it doesn't on yours, run tail -f /var/log/maillog while you run the script to see why the message might not be getting delivered.

0

Try:

/usr/lib/sendmail -oi -t << EOF
Subject: Port doesn't function
To: [email protected]

Connection refused
EOF

Which should be fairly portable (as long as sendmail is found in /usr/lib, you may want to try a few other locations like /usr/sbin or just use sendmail for a $PATH lookup if it's not there).

-oi is to not consider a "." on a single line as a terminator (not needed here, but useful in the general case).

On POSIX compliant systems, you should also be able to use mailx:

echo Connection refused | mailx -s "Port doesn't function" [email protected]

All those assume the system has a properly configured mail transfer agent.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.