Raspberry Pi automate certain tasks – script example

2014-03-10 324 words 2 mins read

Now, if you have followed these :

fetchmail

ssmtp

Then you already have a working system for sending and receiving mail. Now, you can set the mda in the fetmailrc to a script which can do few things for you. The script below will get a page and mail it to you, if you have the subject as “get” and send “wake on LAN” to desired PC if you have subject as “wol”. Cool 🙂

Original idea from here.

Here is the script:

#!/bin/bash

expectedFrom=""
expectedFrom2=""
homePC="MAC Here"

mailHelp() {
	sendMail $1 "Help - Possible Commands" "Help"
}

sendMail() {
	echo "To: "$1 > $tmpMail
	echo "From: From address here" >> $tmpMail
	echo "Subject: "$2 >> $tmpMail
	echo "Content-Type: text/html" >> $tmpMail
	echo "" >> $tmpMail
	echo $3 >> $tmpMail
	cat $tempMail >> $tmpMail
	cat $tmpMail|/usr/sbin/ssmtp  $1
}
#here we start the actual processing

rightSender=0
sender=""
tmpFile=/tmp/mailtemp
tmpMail="/var/tmp/mailtxt.txt"
tempMail="/tmp/tosend.txt"
>$tempMail
>$tmpFile
>$tmpMail

#Write the mail to tmpFile
while read line
do
	echo $line >> $tmpFile
done

grep "From:" $tmpFile | grep $expectedFrom > /dev/null
if [ $? -eq 0 ]; then
	rightSender=1
	sender=$expectedFrom
fi

grep "From:" $tmpFile | grep $expectedFrom2 > /dev/null
if [ $? -eq 0 ]; then
	rightSender=1
	sender=$expectedFrom2
fi

if [ $rightSender -eq 1 ]; then
	task=`grep "Subject:" $tmpFile`
	task=${task:9}
	task=`echo $task | tr [:upper:] [:lower:]`

	echo $task | grep "help" > /dev/null
	if [ $? -eq 0 ]; then
		mailHelp $sender
		exit
	fi
fi
while read line
do
	if [[ $line =~ ^$|^Content*:*|^charset=*|^--=* ]]; then
		continue;
	fi
	echo "LINE :: $line"
	case $task in
		get)
			cmd="wget -o /dev/null -O - $line"
		;;
		wol)
			cmd="sudo etherwake $$line"
		;;
		*)
			cmd="$line"
		;;
	esac
	eval $cmd >> $tempMail
done < <( sed '1,/^$/ d' $tmpFile|sed '/^--$/,$ d')
sendMail $sender "Output result of command $task" "Happy Hacking"

rm $tmpFile
rm $tmpMail
rm $tempMail
Enhanced by Zemanta

author

Authored By Amit Agarwal

Amit Agarwal, Linux and Photography are my hobbies.Creative Commons Attribution 4.0 International License.

We notice you're using an adblocker. If you like our webite please keep us running by whitelisting this site in your ad blocker. We’re serving quality, related ads only. Thank you!

I've whitelisted your website.

Not now
This website uses cookies to ensure you get the best experience on our website. Learn more Got it