Showing posts with label cron. Show all posts
Showing posts with label cron. Show all posts

Thursday, May 15, 2014

ssmtp to email cron output

Cron output in Ubuntu gets discarded. The default install of Ubuntu does not install a Mail Transport Agent (MTA), so cron cannot mail you the output.

You can install an MTA -several are easily available in the Ubuntu repositories- but configuration is not trivial. MTAs date from before the IMAP- and SMTP-based e-mail systems we use today, which makes them highly flexible and configurable...but not necessarily the easiest solution.

ssmtp is a limited-purpose MTA intended to replace the 'mail' command and send all output to an SMTP mailserver. ssmtp is provided by the 'ssmtp' package.

Install


sudo apt-get install ssmtp

Configuration file #1: /etc/ssmtp/ssmpt.conf

This tells ssmtp how to send email to my account.
It's not the best idea to store your e-mail password in world-readable plain text. See how to protect the password properly.

# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=me@example.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=my_mail_server.net:465
AuthUser=me@example.com
AuthPass=my_email_password
UseTLS=Yes

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

# The full hostname
hostname=hey_its_my_computer

# 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


Configuration File #2: /etc/ssmtp/

This directs root mail to my account.

# sSMTP aliases
#
# Format:       local_account:outgoing_address:mailhub
#
# Example: root:your_login@your.domain:mailhub.your.domain[:port]
# where [:port] is an optional port number that defaults to 25.
root:me@example.com:my_mail_server.net:465



And now cron output lands in my normal inbox.

Sunday, June 28, 2009

Xubuntu desktop wallpaper from a website (NOAA Radar)

This post has been superseded by a newer post. Much of this information is still valid, but the newer post has more detail amd examples, and includes more services.



Living in the midwest, I check the weather radar a lot to protect my laundry drying outside from lots of pesky thunderstorms. So I want to make the radar image my desktop picture in Xubuntu, and to have it automatically update.

To get the image: I'm using http://radar.weather.gov/lite/N0R/MKX_0.png. It is from the United States National Weather Service and updates every 5-6 minutes.

A shell script to refresh the radar image as the desktop picture:

#!/bin/sh
# BEGIN CONFIGURATION
# This is the path of the final output files that get read by other processes.
# Working files show up here, too. You may wish to create your own directory.
Local_Path=/home/me/.config/weather/
Local_Name="${Local_Path}radar_image.png"
Username=<your username>

# This is the closest weather station for observations. Find your weather 
# station: http://www.nws.noaa.gov/xml/current_obs/. Format is four letters. 
# All UPPER CASE. For example, 'KMKE' for Mitchell Field in Milwaukee, WI
Station=KMKE

# This is the closest weather radar. Find your radar: http://radar.weather.gov/
# Check the link to your weather radar, for example:
# http://radar.weather.gov/ridge/radar.php?rid=mkx&product=N0R&overlay=11101111&loop=no
# The radar name is in the 'rid=' field. In this example, mkx is Milwaukee, WI
# Format is UPPER CASE. For example, 'MKX' for Milwaukee.
Radar_Name=MKX
Radar_Url="http://radar.weather.gov/lite/N0R/${Radar_Name}_0.png"

# (OPTIONAL) The height of your top menu bar, in pixels.
# The radar image is padded by this amount on the top edge so the menu doesn't
# block the timestamp in the image.
#Radar_Image_Top_Padding=15
# END CONFIGURATION

# BEGIN RADAR IMAGE
# Download the radar image.
echo "Weather Update: Downloading the most recent radar image available..."
curl -o $Local_Name $Radar_Url

# (OPTIONAL) Use imagemagick to pad the image top so the timestamp is not 
# blocked by the menu bar.
#convert $Local_Name -background none -splice 0x${Radar_Image_Top_Padding} $Local_Name

# Refresh desktop background with 'xfdesktop -reload'. NOTE - some versions 
# of XFCE flicker all the icons brighter when this occurs, providing visual 
# feedback that the refresh occurred. An Alternate method to avoid the 
# flicker is below.
# The 'DISPLAY=:0.0' prefix is required so root processes like cron and 
# Upstart can process it.
# The 'sudo -u $Username' is required because a root process (like an Upstart 
# trigger) may be trying to change a user's desktop. Sudo changes the command 
# to run as user instead of root. Use your username, of course.
DISPLAY=:0.0 sudo -u $Username xfconf-query -v -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s $Local_Name
DISPLAY=:0.0 sudo -u $Username xfdesktop -reload

# Alternate method to avoid the flicker by changing desktop pictures for 
# just a moment, then changing it back.
#DISPLAY=:0.0 sudo -u $Username xfconf-query -v -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s /usr/share/xfce4/backdrops/xfce4logo.png
#DISPLAY=:0.0 sudo -u $Username xfconf-query -v -c xfce4-desktop -p /backdrop/screen0/monitor0/image-path -s $Local_Name

# END RADAR IMAGE
I'll save this script as radar_background.sh, and make it executable with sudo chmod +x radar_background.sh.

Notes:
  1. The DISPLAY=:0.0 element is explained here.
  2. The xfconf-query command, and how to change the background using DBus, are discussed in the XFCE forums

Updating the desktop picture manually:

Since we have it in a shell script already, we can create a .bashrc alias to run the script manually.
nano .bashrc opens the .bashrc for editing.
Add the line alias radar='/home/me/radar_background.sh' to the bottom of the file and save it.
Open a new terminal window (terminals only read the .bashrc upon starting) and try the command radar.



Updating the desktop picture automatically: Since we can update the desktop image using bash commands, let's make a crontab entry to update the desktop image automatically. Here's what it looks like - a crontab entry with just the shell command:

# m h  dom mon dow   command
*/20 * * * * /home/me/radar_background.sh
Note that the desktop picture will refresh every 20 minutes.

Explaining the cron instructions:

# m h dom mon dow command - That's just part of the crontab

*/20 * * * * - tells the machine to run the script every 20 minutes. */5 * * * * will run the script every five minutes.

> /dev/null at the end (optional) - tells the machine to not e-mail me every time the script runs.

Make sure the command is all on one line (not wrapped), or you'll get crontab errors.

Friday, January 23, 2009

Moving Cron jobs to Anacron

Cron is a great way to run recurring jobs. But some jobs need to run weekly...and sometimes the computer is turned off, so the cron job doesn't run. So I'm going to migrate some jobs to anacron. Cron runs once each minute, checking if the time matches anything in the crontab list. Anacron, however, runs once each hour (triggered by cron, restart, or resume) and checks the interval in days since a job was last run.

Tips

  • Anacron is a root/sudo-level command. Running it as a user will silently FAIL.
  • Anacron will silently FAIL to run scripts with periods '.' in the filename.
  • Anacron stores the timestamps of each job's last run in /var/spool/anacron/JOBNAME. This is handy to change while testing.

There are two ways to run a command using anacron. You can place the command directly in the anacrontab (/etc/anacrontab), or you can put a script in one of the periodic folders (/etc/cron.daily, /etc/cron.weekly, or /etc/cron.monthly)Here are some examples:

  • For comparison, here's an example cron.daily entry that runs at 07:25 each morning:
    # min hr dom mon dow   command
    25 07 * * * date > /home/YOUR_USERNAME/.cron/test_file_1
  • This /etc/anacrontab entry runs each time anacron is called (days = 0), which is very useful for testing. Start anacron manually with sudo anacron -d.
    #days delay  jobname   command
    0 0 anacron-test2  date > /tmp/crontab-test-ouput-everytime
  • This /etc/anacrontab entry runs once daily (days = 1), no matter how many times anacron is called automatically or manually.
    #days delay  jobname   command
    1 0 anacron-test3  date >> /tmp/crontab-test-output-daily

Saturday, September 20, 2008

Cron to be deprecated in favor of Upstart in Ubuntu

Ubuntu's Upstart is an init daemon replacement, quite analagous to OS X's launchd. Launchd also replaced cron on OS X - and upstart plans to replace cron on Ubuntu. No telling when, but all my cron jobs will need to be reformatted.

Update: Sept 2011. Three years later and still waiting...

Wednesday, September 17, 2008

Recurring jobs, launchctl, plist, and shell scripting on OSX

OSX is Unix - similar, and yet dissimilar to linux. I'm setting up a few recurring maintenance scripts

First of all, cron is deprecated in favor of launchd, which handles a lot more than just cron jobs.

First, recurring jobs are located in /Users/username/Library/LaunchAgent/ as .plist files.

Sample syntax of a .plist file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http:// www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.thisismytask</string>
   <key>LowPriorityIO</key>
   <true/>
   <key>Nice</key>
   <integer>1</integer>
   <key>ProgramArguments</key>
   <array>
      <string>/Users/username/thisismytask.sh</string>
   </array>
   <key>StartInterval</key>
   <integer>3600</integer>
</dict>
</plist>


Alternative interval for daily
   <key>StartCalendarInterval</key>
   <dict>
      <key>Minute</key>
      <integer>0</integer>
      <key>Hour</key>
      <integer>5</integer>
   </dict>


Activate the job using the command launchctl load /Users/username/Library/LaunchAgents/plistname.plist

Deactivate the job the same way (except use unload)

Tuesday, September 9, 2008

Replacing update-notifier with a cron script in Xubuntu

Update-notifier does a lot of good things. It shows you when a package manager is working in the background, it automates security updates, it caused updates to be downloaded in the background, and it provides a convenient icon to click on and launch update-manager. Good stuff.

But it's daemon eats an annoying trickle of ram and resources.

I have it set to update weekly, so the rest of the time it's just eye candy. Much of it's power is wasted on my scheduled update cycle. Time to find a replacement with less overhead.

The simple solution: Really, all I need is to run update-manager weekly. So add the following to your user crontab (crontab -e):

#Reminder bot - this e-mail replaces the update-notifier package
# nail must be instaled, it is part of the heirloom-mailx package
40 7 * * sun /usr/bin/nail -s "Reminder Bot: Run Update-Manager" me@example.com >/dev/null
or instead of using nail (to e-mail the notice), I can simply use zenity to create a pop-up:
#Reminder bot - this e-mail replaces the update-notifier package
40 7 * * sun DISPLAY=:0.0 /usr/bin/zenity --info --title "Reminder!" --text "It's time to run Update-Manager"
or zenity can also create a notification-area icon:
#Reminder bot - this e-mail replaces the update-notifier package
40 7 * * sun DISPLAY=:0.0 /usr/bin/zenity --notification --text "Reminder: It's time to run Update-Manager"

and I'll get a reminder e-mail every Sunday morning at 7:40 am...if I'm awake. Then I launch update-manager from the menu or command line...if I want.


The lazy solution: The simple solution has a drawback - none of the packages are downloaded yet, so the update might take a while (zzzzz). An additional cron entry, though, will have everything downloaded and ready.

Edit the root crontab: sudo mousepad /etc/crontab

Add the line 42 6 * * sun root apt-get update && apt-get autoclean && \apt-get -q -d -y -u upgrade (source)

This will download the updated and upgraded packages on Sunday mornings about an hour before the reminder e-mail, plenty of time.


In theory we could try 42 6 * * sun root apt-get update && apt-get autoclean && \apt-get -q -d -y -u upgrade && /usr/bin/nail -s "Reminder Bot: Run Update-Manager" me@example.com and have it all in one place, but I'll find that confusing in another 6 months.


Removing update-notifier and update-notifier-common: Nothing depends on the package in Xubuntu 8.04, so a simple sudo apt-get remove update-notifier update-notifier-common gets rid of the packages, freeing up a whopping 426kb of disk space.


I find I don't miss the old notifier at all.

Friday, August 22, 2008

Opening a terminal window using cron

Fast experiment to use cron to open a terminal window and execute a command. Success!

The crontab item is:

* * * * * DISPLAY=:0.0 /usr/bin/xfce4-terminal -x top
     # * * * * *               - the crontab time codes. Substitute your own.
     # DISPLAY=:0.0            - sends the subsequent commands to the screen
     # /usr/bin/xfce4-terminal - the application (opens a terminal window)
     # -x top                  - execute the top command in the application
Once a minute, a new terminal window spawns running 'top', just as intended.

Sunday, June 1, 2008

Sending e-mail from the command line

I want to send automatic e-mail as a cron job from my Xubuntu 8.04 laptop. Originally, I tried routing it through the legacy mail spools - it is, after all, on the same laptop as my e-mail - but gave up in despair. Thanks to Ubuntu Forums for the info.

  1. sudo apt-get install ssmtp heirloom-mailx
    or install ssmtp and nail using Synaptic.
  2. sudo mousepad /etc/ssmtp/ssmtp.conf to edit the ssmtp config file. Modify or add the following lines to the config file:
    mailhub=mail.mymailserver.com
    AuthUser=me@mymailserver.com
    AuthPass=my_mail_password
    
    The nail config file does not need to be changed at all.
  3. Using the nail command to send e-mail:
    Tip: Pay close attention to the <RETURN>s and <CTRL+D>s
    First line: nail recipient@address.com<RETURN>
    Second line: Subject: subject<RETURN>
    Third line: E-mail body text<CTRL+D>

    Example:
    nail me@virusmagnet.com
    Subject: Lotta viruses coming into this account
    I need to stop responding to the spam.
  4. Generating e-mail as part of a script or cron job:

    Script nail -s "Test 3" recipient@email.com < /tmp/test_email will send the following e-mail.
    From: You (automatic)
    To: recipient@email.com
    Subject: Test 3
    Message Body: (read from file /tmp/test_email)


    nail -s "Test 3" recipient@email.com < /dev/null will send an e-mail with a blank body - good for quick reminders using the subject line only.

    To generate e-mail from cron events, use the command crontab -e to edit your crontab file:

    26 21 * * * nail -s "Test 3" recipient@email.com < /tmp/test_email

    This crontab entry will send the same "Test 3" e-mail every day at 9:26 p.m.

Many elements can be added or customized - this is simple enough to generate automatic e-mails to myself.

UPDATE: September 9, 2008: I could do this in evolution, but it's more fun to use cron and nail or zenity
This crontab entry:

0 6 28 * * /usr/bin/nail -s "Reminder bot: Pay The Store Rent!" me@example.com </dev/null

will send the following e-mail at 6:00 am on the 28th of each month,

From:    me <my computer>
To:      me@example.com
Subject: Reminder bot: Pay The Store Rent!
Date:    Thu, 28 Jul 2008 06:00:01 -0500 
Text:    None
So I won't forget to pay the rent.... It's important.
This sends an e-mail to a known (to nail) e-mail server, so all machines that check the account get the mail.
Alternately, if I want a a pop-up window:

0 6 28 * * DISPLAY=:0.0 /usr/bin/zenity --info --title "Reminder Bot" --text "Pay The Store Rent"

will give me a pop-up window instead, and

0 6 28 * * DISPLAY=:0.0 /usr/bin/zenity --notification --text "Reminder Bot: Pay The Store Rent"

will give me a tiny notification-area icon.