Ban email first thing in the morning

I noticed that when I check my email first thing in the morning, I spend the day putting out small fires instead of doing good work. I wrote a quick script that bans my email after about 7 hours of idle activity and then restores it sometime between the first 45-75 minutes of activity.

  1. Install xprintidle: sudo apt-get install xprintidle
  2. Paste this script somewhere on your system and make it executable.
  3. Add it to root’s crontab (sudo crontab -e):
    53 * * * * /home/abarry/scripts/banEmailCronjob
    
#!/bin/bash

# this should be run as a cron job (as root)
#
# sudo crontab -e
#   53 * * * * /home/abarry/scripts/banEmailCronjob
#
# the idea is that within an hour of the user returning, the job
# will run and email will be restored, but just as you sit down,
# email will be banned.
#
# DEPENDS on xprintidle which is in apt.

set -x # tells bash to print everything it's about to run

PATH=/home/abarry/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin
PATH=$PATH:/usr/bin:/sbin:/bin

HOME=/home/abarry

DISPLAY=:0.0




# first get the idle time



IDLE=`DISPLAY=:0.0 xprintidle`
echo "Idle amount: " $IDLE
echo "Sleeping for a while..."

sleep 1727 # sleep for a while so email will never be active right as you sit down



# get the IPs of gmail
ADDRESSES=`dig +short A gmail.com`
FIRSTIP=`dig +short A gmail.com | head -n 1`

# dig seems unreliable
IPV6ADRESSES=`dig +short AAAA gmail.com`
IPV6ADRESSES="$IPV6ADRESSES 2607:f8b0:4009:802::1015 2607:f8b0:4009:802::1016"

#IPV6ADRESSES="2607:f8b0:4009::/48"

if [ $IDLE -gt "25200000" ]
then
    echo "Idle is greater than threshold, banning email..."
    # ban email here

    # check to see if it is already banned
    HOSTS=`iptables -L -v -n | grep "$FIRSTIP"`
    echo "$HOSTS"
    if [ -z "$HOSTS" ]
    then
        # not already banned, so ban it

        # ban gmail's IPs
        # find these IPs using $ dig mail.google.com
        echo "banning via iptables"

        # loop through the IPs and ban them
        for thisip in ${ADDRESSES}; do
            iptables -A INPUT -s $thisip -j DROP
        done

        # loop through IPv6 aadresses
        echo "banning via ip6tables"
        for thisip in ${IPV6ADRESSES}; do
            ip6tables -A INPUT -s $thisip -j DROP
        done

        echo "banned!"
    fi

else
    echo "Idle is less than threshold, so removing ban on email..."
    # remove ban here

    echo "removing iptables ban"
    # unban IPs
    #for thisip in ${ADDRESSES}; do
    #    iptables -D INPUT -s $thisip -j DROP
    #done
    iptables -F

    echo "removing IPv6 ban"
    #for thisip in ${IPV6ADRESSES}; do
    #    echo "ip6tables -D INPUT -s $thisip -j DROP"
    #    ip6tables -D INPUT -s $thisip -j DROP
    #done
    ip6tables -F


fi