Saturday, July 2, 2016

Using Python and Bash Scripts and sSMTP to Notify You by E-mail When a New Issue of 2600: The Hacker Quarterly Is Released

I wrote this python script to get notified when a new issue of 2600: The Hacker Quarterly is released:


#!/usr/bin/python
import re
import feedparser
url = 'http://www.2600.com/rss.xml'
f = "log.txt"
d = feedparser.parse(url)
fh = open(f, 'r+')
line = fh.readline()
if line != d['entries'][0]['link']:
        if re.match(r'(WINTER|SPRING|SUMMER|AUTUMN).*', d['entries'][0]['title']):
                print d['entries'][0]['title'] + " " + d['entries'][0]['link'] + "\r\n"
fh.seek(0)
fh.write(d['entries'][0]['link'] + "\r\n")
fh.truncate()
fh.close()


And here is the Bash Shell script to take the output from stdout and use it as the subject for an e-mail:


#!/bin/bash
#
# Executes the script given as argument #2,
# then if there is anything printed to stdout,
# it will email the text as the body of the email
#
# © Michael Craze -- http://projectcraze.us.to

if [ "$#" -ne 2 ] ; then
        echo "Usage: $0  <2600_script>"
        exit
fi

EMAIL="your_email@domain.com"
SUBJECT=$1
CLSCRIPT=$2
PY=`which python`
MAIL=`which mail`
BODY=`$PY $CLSCRIPT`

# send email if something was posted today
if [ -n "$BODY" ] ; then
        echo $BODY | $MAIL -s $SUBJECT $EMAIL
fi


Here is the crontab (crontab -e) entry I use to run it once daily:


30 8 * * * /bin/bash /home/mike/code/2600_notifier/2600-mail.sh New_2600 /home/mike/code/2600_notifier/2600_notifier.py


This will only work if you have your MTA setup correctly. I use a package called ssmtp (sudo apt-get install ssmtp), and set it up to use my gmail account to send mail, here is my ssmtp.conf:


# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
#root=postmaster
root=your_email@gmail.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
#mailhub=mail
mailhub=smtp.gmail.com:587

AuthUser=your_email@gmail.com
AuthPass=your_password
UseTLS=YES
UseSTARTTLS=YES

# Where will the mail seem to come from?
#rewriteDomain=
rewriteDomain=gmail.com

# The full hostname
#hostname=MyMediaServer.home
hostname=your_email@gmail.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES

No comments:

Post a Comment