jaapar
August 15, 2017, 11:56am
1
I am currently try to write a simple script with the following condition, but so far not having luck as the exit code would always be 0.
Run remote command to read a file and grep for test
word.
if test
word is in the file, send email.
if not, do nothing
also possible to ssh to multiple servers in one script?
Any help would be greatly appreciated. Thank you in advance!
#!/bin/bash
date=`/bin/date +%Y%m%d%H%M%S`
email_to="test_email@xxx.com"
email_subject="subject"
email_body="email body"
server="Host.google.com"
/usr/bin/ssh "$server" "cat log`date +"%m%d"` | grep test" >/dev/null 2>/dev/null
if [ $? -eq 0 ]
then
echo "$email_body" | /bin/mailx -s "$email_subject" "$email_to"
exit 1
fi
exit 0
RudiC
August 15, 2017, 12:16pm
2
I can't confirm that "the exit code would always be 0" :
ssh root@"$server" "grep -q test log$(date +"%m%d")"; echo $?
0
ssh root@"$server" "grep -q txst log$(date +"%m%d")"; echo $?
1
Try
ssh root@"$server" "grep -q test log$(date +"%m%d")" && echo "$email_body" | /bin/mailx -s "$email_subject" "$email_to"
/bin/mailx -s subject test_email@xxx.com
email body
1 Like
I guess the problem is in your invocation of ssh:
/usr/bin/ssh "$server" "cat log`date +"%m%d"` | grep test" >/dev/null 2>/dev/null
The | grep test
should really be running on your machine rather than the server. I also don't like the embedding of quotes - it might work, but ...
I've made a few changes to your code (untested).
#!/bin/bash
date=$(/bin/date +%Y%m%d%H%M%S)
# bash 4.2: printf -v mydate "%(%Y%m%d%H%M%S)T" -2
log_file=$(/bin/date +"log%m%d")
# bash 4.2: printf -v log_file "log%(%m%d)T" -2
email_to="test_email@xxx.com"
email_subject="subject"
email_body="email body"
server="Host.google.com"
/usr/bin/ssh "$server" "cat ${log_file}" | grep test >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo "$email_body" | /bin/mailx -s "$email_subject" "$email_to"
exit 1
fi
exit 0
By setting the name of the log file outside of the invocation of ssh not only do you reduce the number of quotes in the line but it becomes easier to read.
Using backticks for process substitution is deprecated, I believe, and tends to be frowned upon in this forum; also $(...)
is easier to read.
Is this any better?
Andrew
1 Like
jaapar
August 16, 2017, 10:46am
4
Thanks Andrew, learned something new today about backticks. Your modification did work as intended