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 "  mit@gmail.com
  echo "open"

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

  • 1
    use /usr/bin/mail. You are not supposed to use sendmail (and anything in /usr/lib/) – Giacomo Catenazzi Nov 30 '16 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 Nov 30 '16 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) – Giacomo Catenazzi Nov 30 '16 at 10:25
  • Add content of your /var/log/maillog to your initial post – user1700494 Nov 30 '16 at 11:42

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
    : Do whatever you wanted to do

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.



/usr/lib/sendmail -oi -t << EOF
Subject: Port doesn't function
To: mit@gmail.com

Connection refused

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" mit@gmail.com

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.