#!/usr/bin/env python
# macparser.py -	parses an input file for MAC-addresses and 
# 					calls iptables to block them
#					NOTE: You must replace the print statement
#					with the following system_command to do anything 
#					useful. Only do this when you are sure it works
#					properly!
# Author: Andreas R. Fugl 2006

import fileinput,re,sys,commands,os,string

MACLIST = "input.txt"
LOG_OUTPUT = "log.txt"
IPTABLES = "/sbin/iptables"

# Wrapper function for commands
def system_command( string_command ):
	return_value = [ ]
	return_value = ( commands.getstatusoutput( string_command ) )
	if not return_value[ 0 ] == 0:
		raise IOError( return_value[ 1 ] )
	return return_value[ 1 ]

# main parser 
def parse():
	linecount = 0
	maccount = 0
	logfile = file(LOG_OUTPUT, "a") #append to logfile
	logstr = ""

	for line in fileinput.input([MACLIST]):
		mac = line.strip('\n') #remove newline char
		if len(mac) == 17:
			print IPTABLES + " -A INPUT --mac-source " + mac  + " -j DROP"
			#system_command(IPTABLES + " -A INPUT --mac-source " + mac  + " -j DROP")

			logstr = "Blocking " + mac + '\n'
			logfile.write(logstr)
			logfile.flush()
			print logstr
			maccount += 1
		else:
			logstr = "Bad input: '%s'" %mac
			logfile.write(logstr)
			logfile.flush()
			print logstr
		linecount += 1

	print "%i lines processed" %linecount
	print "%i lines MAC-addresses" %maccount

if __name__ == "__main__":
	parse()
