How to send email on my shell script condition in jenkins - shell

i had created a job and in build step i had given below mentioned shell script
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free avilable) percentage
# of space is >= 70%
# -------------------------------------------------------------------------
# set admin email so that you can get email
# set alert level 70% is default
ALERT=70
EXCLUDE_LIST="/net|/home|devfs"
if [ "$EXCLUDE_LIST" != "" ] ; then
df -H | grep -vE "^Filesystem|Users|${EXCLUDE_LIST}" | awk '{ print $5 " " $1 }' | while read output;
do
#echo $output
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge $ALERT ]; then
echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" > /Users/Shared/Jenkins/disk_space.txt
else
echo "space \"$partition ($usep%)\" on $(hostname) as on $(date)" > /Users/Shared/Jenkins/space.txt
fi
done
fi
After this script executed the email need to be triggered in jenkins if the condition satisfied. otherwise job should run but email should not trigger.

Looks like a standard question on how to send an email from a shell script: Have a look at the following links.
Shell script to send email
http://theos.in/shell-scripting/send-mail-bash-script/
http://www.cyberciti.biz/faq/linux-unix-bash-ksh-csh-sendingfiles-mail-attachments/

One way may be to call another jenkins job within the if loop, using jenkins cli.You can have another job configured which will trigger a mail with certain content. And that job will be triggered within the success part of your if loopMore info on jenkins CLI can be found at here
May be this will be helpful.

Related

Email Alerts when service or server automatically comes up

I am working on a bash script that helps to ping and get the network interface level status of the host machines and services.
This script will send a email alerts in case of failure.
#!/bin/bash
HOSTS="192.168.8.200"
COUNT=4
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail -s “Mail subject” anymail#anydomain.com
fi
done
This works fine.
But need help to get a one single email alert when host automatically comes up (ping success).
You need to save the state of the host (up/down) during the calls of your script.
if the host is "up" and the former state was "down" then you need to send an email.
You can just write the result of the "check command" to a file in /tmp/
if the check returns that the server is up you read the content of the file. if the state is "down" in the file, then send an email an write "up" to the file.
on the next check if the server is up, there will be no additional email sent, because the server was also "up" before.
#!/bin/bash
HOSTS="192.168.8.200 192.168.8.201 192.168.122.1"
COUNT=4
STATE="/tmp/ping_state.txt"
for myHost in $HOSTS
do
count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
if [ $count -eq 0 ]; then
# 100% failed
#echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail -s “Mail subject” anymail#anydomain.com
echo "host $myHost down"
#delete all previous entries of that ip
sed -i "/$myHost/d" $STATE
#mark host as down
echo "$myHost - down" >> $STATE
else
CHECK=`grep "$myHost" $STATE | grep -o "down"`
if [ "$CHECK" = "down" ]; then
echo "host $myHost up again"
#insert email for host up here
fi
#delete all previous entries of that ip
sed -i "/$myHost/d" $STATE
echo "$myHost - up" >> $STATE
fi
done
for simple testing I just used an echo statement instead of sending an email.

Real time CPU% by process monitoring script in AIX 6.1

I'm trying to write a script that monitors real time CPU% load in AIX 6.1-servers by process(PID), and have been searching for this both in IBMs documentation and all over stackoverflow.
I only find examples of people using, for example
ps aux
Needless to say, thats not what I need, since it only monitors how much CPU% the process has been using over the session time, which in my case is quite long.
The information I need is contained in topas and nmon, but I don't know how to grab a snapshot of this information for each individual moment.
top
Does not exist in AIX systems.
Solved this by making a script that generates 30second tprof logs and iterates through them adding up the process threads by PID and reaching a sum that equals more or less a real-time CPU load% process list.
Here is a function I use to search and grab CPU load from nmon data log
function fetch_UARG_process_by_pid ()
{
#Check_Argument $1 $2
#parameter initialization
filesource=$1
cpuvalue=$2
readarray -t X <<< "$(grep TOP $filesource)"
length=${#X[#]}
#echo " this is the length of my array : $length"
#you have to start from 2 to avoid the first lines that describe the content of the file
#TOP,%CPU Utilisation
#TOP,+PID,Time,%CPU,%Usr, Sys,Size,ResSet,ResText,ResData,ShdLib,MinorFault,MajorFault,Command
for ((i = 2; i != length; i++)); do
echo ${X[i]} | awk -F "," '{print $2 , $4}' | while read processid n
do
if (( $(echo "$n > $cpuvalue " |bc -l) ));
then
echo "the value of CPU usage is: $n"
echo "the Linux PID is : $processid "
echo "And the short desciption of the process:"
echo ${X[i]} | awk -F "," '{print $14}'
echo -e "And the long desciption of the process:"
grep UARG $1 | grep $processid | awk -F "," '{print $5}'
echo -e "\n"
fi
done
done
}

My script is sending non-stop

My shell script below is sending non-stop even if the parameters are not being met already:
MAX=85
EMAIL="my#email.com"
PART=sda1
USE=`df -h |grep $PART | awk '{ print $5 }' | cut -d'%' -f1`
if [ $USE -gt $MAX ]; then
echo "Percent used: $USE of /" | mail -s "Server is running out of disk space" $EMAIL
fi
This code is working on my system. Perhaps check to make sure that the output of dh is always adding up to an amount greater than 85. You may have more success not using the -h argument to dh and instead retrieving the actual number in bytes and operating on that instead.
#!/bin/sh
# Change this number accordingly as usual
MAX=100000000
EMAIL="my#email.com"
PART=sda1
USE=$( df | grep $PART | awk '{ print $3 }' )
if [ "$USE" -gt "$MAX" ]
then echo "Successful"
#echo "Percent used: $USE of /" | mail -s "Server is running out of disk space" $EMAIL
fi
Or for the percentage perhaps try POSIX shell string cutting:
#!/bin/sh
MAX=85
EMAIL="my#email.com"
PART=sda1
USE=$( df | grep $PART | awk '{ print $5 }' )
if [ "${USE%%%}" -gt "$MAX" ]
then echo "Successful"
#echo "Percent used: $USE of /" | mail -s "Server is running out of disk space" $EMAIL
fi
This server is running in AWS. I looked at the email's headers and saw a queer IP address. I traced the IP in AWS and found a replica of the original server I thought was sending out the mails. It was cloned by a now-defunct vendor. So, I just terminated that server and problem solved! :D
This is a very good community! The people are very gifted technically and are so whilling to share. Keep it up, guys! I appreciate all those who tried to help me. Thanks!

How to safely experiment with scripts that fork themselves

I was experimenting with a bash script that would recursively fork and call itself. The terminating condition was subtle and I got it a wrong a few times, the result being a script that called itself ad infinitum. What's a safe way to sandbox a script like this while debugging it so that every time there's a mistake, I don't have to deal with stopping the infinite tower that fills up the process table?
You could use ulimit
ulimit -u 20
Will limit the maximum number of processes runned by your user
You could simply count the numbers of processes with your script name and terminate if the number gets too high.
This blog post introduces a function to achieve this:
count_process(){
return $(ps -ef | grep -v grep | grep -c $1)
}
Explanation (taken from blog post):
ps -ef will return a list of all running processes (in detail),
and the process list will then be filtered first to exclude any instances of grep
and second to count the processes specified with $1
For re-usability the author provides the function as little script:
#!/bin/sh
#
# /usr/bin/processCount
# Source: http://samcaldwell.net/index.php/technical-articles/3-how-to-articles/68-how-do-i-count-the-number-of-linux-instances-of-a-given-process-using-a-bash-script
#
[ -z $1 ] && {
echo " "
echo "Missing expected input."
echo " "
echo "USAGE:"
echo " "
echo " $0 <executable file>"
echo " "
echo " NOTE: When executing this script use the path and filename of the"
echo " program. Using only the process name can potentially return inaccurate"
echo " results."
echo " "
exit 1
}
echo $(ps -ef | grep -v grep | grep -v $0 | grep -c $1)
#script ends here.

Shell script to edit a large text file

I need to append the server name to the front of each user entry associated with that server. Below is an example of the file I'm curently dealing with:
<server_name>
at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash
bin:x:1:1:bin:/bin:/bin/bash
<server_name>
at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash
bin:x:1:1:bin:/bin:/bin/bash
I need a script to strip out the server name and append it to the front of the user entry. So the file would end up looking like this:
<server_name_a>
<server_name_a>:at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash
<server_name_a>:bin:x:1:1:bin:/bin:/bin/bash
<server_name_b>
<server_name_b>:at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash
<server_name_b>:bin:x:1:1:bin:/bin:/bin/bash
Here's a simple awk program that should do what you're describing:
awk '/^INFO/{prefix=$NF;next}{printf "%s:%s\n", prefix, $0}' < ${FILENAME} > ${OUTPUT}
Try something like this:
#!/bin/bash
cat $* | while read line
do
if echo $line | grep "^INFO:" > /dev/null
then
SERVER=`echo "$line" | sed -e 's/.*<\(.*\)>.*/\1/g'`
else
echo $SERVER:$line
fi
done

Resources