|
| 1 | +#!/usr/bin/python3.3 |
| 2 | +# |
| 3 | +# link-checker.py |
| 4 | +# Script to be run by crontab to report broken links. |
| 5 | +# |
| 6 | +# Builds upon linkchecker (Ubuntu: sudo apt-get install linkchecker) |
| 7 | +# to hide warnings and to send a concise email if bad links are found. |
| 8 | +# |
| 9 | +# Brandon Amos <http://bamos.io> |
| 10 | +# 2014.02.06 |
| 11 | + |
| 12 | +from subprocess import Popen,PIPE |
| 13 | + |
| 14 | +from email.mime.multipart import MIMEMultipart |
| 15 | +from email.mime.text import MIMEText |
| 16 | +import smtplib |
| 17 | + |
| 18 | +# Settings to send emails with SMTP with gmail. |
| 19 | +server = "smtp.gmail.com" |
| 20 | +port = 587 |
| 21 | +user = ENTER_USER |
| 22 | +pw = ENTER_PW # Please use an application-specific password for security! |
| 23 | +email_to = ENTER_TO_EMAIL |
| 24 | +email_from = ENTER_FROM_EMAIL |
| 25 | +url = ENTER_URL |
| 26 | + |
| 27 | +cmd = ["linkchecker", "--no-warnings", "--no-status", url] |
| 28 | +output = Popen(cmd, stdout=PIPE).communicate()[0].decode("UTF-8") |
| 29 | + |
| 30 | +bad_urls = [] |
| 31 | +for line in output.splitlines(): |
| 32 | + if line.startswith("URL"): current_url = line |
| 33 | + if line.startswith("Parent URL"): parent_url = line |
| 34 | + elif line.startswith("Result"): |
| 35 | + current_result = line |
| 36 | + toks = line.split() |
| 37 | + if toks[1] != "Valid:": |
| 38 | + bad_urls.append((current_url, parent_url, current_result)) |
| 39 | + |
| 40 | +if bad_urls: |
| 41 | + message_contents = "Error checking links for " + url + "\n\n" |
| 42 | + for url in bad_urls: |
| 43 | + message_contents += "\n".join(url)+"\n\n" |
| 44 | + |
| 45 | + server = smtplib.SMTP(server, port) |
| 46 | + server.ehlo_or_helo_if_needed() |
| 47 | + server.starttls() |
| 48 | + server.login(user, pw) |
| 49 | + |
| 50 | + multi_msg = MIMEMultipart() |
| 51 | + multi_msg['From'] = email_to |
| 52 | + multi_msg['To'] = email_from |
| 53 | + multi_msg['Subject'] = "Bad links on " + url + "." |
| 54 | + multi_msg.attach(MIMEText(message_contents)) |
| 55 | + server.sendmail(email_to, email_from, multi_msg.as_string()) |
| 56 | + |
| 57 | + server.close() |
0 commit comments