Archive

Posts Tagged ‘Linux’

Parse error log and send email

November 4th, 2008

This post gives an example of how I wrote a script that parsed an error log looking for ‘Traceback’ errors and emailing them to the admin on a daily basis. The cool thing about this script is that it keeps a byte track of each time it reads the log file, stores that byte count in a temp file then picks up at the byte count the next day so you don’t get duplicate emails from tracebacks on a previous day…

let’s call this file tracebacks.py

#!/usr/bin/python
import os
import sys
import time
import smtplib
import socket #required to get host name
from email.mime.text import MIMEText #need this for subject line in email

def main():
	line=""
	line_num=0
	last_byte_read=""
	byte_num=""
	stored_byte_num=""
	traceback_count=0

	log_file=open("/var/log/loadscript/<logfilename here>","r")
	tmp_file="/tmp/loadscript.tmp"

	###############################
	#check if required file exists
	###############################
	if os.path.exists(tmp_file):
		writefile = open(tmp_file,'r')
		stored_byte_num=writefile.read()
	else:
		writefile = open(tmp_file,'w')
		writefile.write("")
		writefile.close()

	writefile = open(tmp_file,'r')			 

	################################
	# find last byte searched in file
	################################
	if len(stored_byte_num)>0:
		stored_byte_num=int(stored_byte_num)
		log_file.seek(stored_byte_num)

	data = log_file.readlines()
	was_found=False

	#loop through file
	for x in data:
		#print x.strip()
		line_num=line_num + 1
		if x.startswith('Traceback'):
			traceback_count += 1
			line += "\n+++++++++++++++++++++++++++++++++++++++"
			#########################################################"
			line += "\nError on Line: %s\n" % line_num
			line += "\n"+x
			was_found=True
		if was_found:
			if x.find('File')==2:
				line += x
		else:
			was_found = False

	# record last byte read in tmp file
	last_byte_read=log_file.tell()
	last_byte_read=str(last_byte_read)
	handle=open(tmp_file,'w')
	handle.write(last_byte_read)
	handle.close()

	#print last_byte_read

	#send mail summary
	if was_found==False:
		mail_message = "\nDid not find any Tracebacks!\n"
	else:
		mail_message = "SCRIPT SUMMARY\n"
	       	mail_message += "================================================\n"
		mail_message += "Tracebacks found: %s\n" % traceback_count
		mail_message += "Last byte checked: %s\n" % last_byte_read
		mail_message += "Script will start at this number next search!\n"
       		mail_message += "================================================\n"
		mail_message += line

		send_mail(mail_message)

        print "Errors found and sent to pse-admin"
        #print "%s" % mail_message

def send_mail(mail_message):

	smtpserver='smtp.example.com'
	host = socket.gethostname()

	RECIPIENTS = ['username@domain.com']
	SENDER = ‘root@%s.mascorp.com’ % host
	MESSAGE = “”"Subject: [Nagios] Loadscript Errors
From: nagios@%s.mascorp.com

%s
“”" % (host, mail_message)

	session = smtplib.SMTP(smtpserver)
	smtpresult = session.sendmail(SENDER, RECIPIENTS, MESSAGE)

	session.close()

try:
	main()

except:
        health = ‘UNKNOWN’
        result = 3
        print “Error: Check script”
        sys.exit(1)

Python ,

Nagios Monitoring w/Ubuntu

November 4th, 2008

Will be updated soon…

Linux , ,

Setting up cron jobs

November 4th, 2008

Need to setup a script to run at a specified time every day, week or month. Use cron!

While logged into linux you can view your crontab file by typing the following

$crontab -l

# m h  dom mon dow   command
35 15 * * *    python /home/jesterj/fogbugz_sql_backup.py

Notice the time parameters followed by the system command. The format is follows…

#min | hour  | day month | month | day of week
10 12 * * *  <command here>

The above script would execute at 12:10pm every day.

To edit this file issue the command with an -e option

$crontab -e

To run a command with sudo priviledges, simply issue a ’sudo’ before the cron command like so.

$sudo crontab -e

That’s it!

Uncategorized , ,

SSH logins using Keys (not passwords!)

November 4th, 2008

CREATE KEY ON CLIENT

jesterj@jesterj-laptop:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/jesterj/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/jesterj/.ssh/id_rsa.
Your public key has been saved in /home/jesterj/.ssh/id_rsa.pub.
The key fingerprint is:
b3:82:51:f6:14:71:d1:48:bf:26:65:60:50:3e:a3:44 jesterj@jesterj-laptop
The key’s randomart image is:
+–[ RSA 2048]—-+
|        E=B+     |
|       . =.o.    |
|      o o + +    |
|     o + . = .   |
|    .   S . o    |
|     o   o o     |
|    . . .        |
|       .         |
|                 |
+—————–+

COPY PUB KEY TO SERVER

jesterj@jesterj-laptop:$ scp ~/.ssh/id_rsa.pub jesterj@donkey.dnsdojo.com:/home/jesterj/

ON REMOTE SERVER, ADD PUB KEY TO AUTHORIZED KEYS

root@donkey:~# cat id_rsa.pub >> .ssh/authorized_keys
root@donkey:~# tail .ssh/authorized_keys
….
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAsW9ypBuq/Xj1c6HNp8m45H8Kc3ZkZQanP3QLQWGDFLpdtnUCWfAe4dzQBL+ZaMjX7WRX/9i/YUCxB+589tRRXBLqoQ4OxaqUugdgfa2iBSDo9wMuGqfWhTcVKu0gTpKnocdQQKB2W7KjvEpJYjz4LFMwWvRnpAcy0Pmmd9KP9X9LDfRyLCjn8qYBzZ69eoJgQc8zA7gD6Cj0nGiQNlFo3yKvonyZEFO/hXja3SIM4XttYG+CLHCR2q1Itstdw9K8ZjhCXyxUl0K78AysT1nzZ5DRLoPb4GZ27oHcGQuS2127UEiMYUszDZRluXTZik679BZQlhZyGQdtEZMw/jt11Q== jesterj@jesterj-laptop

TEST FROM CLIENT

jesterj@jesterj-laptop:~/.ssh$ ssh jesterj@donkey.dnsdojo.com
Linux donkey.dnsdojo.com 2.6.28-17-generic #58-Ubuntu SMP Tue Dec 1 18:57:07 UTC 2009 i686

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/

Last login: Tue Jan 12 14:31:21 2010 from 206-169-197-253.static.twtelecom.net
jesterj@donkey:~$

SUCCESS!

Linux ,