NSLU2-Linux
view · edit · print · history

changed formatting of program text The DHCP server is a bit too much of a black box.

Here is a mechanism to make it easier to manage/debug.

Prerequisites:

  1. Install Perl -- see BuildPerlOnYourNSLU2Box
  2. Install DateManip -- see http://search.cpan.org/~sbeck/DateManip-5.42a/

Now, add the following script to /opt/etc/init.d

/opt/etc/init.d/S53dhcpweb (chmod +x the script file)

 
#!/bin/sh
if [ -e /opt/bin/leaseholders.cgi ]; then 
	cp -p /opt/bin/leaseholders.cgi \
	/home/httpd/html/leaseholders.cgi
fi
# Last line of /opt/etc/init.d/S53dhcpweb

Add the following script to /opt/bin

/opt/etc/init.d/leaseholders.cgi (chmod +x the script file)

 
#!/opt/bin/perl
#
# script to list active, expired and abandoned leases.
#
# Original script received by Ian Jones, ltjones@hawkeye.ualr.edu
#
# Current Version by Rainer Krienke, krienke@uni-koblenz.de
# Version 1.0
# Added: - output in local timezone
#        - output in HTML  using -w option 
#        - eliminate double entries for same ip address
#
# TL: Rework for nslu2/thttpd cgi script.
#     Rewrite parse to deal with ddns lines.
#	Break out clients & addresses.
#     Install in /opt/bin/leaseholders.txt
#     Add a script to copy to /home/httpd/html/leaseholders.cgi

use Getopt::Std;
use Date::Manip;
use CGI;

# Look for Options
$res=getopts('wh');

# Echo help message 
if( $opt_h || $res =="" ){
	die "$0 [-w]  List active and expired DHCP leases \n",
	    "\tOptions:\n",
	    "\t -w: output is not written in HTML format.\n\n";
}

$abandonedc = 0;
$leasesc = 0;
$expiredc = 0;

# Find local host name -- from IP address if possible.

$ipName = `localhost`;
open(CFG, "/etc/sysconfig/network-scripts/ifcfg-ixp0");
while ($line = <CFG>) {
	next if ( $line =~ /^\s*#/o );
	$mline = $line;
        chomp($mline);
	@wds = split( '=',$mline);
	next if ( $wds[0] ne "IPADDR" );
	$ipAddr = $wds[1];
	@numbers = split(/\./, $ipAddr);
	$ip_number = pack("C4", @numbers);
	($ipName) = (gethostbyaddr($ip_number, 2))[0];
}
close(CFG);
chomp($localhost = $ipName);

#
# Format (see man date) in that the expiration date is echoed.
# Select the format of your choice. If you want the lease time to 
# be printed in amarican style put a comment char ``#'' right in 
# front of the first $outputDateFormat line and remove it from the
# second one.
#
# European Style date
#$outputDateFormat="%H:%M:%S %d.%m.%Y ";

# American style date
$outputDateFormat="%m/%d/%Y %H:%M:%S";

# ### point this to your dhcpd.leases ###
# /etc/dhcpd.leases and /var/state/dhcpd/dhcpd.leases 
# will be seachred by default.
#
$LEASEFILE = "/opt/var/state/dhcp/dhcpd.leases";
if( ! -r $LEASEFILE ){
	if( -r "/etc/dhcpd.leases" ){
		$LEASEFILE="/etc/dhcpd.leases";
	}else{
		die "Cannot find \"dhcpd.leases\" file \n";
	}
}

# ### get universal date from system    ###
#
$xTZ = &ParseDate("now");
$tz=&Date_TimeZone;
$x=Date_ConvTZ($xTZ, $tz, "UTC");

open(LEASES, "$LEASEFILE") or die "Can't open $LEASEFILE";
$inlease = 0;

while ($line = <LEASES>) {
	next if( $line =~ /^\s*#/o );
	$mline = $line;
      chomp($mline);
	$mline=~ s/  / /g;

	@wds = split( ' ',$mline);
	if( !$inlease ) {
		# Look for a lease record
		next if( $wds[0] ne "lease" );
		$ipAddr = $wds[1];
		@numbers = split(/\./, $ipAddr);
		$ip_number = pack("C4", @numbers);
		($ipName) = (gethostbyaddr($ip_number, 2))[0];
		if ($ipName) {
		   ;
		} else {
		   $ipName = "<unknown>";
		}
		$startDt = "<unknown>";
		$endDt = "<unknown>";
		$endNever = 0;
		$ddnsClient = "<unknown>";
		$ethAddr = "<unknown>";
		$hostName = "<unknown>";
		$leaseState = "<unknown>";
		$leaseAbandoned = 0;
		$inlease = 1;
		next;
	}
	# Parse each clause in lease
	if( $wds[0] eq "starts" ) {
		$startDt = join( ' ', $wds[2], $wds[3] );
		$startDt=~s/;\s*$//;
		# Parse Date in Date::Manip internel format
		$startDtUTC=ParseDate($startDt);
		#
		# Convert it to local timezone
		$startDtTZ=Date_ConvTZ($startDtUTC,"UTC", $tz);
		#
		# Finally make a human readable date string out of it
		$startDt=UnixDate($startDtTZ, ($outputDateFormat) ) ;
		next;
	}
	if( $wds[0] eq "ends" ) {
		if( $wds[2] eq "never" ) {
			$endDt = "2999\/01\/01 12:00:00";
			$endNever = 1;
		} else {
			$endDt = join( ' ', $wds[2], $wds[3] );
			$endDt=~s/;\s*$//;
		}
		# Parse Date in Date::Manip internel format
		$endDtUTC=ParseDate($endDt);
		#
		# Convert it to local timezone
		$endDtTZ=Date_ConvTZ($endDtUTC,"UTC", $tz);
		#
		# Finally make a human readable date string out of it
		$endDt=UnixDate($endDtTZ, ($outputDateFormat) ) ;
		next;
	}
	if( $wds[0] eq "hardware" ) {
		$ethAddr = $wds[2];
		$ethAddr=~s/;\s*$//;
		next;
	}
	if( $wds[0] eq "client-hostname" ) {
		$hostName = $wds[1];
		$hostName=~s/;\s*$//;
		$hostName=~ s/"//g;
		next;
	}
	if( $wds[0] eq "binding" ) {
		$leaseState = $wds[2];
		$leaseState=~s/;\s*$//;
		next;
	}
	if( $wds[0] eq "set" ) {
		if( $wds[1] eq "ddns-client-fqdn" ) {
			$ddnsClient = $wds[3];
			$ddnsClient=~s/"//g;
		}
	}
	if( $wds[0] eq "abandoned;" ) {
		$leaseAbandoned = 1;
		next;
	}
	if( $wds[0] ne "}" ) {
		next;
	}

	## End of lease data, generate output

	$inlease = 0;

	if( $ipName eq "<unknown>" ) {
		$ipName = $ddnsClient;
	}

	$endDt = "dyn-bootp: never" if( $endNever );
	$lease = sprintf "%-17s %-15s %-19s %-19s %-25s %s\n",
                         $ethAddr,
                         $ipAddr,
                         $startDt,
                         $endDt,
                         $hostName,
                         $ipName;

	$ClientLeases{$ethAddr} = $lease;
	$ClientLeaseTime{$ethAddr} = $endDtUTC;
	$ClientLeaseState{$ethAddr} = $leaseState;

	if( $leaseAbandoned ) {
		# Unexpectedly found someone with this address
		$AbandonedAddresses[$abandonedc++] = $lease;
		next;
	}

	if( $leaseState eq "active" ) {
		$ActiveLeases{$ipAddr} = $lease;
	} else {
		$ExpiredLease{$ipAddr} = $lease;
	}
}

close(LEASES);

if( !$opt_w ){
	$|=1;
	$q = new CGI;
	print $q->header('text/html');
	print $q->start_html( -title=>"DHCP status on $localhost",
			      -expires=>'+5s',
			      -status=>'200 OK',
			      -BGCOLOR=>'white' );
	print "<PRE>\n";
}

# Sort each hash & return the keys for in-order access

@ClientKeys = sort(keys(%ClientLeases));	# MAC address order
@ActiveKeys = sort(keys(%ActiveLeases));	# IP address order
@ExpiredKeys = sort(keys(%ExpiredLeases));	# IP address order
@abandoned = sort(@abandoned);			# MAC, IP address (?)

$xDate=UnixDate($xTZ, ($outputDateFormat) ) ;
print "DHCP leases issued by $localhost as of $xDate\n";

$actc = 0;
print "\nActive Clients:";
foreach $i  ( @ClientKeys ) {
	next if( $ClientLeaseState{$i} ne "active" );

	if( $actc++ == 0 ) {
		print "\nEthernet Address";
                print "     IP Address";
                print "     Lease Issue Time";
                print "    Expiration Time";
                print "	      Client Hostname";
                print "       DNS Hostname\n";
		print "-----------------";
                print " ---------------";
                print " -------------------";
                print " -------------------";
                print " -------------------------";
                print " --------------------";
                print "---------------------\n";
	}
	print $ClientLeases{$i};
}
if( $actc == 0 ) {
	printf " None\n";
} else {
	printf "Total active clients: %d\n", $actc;
}

$iactc = 0;
print "\nInactive Clients:";
foreach $i  ( @ClientKeys ) {
	next if( $ClientLeaseState{$i} eq "active" );

	if( $iactc++ == 0 ) {
		print "\nEthernet Address";
                print "     IP Address";
                print "     Lease Issue Time";
                print "    Expiration Time";
                print "	      Client Hostname";
                print "       DNS Hostname\n";
		print "-----------------";
                print " ---------------";
                print " -------------------";
                print " -------------------";
                print " -------------------------";
                print " --------------------";
                print "---------------------\n";
	}
	print $ClientLeases{$i};
}
if( $iactc == 0 ) {
	printf " None\n";
} else {
	printf "Total inactive clients: %d\n", $iactc;
}

$actn = 0;
print "\nActive Addresses:";
foreach $i  ( @ActiveKeys ) {
	if( $actn++ == 0 ) {
		print "\nEthernet Address";
                print "     IP Address";
                print "     Lease Issue Time";
                print "    Expiration Time";
                print "	      Client Hostname";
                print "       DNS Hostname\n";
		print "-----------------";
                print " ---------------";
                print " -------------------";
                print " -------------------";
                print " -------------------------";
                print " --------------------";
                print "---------------------\n";
	}
	print $ActiveLeases{$i};
}
if( $actn == 0 ) {
	printf " None\n";
} else {
	printf "Total Active: %d\n", $actn;
}

$expn = 0;
print "\nExpired Leases:";
foreach $i  ( @ExpiredKeys ) {
	@wds = split( ' ', $ExpiredLeases{$i});
	if( !defined($ActiveLeaseTime{$wds[1]}) ) {
		if( $expn++ == 0 ) {
			print "\nEthernet Address";
	                print "     IP Address";
			print "     Lease Issue Time";
			print "    Expiration Time";
			print "	      Client Hostname";
			print "       DNS Hostname\n";
			print "-----------------";
			print " ---------------";
			print " -------------------";
			print " -------------------";
			print " -------------------------";
                        print " --------------------";
                        print "---------------------\n";
		}
		print $ExpiredLeases{$i};
	}
}
if( $expn == 0 ) {
	printf " None\n";
} else {
	printf "Total expired: %d\n", $expn;
}

$abdn = 0;
print "\nAbandoned Addresses:";
foreach $i  ( @abandoned ) {
	if( $abdn++ == 0 ) {
		print "\nEthernet Address";
                print "     IP Address";
                print "     Lease Issue Time";
                print "    Expiration Time";
                print "	      Client Hostname";
                print "       DNS Hostname\n";
		print "-----------------";
                print " ---------------";
                print " -------------------";
                print " -------------------";
                print " -------------------------";
                print " --------------------";
                print "---------------------\n";
	}
	print $i;
}
if( $abdn == 0 ) {
	printf " None\n";
} else {
	printf "Total abandoned: %d\n", $abdn;
}

printf "\n";

if( !$opt_w ){
	print "</PRE>\n";
	$me = $q->url();
	print $q->a({href=>$me},"Refresh");
	print $q->br();
	print $q->a({href=>"/"}, "Home Page");
	print $q->end_html;
}
# Last line of /opt/bin/leaseholders.cgi

you can just copy 'n paste with the changed formatting 'Don't forget to change <beginningofline><space># to <beginningofline>#.'

You will be able to get status from http://yournslu2/leaseholders.cgi(approve sites)

Enjoy

 --tlhackque
view · edit · print · history · Last edited by janne5011.
Based on work by mikey way my chemical romance, ancient greek clothes, anara gupta video clips downloads, zoolove, http, blubb, lux video, love comes slowly movie, quebec financial planner, juggalo music video, license practice tests, demon, jeroen, american bald eagle, links, automotive job description, maine fishing, webmap, splenic abnormality, prescription drug medicine, the brown bunny dvd release, popcap bejeweled 2 deluxe v10 crack, medal of honor no cd key, outcast torrent, email adressen finden, stunning serena movie, Rolf, rift scifi tripping, mousepad maphack 65 crack, tara reid videos, swg fragments of the past, laddie court, fuck it, resale license in california, lauren graham, golf driving tips, multilingual translation, nfl videos, domain, scenalyzerlive crack, geoscouter, novelas univision, altavista crack box, aristocracy nation, after effects serial key, bloodhound gang ringtones, medical plus pro, equipment store video, oriental movie theater milwaukee, nissan titan oem video system diagram, siblings sharing bedroom, lawrence kaminsky, arab clip music video, bollywood ringtones compose, Thomas Reitmayr, alice springs telegraph station, lvl 60 rogue video, sing smurfing song, oye mi canto video download, nokia 2200 ringtones, promo codes, real producer 10 serial, wine racks metal, saint george utah homes, link, polycom video conferencing unit, maryland apartments, travel agents in usa, milf, adult shar pei, oregon station weather, oklahoma betting, psp 20 firmware cracked, movie godfather, pittsburg kansas movie theatre, candi evans, jake simpson oprah, quote on drug addict, roman costumes, ebony free lesbian movie sex, real fight club video, love naruto sakura sasuke story video, cum swapers, index, Daniel, link creativecommonsorg license nc sa 10 fi, screen saver, adipex by paypal, alvin cartoon chipmunk home video, new napster crack, astx813, replenex drug, movie software download, english to italian dictionary translation, excema treatment, refurbished precor treadmills, slugmanbashi, parts for power tools, site, sexual stimulant for women, joseph inga crystal sky, nj state licensed real estate course instructor, designer, okinawa training video, cheats for heli attack 3, adalt friend finder, showtunes ringtones, hip roof, archive thumb video, empire earth cracked, gunbroker, boxing equipment houston, vanessa angel nude, average blood pressure by age, susquehanna mall movies, what is vestibular dysfunction, pc video player, know making music things video when, kid playground safety video, tow cars, pembo, lanview crack, real estate exam license nc school, racketeering, pima justice, illinois malpractice attorneys, efficiency fuel kid video, cute chick ringtone, la audio video western, real estate license exam online, smooth criminal video michael jackson, kalinka ringtone, turn on, kultur tourismus, sears store locator, map, gay daddy, contact center analytics, anneberg foundation, american idle, drunk porn, very young asian lolitas, bjohv052, snow plow equipment, anara gupta video clippings, simpsons intro video, arizona golf peoria properties, la bamba movie script, joanna lumley, nymphomaniac girls, ellipticals true, sitemap, Sil53r Surf3r, neuter, nursing care of infants with respiratory disease, newbury park real estate, spring break movies free, mr potato head, miami lake movie theater, sidhe, mike russell photoshop, nokia 3330 ringtones, nutcracker ballet story, visual sensations for women, memorial florist houston, real estate license louisiana, xeriscape designs, piantball gear, airport car edinburgh hire uk, rotate movie quicktime, chantelle fontain, safety dance music video, contract furniture parts, extreme mountain biking video clips, i klaymation make movie myspacecom site, nejp viagra yybbs yybbscgi, top, t0ny, navy blue shower curtain, mystery novels, yingyangtwins, monster truck crash videos, in the movie the gospel, lock folder xp crack, lil jon ice cube roll call video, broken ankle, energy speakers, aileen wuornos video clips, stamina-rx, the equinox resort spa, elite personnel, password videozcom, serial port definition, lorazepam 1mg tablets, license plate fastener, swap shop movies, canadiantireca, page, incredimail xe premium crack, memphis belle movie, neck anatomy, mtv musicvideoscom, information on metformin, movie review the notebook, belmont club, nero 6608 crack serial, labioplasty, sir frederick banting biography, kentucky medical license board, john gries movies, sites, oss3d crack, ByronT, aspiration food solid, big houses, lesian video, sakis rouvas eurovision video, movie rating triangles, licenced electrician, developing telekinesis, romance 1999 movie, oui girls movie, junior homecoming dress, free casino slot, newsbin pro 432 cracks, iso buster serial number, killing me softly video clip, ibroadcast video streams, queen of the damned music videos, fcarolo, marley station mall movies, replace video card in laptop, irc spy torrent, lindsay lohan flash video, erd 2003 crack, the telegraph calcutta india, nobodelb, ashrae standard 901 2001, online xxx dvd, lidomlieltg, tman, Lex Delani, and tlhackque.
Originally by tlhackque.
Page last modified on November 23, 2008, at 09:06 AM