使用命令行发送电子邮件并保存IP规则

时间:2016-01-28 03:36:52

标签: shell email sendmail

我正在编写脚本来从数据库中的表中选择一些IP,然后使用IPTables规则禁止这些IP,最后一步是通过电子邮件通知,但我收到2个错误:

#!/bin/bash

Now=$(date +"%d-%m-%Y %T")

fileLocation="/var/lib/mysql/DBName/"
fileName="ip2ban.txt"
filePath=$fileLocation$fileName
curLocation=$(pwd)

#Connect to DB and select ban_ip
mysql -u root -pPASSWORD -D DBName -e 'SELECT ip INTO OUTFILE "'$filePath'" FROM ban_ip WHERE ip_tables = "0"' >> banIP.log 2>&1

selRes=$?

# If the command was successful
if [ $selRes -eq "0" ]
then   

    # We need to check if the file exists on the saved location
    #find $fileLocation -type f -iname "ip2ban.txt" -empty => To check if file empty or not

    if [ -f $filePath ]
then   
    mv $filePath $curLocation'/ip2ban.txt'

    # Connect to DB and update the ban_ip
    mysql -u root -pPASSWORD -D DBName -e 'UPDATE ban_ip SET ip_tables = "1" WHERE ip_tables = "0"' >> banIP.log 2>&1

     upRes=$?

    if [ $upRes -eq "0" ]
            then

    # Send message for succesful result
    echo -e "Database updated with new banned IPs on $Now \nThank you for using this script" 2>&1 | sed '1!b;s/^/To: myID@gmail.com\nSubject: New banned IPs[Success]\n\n/' | sendmail -t

    else

    # Send message for failure result
    echo -e "We cannot update the ban_ip table on $Now \nThank you for using this script" 2>&1 | sed '1!b;s/^/To: myID@gmail.com\nSubject: [Failure] New banned IPs\n\n/' | sendmail -t

    fi

fi

else
    echo 'Something wrong with Select statment on' $Now >> banIP.log
fi

# Save IPTables rules
iptables-save > /root/Scripts/IPTables/BannedIPs.conf // LIGNE 53

我收到2个错误:

line 53: iptables-save: command not found 
line 37: sendmail: command not found

然而,已安装sendamil,邮件,后缀:

# which sendmail
/usr/sbin/sendmail

# which mail
/usr/bin/mail

# which postfix
/usr/sbin/postfix

感谢您的平常支持

1 个答案:

答案 0 :(得分:1)

根据Linux的crontab(5)手册页:

  

PATH设置为" / usr / bin:/ bin"。

意味着您的shell脚本将无法在/ usr / sbin或/ sbin下找到任何内容。通过在脚本顶部附近添加以下内容来更改此选项:

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

此外,可以在crontab中设置环境。有关如何执行此操作,请参阅https://stackoverflow.com/a/14694543/5766144