I need to create an email notification linux script which can be used in the server patching activity. I have created one script for the same but getting some errors. Can anyone please check what's the issue.
Script -
#email constants
export to_addresses=xyz#abc.com
auth_1_app_path=/export/home/apps/test1/dev1;
function sendServerPatchingSuccessMail()
{
printf "HI Team,\r\n\r\nServer patching activity has been done successfully.\r\n\r\nRequest eText DEV team to validate the server patching changes.\r\n\r\nTotal time taken = $(( ($end_date-$start_date) / ( 60) )) minutes.\r\n\r\nRegards,\r\nAdmin\r\n\r\nNote: This is an auto generated mail, please do not reply. " | mail -s "server patching activity is done sucessfully." $to_addresses -c $cc_addresses
}
function sendServerPatchingStartMail()
{
printf "Hi Team,\r\n\r\nServer patching activity has started at $start_date.\r\n\r\nRequest eText DEV team to validate the server patching changes once they receive the server patching success mail.\r\n\r\nRegards,\r\nAdmin\r\n\r\nNote: This is an auto generated mail, please do not reply. " | mail -s "server patching activity has started." $to_addresses -c $cc_addresses
}
#define list of hosts as array
servers_array=( bookvm04 #DEV1
);
function doWork() {
start_date=$(date +%Y%m%d%H%M%S);
sendServerPatchingStartMail
#stop tomcat on all hosts
echo "`date "+%Y-%m-%d %H:%M:%S"` Stop tomcat stop."
#start for each host
for i in "${servers_array[#]}"
do
export ssh_to_remote_host="ssh -l bookweb -i /export/home/apps/bookplus/.ssh/id_dsa "
case $i in
#DEV1 Book Server
b3bookvm05)
app_path=$view_1_app_path;
;;
#DEV1 Book Server
b3bookvm04)
app_path=$auth_1_app_path;
;;
*) echo "`date "+%Y-%m-%d %H:%M:%S"` $i is not a valid option exiting"
exit 0;;
esac #end case
$ssh_to_remote_host $i $app_path/scripts/stopremote
if [ "$?" -ne 0 ]
then
echo "`date "+%Y-%m-%d %H:%M:%S"` node ${i} could not be stopped"
exit 0
fi
end_date=$(date +%Y%m%d%H%M%S);
echo "`date "+%Y-%m-%d %H:%M:%S"` Total time taken = $(( ($end_date- $start_date) / ( 60) )) minutes";
sendServerPatchingSuccessMail
}
Error while executing above script
-bash-4.1$ sh server_patching_alert.sh
: command not foundrt.sh: line 4:
: command not foundrt.sh: line 5:
: command not foundrt.sh: line 9:
: command not foundrt.sh: line 13:
'erver_patching_alert.sh: line 14: syntax error near unexpected token `
'erver_patching_alert.sh: line 14: `function sendServerPatchingSuccessMail()
This script is working fine.
server_array=$(hostname)
function sendServerPatchingSuccessMail()
{
# Set email constants
to_addresses=
cc_addresses=
# Send server patching completion mail
printf "mail body - server patching activity for hostname '$server_array' has been completed successfully" | mail -s "mail subject" -c $cc_addresses $to_addresses
}
sendServerPatchingSuccessMail
Related
I have a shell script. To this script I am passing arguments from a file. This file contains tables names
The script is working fine. I am able execute the command for all the tables in the file.
shell script
#!/bin/bash
[ $# -ne 1 ] && { echo "Usage : $0 input file "; exit 1; }
input_file=$1
TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log
#Function to get the status of the job creation
function log_status
{
status=$1
message=$2
if [ "$status" -ne 0 ]; then
echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
#echo "Please find the attached log file for more details"
#exit 1
else
echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
fi
}
while read table ;do
sqoop job --exec $table > /home/$USER/logging/"${table}_log" 2>&1
g_STATUS=$?
log_status $g_STATUS "Sqoop job ${table}"
cp /home/$USER/logging/"${table}_log" /home/$USER/debug/`date "+%Y-%m-%d"`/logs/
done < ${input_file}
Now I want to send emails to my email address for failed jobs.
Requirements
1) Send email for each failed job i.e If `status log` has failed job for one particular table then I want email sent out saying job for that table has failed.
2) Or Send out one email for all the jobs that have failed for one input file.
Which is the best method to approach. I would like the 2nd option atleast it will reduce the no of emails to go through.
But better if I know both methods to do
edited function log_status
#Function to get the status of the job creation
function log_status
{
status=$1
message=$2
if [ "$status" -ne 0 ]; then
echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
mail -a mail.txt -s "This is the failed job log" user#example.com < /home/$USER/logs/${TIMESTAMP}.fail_log
#exit 1
else
echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
fi
}
If I do this will I get one email for all the failed jobs.
Also it's possible using sendmail command:
sendmail user#example.com < email.txt
Using mail command:
mail -a mail.txt -s "This is the failed job log" user#example.com
-a is a attachment, -s is a subject
And with many attachments:
$(uuencode file1.txt file2.txt) | mailx -s "Subject" user#example.com
Here is a simple snippet for sending an err.log:
mail -s "stder logs for ps" "name#example.com" < err.log
This appends a subject in the first quotes and mails it to the recipient in the second set. In this case I suppose you would have a code block export the error logs via 3> to a file which I called err.log for readability. I would place the above snippet either inside of your script if you are not worried about being too vocal about the errors or neatly outside of the script if you want to be more discrete about how often you are emailing the recipient.
I'm building a backup script to run on Ubuntu.
backup-all.sh file:
echo "bootstrap"
/home2/backup/bootstrap/backup.sh
BOOTSTRAP_STATUS=$([ "$?" == 0 ] && echo "OK" || echo "** FAIL **")
echo "sv2"
/home2/backup/sv2/backup.sh
SV2_STATUS=$([ "$?" == 0 ] && echo "OK" || echo "** FAIL **")
if [ "$BOOTSTRAP_STATUS" == "OK" ] && [ "$SV2_STATUS" == "OK" ] ; then
TITULO="Backup OK"
else
TITULO="Backup !FAILED!"
fi
(
echo "Backup status"
echo "-------------"
echo "BOOTSTRAP_STATUS = $BOOTSTRAP_STATUS"
echo "SV2_STATUS = $SV2_STATUS"
echo "-------------"
) | mail -s "${TITULO}" "my#mail.org"
The backup.sh files ends with:
exit 0 # for success; OR:
exit 1 # for errors + send mail with log file
* backup.sh files contains rsync and mysql backup.
When the script returns 1 (error), it will also send me an e-mail telling me that's something is wrong and all steps are recorded on a log file.
** I have email calls. One for overview, and one for each "server" which gets errors.
So, If I run manually,
./backup-all.sh
Everything is nice. I receive just one mail with title "Backup OK".
If I wait cron to run the job, I receive just one mail with title "Backup !FAILED!", even though I didn't receive errors details and the log files are OK.
crontab -e
0 0 * * * /home2/backup/backup-all.sh
So, what cron job does with the condition/exit values of my scripts?
to debug, log stdout and error to log file:
0 0 * * * /home2/backup/backup-all.sh > /tmp/debug.log 2>&1
A few possibilities, cron does not have proper env by default or by design:
rsync and mysqldump not in cron env
add #!/usr/bin/bash to your bash script
this is the full code of my script which I use on linux RHEL5 and it used to have no error. Recently, I copied the same script file for use on another linux RHEL6 server and I get the following error:
[zenoss]$ bash zen-remote-bkp.sh
: command not foundline 14:
: command not foundline 23:
Started at : Wed-11/05/14-#-09:42:13 AM-EST
: command not foundline 26:
find: `/opt/zenoss/backups/\r': No such file or directory
zen-remote-bkp.sh: line 51: syntax error: unexpected end of file
Code:
SERVER_HOSTNAME="server"
ZENOSS_BACKUP_DIR="/opt/zenoss/backups"
BACKUP_COUNT=0
RSYNC_HOST="client"
SSH_RSYNC_USER="zenoss"
SSH_RSYNC_DEST_DIR="/var/backups_dir/zenoss/$SERVER_HOSTNAME"
MESSAGE_FILE="/home/zenoss/message.txt"
# Initialize the message file with the starting date and time
echo "Started at : " `date +%a-%D-#-%X-%Z`
# Check to see if there are any backup archives
BACKUP_COUNT=`find $ZENOSS_BACKUP_DIR -name "zenbackup*" | wc -l`
if [ "$BACKUP_COUNT" -eq 0 ] ; then
echo "No backup archive to synchronize!"
echo "Ended at : " `date +%a-%D-#-%X-%Z`
exit 1
fi
# Transfer most recent backup via rsync over ssh and (later) delete all
# backups older than 3 days
RECENT_BACKUP=`ls -1 $ZENOSS_BACKUP_DIR/zen* | tail -n 1`
echo "Most recent backup : " $RECENT_BACKUP
rsync -az --stats --partial --ignore-existing -e ssh $RECENT_BACKUP $SSH_RSYNC_USER#$RSYNC_HOST:$SSH_RSYNC_DEST_DIR 2>&1
if [ "$?" -ne 0 ] ; then
echo "Backup archive replication failed!"
echo "Ended at : " `date +%a-%D-#-%X-%Z`
exit 1
fi
echo "Backup archive replication successful!"
echo "Ended at : " `date +%a-%D-#-%X-%Z`
exit 0
Does anyone know what is the cause of it? Thank you.
I have a written a shell script wherein I want to send an email through it. I am executing this script on windows through cygwin. I have installed email package on my machine. However, I am having a hard time making it work. Please let me know what is the easiest way to send email through cygwin command prompt.
My ssmtp.conf file is :
mailhub=smtp.gmail.com:587
FromLineOverride=YES
rewriteDomain=gmail.com
root=aci.lfindba#gmail.com
UseTLS=YES
AuthUser=userid
AuthPass=password
and email.conf file has:
SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = '25'
MY_NAME = 'ABC'
MY_EMAIL = 'emailaddress'
REPLY_TO = 'emailaddress'
USE_TLS = 'true'
ADDRESS_BOOK = '&/email.address.template'
SMTP_AUTH = 'LOGIN'
SMTP_AUTH_USER = 'userid'
SMTP_AUTH_PASS = 'password'
I am using below command to send email:
echo "mail body"|email -s "subject" recipient#gmail.com
However, I am getting following error:
email: FATAL: Could not connect to server: smtp.gmail.com on port: 25: Operation not permitted
Please help.
Install and configure the ssmtp package.
Create /bin/mail with these contents:
#!/bin/sh
#
# copyright 2016 Gene Pavlovsky [http://www.razorscript.com]
#
# mail: mail-like wrapper script for sendmail
SENDMAIL=/usr/sbin/ssmtp
usage()
{
{
echo "Usage: $(basename $0) [-s "subject"] [-f from-addr] [to-addr]..."
echo
echo "Sends mail."
echo
echo "Options:"
echo -e " -s\tsubject (quote subjects containing spaces)"
echo -e " -f\tfrom address"
} >&2
exit 2
}
while test $# -gt 0; do
case $1 in
-s)
shift
test $# -eq 0 && usage
subj=$1
;;
-f)
shift
test $# -eq 0 && usage
from=$1
;;
-*)
usage
;;
*)
rcpt+=( "$1" )
;;
esac
shift
test "$end_options" = yes && break
done
test ${#rcpt} -eq 0 && usage
{
test "$from" && echo From: $from
test "$subj" && echo Subject: $subj
echo
exec /bin/cat
} | "$SENDMAIL" "${rcpt[#]}"
Don't forget to chmod 755 /bin/mail.
I use the msmtp package, with this configuration:
port 587
auth on
from srpen6#gmail.com
host smtp.gmail.com
tls on
tls_certcheck off
user srpen6#gmail.com
https://cygwin.com/cgi-bin2/package-grep.cgi?grep=msmtp&arch=x86_64
I wrote script to send mail automatically using an SMTP connection but when I execute the script, sometimes it works and sometimes it is not sending mail. Behavior is quite ambiguous.
Environment : Linux Server Fedora 14
Mailing Client : Lotus Notes 8.5.2
Please find script below.
# Function for sending email
sendemail(){
date=`date '+%d-%m-%Y'`
dbDir=/var/lib/MYSQLBACKUP/$date
dbname='DBNAME'
log_file="${dbDir}/${dbname}_${date}.log"
attached_file="${dbname}_${date}.log"
echo $log_file
echo $attached_file
encoded_log_file=`cat $log_file | openssl base64`
#echo $encoded_log_file
( echo open 172.40.201.31 25
sleep 8
echo helo 172.40.201.31
echo mail from:Pratik.Vyas#gmail.com
echo rcpt to:Pratik.Vyas#gmail.com
echo data
echo to:Pratik.Vyas#gmail.com
echo from:Pratik.Vyas#gmail.com
echo "subject: SPARC CQ DB Backup Report : $date :"
echo "MIME-Version: 1.0"
#echo "Content-Type: text/plain; charset=UTF-8"
#echo "Please view attached file"
echo "Content-Type: text/x-log;name="$attached_file""
echo "Content-Disposition:attachment;filename="$attached_file""
echo "Content-Transfer-Encoding: base64"
echo $encoded_log_file
echo $1
sleep 15
echo .
echo ^]
echo quit ) | telnet
echo "status:$?"
echo "Hello done"
}
sendemail
Here's a rewrite using /usr/lib/sendmail. This is not necessarily the correct location for your system, but you should be able to adapt it.
# Function for sending email
sendemail(){
date=$(date '+%d-%m-%Y') # prefer $(...) over `...`
dbDir=/var/lib/MYSQLBACKUP/$date
dbname='DBNAME'
log_file="${dbDir}/${dbname}_${date}.log"
attached_file="${dbname}_${date}.log"
echo $log_file
echo $attached_file
encoded_log_file=$(openssl base64 < "$log_file") # notice UUCA fix + quoting
#echo $encoded_log_file
# You should configure sendmail to use 172.40.201.31 as your smarthost
/usr/lib/sendmail -oi -t <<________HERE
to: Pratik.Vyas#gmail.com
from: Pratik.Vyas#gmail.com
subject: SPARC CQ DB Backup Report : $date :
MIME-Version: 1.0
Content-Type: text/x-log; name="$attached_file"
Content-Disposition: attachment; filename="$attached_file"
Content-Transfer-Encoding: base64
X-Ample: notice empty line between headers and body! # <-- look
$encoded_log_file
$1
________HERE
echo "status:$?"
echo "Hello done"
}
sendemail
I would recommend using a library or command line program (like mail or mailx) to send mail instead of trying to implement SMTP in a shell script.