Main bulk of script unashamedly ripped from
An Ajax-Enhanced Web-Based Ethernet Analyzer
Main Ruby script
dns-watcher.rb
------------------------------------------------------------
#! /usr/bin/ruby -w
# following packages required on ubuntu
# apt-get install rubygems
# gem install net-dns - no longer works as version updated to 0.6 use 0.5.2 from http://rubyforge.org/frs/?group_id=721&release_id=35799
# apt-get install libpcap-ruby*
require 'rubygems'
require 'net/dns/resolver'
require 'syslog'
require 'pcap'
require 'net/dns/packet'
capture = Pcap::Capture.open_live( 'bond0', 1500 )
capture.setfilter( 'udp port 53' )
# NUMPACKETS = 5000
puts "#{Time.now} - BEGIN run."
$log = Syslog.open('dns_logging', Syslog::LOG_PID, Syslog::LOG_LOCAL1)
capture.loop do |packet|
dns_data = Net::DNS::Packet.parse(packet.udp_data)
dns_header = dns_data.header
if dns_header.query? then
print "Device #{packet.ip_src} "
print "(to #{packet.ip_dst}) "
print "at #{Time.now} looking for "
question = dns_data.question
question.inspect =~ /^\[(.+)\s+IN/
puts $1
if $1 != nil
$log.info("dns queried for " + $1)
end
STDOUT.flush
end
end
capture.close
puts "#{Time.now} - END run."
---------------------------------------------------------------
Bash wrapper to start the script
dns-watcher
---------------------------------------------------------------
/bin/bash
case $1 in
start)
echo $$ > /var/run/dns-watcher.pid;
exec 2>&1 ruby /home/dns/dns-watcher.rb 1>/tmp/dns-watcher.out
;;
stop)
kill `cat /var/run/dns-watcher.pid` ;;
*)
echo "usage: dns-watcher {start|stop}" ;;
esac
exit 0
------------------------------------------------------------
Script can be started with
dns-watcher start &
and stopped with
dns-watcher stop &
Sometimes the script unexpected and my lack of coding skills stop me from understanding why so I use Monit to monitor the process and restart it if need be.
Monit config - follow normal rules for getting Monit to work and then add the lines below specifically for the dns-watcher script
--------------------------------------------------------------
# Monitor Ruby process for dns-watcher
check process dns-watcher with pidfile /var/run/dns-watcher.pid
start program = "/home/dns/dns-watcher start &"
stop program = "/home/dns/dns-watcher stop &"
---------------------------------------------------------------
Can use something like phpLogCon to monitor syslog output