Monday, June 19, 2006

redlof worm cure

When RedLof worm was wrecking havoc on my files, and NAV was deleting all my data, i wrote a small utility that removes infected portions from infected files...

Unfortunately, i knew only Java at that time, so sorry if this program sucks.. but it does its job perfectly..



/** Cure for HTML.Redlof.A virus
* Copyright (C) Anurag
*/

import java.io.*;
import java.util.*;

public class redlof
{

public static void main(String args[])
{
System.out.println("Virus Repair tool <HTML.Redlof.A>\n");
if (args.length==0)
{
System.out.println("Usage : java redlof [directory]");
System.exit(0);
}
String loc=args[0];
System.out.println("\n\n ****** Initializing Virus Remover ****** ");
System.out.println("Searching : "+loc);
redlof virus=new redlof();
virus.scanFiles(new File(loc),new Vector(),"htm");
virus.scanFiles(new File(loc),new Vector(),"html");
virus.scanFiles(new File(loc),new Vector(),"asp");
}

public void scanFiles(File f, Vector htmlList, String fileExtn)
{
if (f.isDirectory())
{
String[] list = f.list();
if (list != null)
{
for (int i = 0; i < list.length; i++)
{
scanFiles(new File(f, list[i]), htmlList,fileExtn);
}
}
}
else
{
if (f.getName().toLowerCase().endsWith(fileExtn))
{
htmlList.addElement(f.getAbsolutePath());
openfile(f.getAbsolutePath());
}
}
}

void openfile(String filename)
{
System.out.print("Scanning file : "+filename);
String content="";
byte b[];
long nob;
try
{
RandomAccessFile raf=new RandomAccessFile(filename,"rw");
nob=raf.length();
if(nob<11519)
return ;
b=new byte[(int)nob];
System.out.println(" ## Size = "+nob);
raf.seek(0);
raf.read(b);
content=(new String(b));
checkinfected(content,filename);
raf.close();
}
catch(Exception e)
{
}
}

void checkinfected(String src,String filename)
{
int infected=src.indexOf("vbscript:KJ_start()");
if (infected==-1)
{
return;
}
else
{
cure(filename);
}
}

void cure(String filename)
{
System.out.println("Repairing file : "+filename);
byte b[];
long nob;
try
{
RandomAccessFile raf=new RandomAccessFile(filename,"rw");
nob=raf.length();
b=new byte[(int)nob];
raf.setLength(raf.length()-11516);
raf.close();
}
catch(Exception e)
{
}
}
}

Tuesday, May 09, 2006

disk utilization notifications

Long time back, at HBCSE we were thinking what to do about the /home partition of server which was getting filled upto 90% every now and then. We used to call up the user having extremely large home directory and ask him/her to freeup some disk space..

Obviously not many people followed our advice, and I was thinking of writing a shell script that would automatically send overusage notifications, and free us of some headache.. Lol, i ended up writing a Python script finally. :)

This script is invoked from crontab with root's priveleges.


#!/usr/bin/env python

## Script for sending Disk utilization notifications:
# Copyright (C) 2004 Anurag <anurag@gnowledge.org>

import os,re,sys,string
import smtplib
import time

tmpfile='/tmp/disk.stat' # Name of temp file that saves disk stats
mailfile='/tmp/mail.file' # file used to store email message
lowerlimit='100 MB' # Maximum size of home directory
upperlimit='300 MB' # Maximum threshold size of homes
uppersizelimit = 300000 # Upper threshold in KiloBytes
todaysdate=time.ctime()


"""
Function for sending email to users
"""
def sendEmail(username,homesize):
# Composing the email to be sent to users
# This part is mime header
wmsg = 'From: HBCSE Server Admin <root@hbcse.tifr.resDOTin>\n'
wmsg = wmsg+'To: <' + username + '@hbcse.tifr.resDOTin>\n'
wmsg = wmsg+'Reply-To: HBCSE Server Admin <root@hbcse.tifr.resDOTin>\n'
wmsg = wmsg+ 'Subject: Warning: Your HBCSE home size\n'
wmsg = wmsg+ 'Date: '+ todaysdate +'\n'
# This part is the actual message
wmsg = wmsg+ '\n\n\nHello '+ username +',\n\n'
wmsg = wmsg+ 'Currently the size of your home directory on HBCSE server is'+'\n'
wmsg = wmsg+ 'more than the maximum threshold limit of '+ upperlimit +'\n'
wmsg = wmsg+ 'Please reduce the size your home directory on HBCSE server so'+'\n'
wmsg = wmsg+ 'that it can run efficiently.'+'\n\n'
wmsg = wmsg+ 'For clarifications call 108 or root@hbcse.tifr.resDOTin '+'\n\n\n'
wmsg = wmsg+ '-- \nHBCSE Server Admin'+'\n'
# connecting to mail server
try:
s=smtplib.SMTP('localhost')
s.mail('root@hbcse.tifr.resDOTin')
s.rcpt(username + '@hbcse.tifr.res.in')
s.data(wmsg)
except Exception:
pass

"""
Function for finding over quota directories
"""
def findOverQuotas(tmpfilename):
ifile = open(tmpfilename,'r') # open the file containing disk stats
filecontents = ifile.readlines() # read it line by line
for lines in filecontents:
userdetails=[]
userdetails = lines.split() # split the line into "size" and "username" pairs
homedirsize,serveruser = userdetails
homedirsize = string.atoi(userdetails[0])
if (homedirsize > uppersizelimit):
sendEmail(serveruser,homedirsize)

# Start of main routine
os.system('cd /home;du -s * 2>/dev/null > '+tmpfile )
findOverQuotas(tmpfile)

Monday, May 08, 2006

rsync backup script

We learnt a hard lesson (everyone does).. Always backup your data.. Harddisks have a very bad habit of going br0ke when you most need it. I just made a small shell script that performs rsync and maintains a copy of data on another server.

CC4 and Web are hostnames of 2 remote webservers which are to be backed up. To enable seamless copying of data across servers, we use passwordless ssh logins. For this purpose, i generated a ssh-key pair for root user, wherein the private key was passwordless. And made a copy of /root/.ssh/id_dsa.pub on the remote servers as well.

The shell script for actual backup is as follows. Its being invoked via crontab every sunday afternoon.



#!/bin/bash
## Script Backs up /etc/ and /var/ from CC4 and Web

LOG_FILE=/var/log/hbc-rsync.log ## Keeps a copy in /var/log

TMP_LOG_FILE=/tmp/hbc-tmp-rsync.log ## Mails the current session's log
rm $TMP_LOG_FILE

CC4_BACKUP_DIR=/mnt/backup/cc4
WEB_BACKUP_DIR=/mnt/backup/web

CURRENT_DATE=`date`

## Sync /etc/ and /var/ from CC4

echo "Starting Backup of CC4 on : $CURRENT_DATE" >> $TMP_LOG_FILE
rsync -avzlp -e ssh --delete root@cc4:/var/ $CC4_BACKUP_DIR/var/ 2>1 1>>$TMP_LOG_FILE
rsync -avzlp -e ssh --delete root@cc4:/etc/ $CC4_BACKUP_DIR/etc/ 2>1 1>>$TMP_LOG_FILE

## Sync /etc/ and /var/ from Web
CURRENT_DATE=`date`
echo "Starting Backup of Web on : $CURRENT_DATE" >> $TMP_LOG_FILE
rsync -avzlp -e ssh --delete root@web:/var/ $WEB_BACKUP_DIR/var/ 2>1 1>>$TMP_LOG_FILE
rsync -avzlp -e ssh --delete root@web:/etc/ $WEB_BACKUP_DIR/etc/ 2>1 1>>$TMP_LOG_FILE
rsync -avzlp -e ssh --delete root@web:/home/ $WEB_BACKUP_DIR/home/ 2>1 1>>$TMP_LOG_FILE
##
cat $TMP_LOG_FILE >> $LOG_FILE
cat $TMP_LOG_FILE | mail root@localhost -s "CC4 rsync results"

Saturday, April 01, 2006

hello world!

mandatory hello world post.. :)