Poll: Your Favorite Scripting Language?

Posted on in Categories Ask nixCraft, C Programming, Linux, Perl, php, Poll, programming, python, Shell scripting, Sys admin, UNIX last updated March 17, 2009

Like most sys admin, I’m lazy. I try to automate almost all things in order to save time. Inexperienced sys admin and help desk staff working under me finds all these tools useful. It saves their time and avoids security issues. Automation allows help desk staff to do things that they don’t have enough direct system knowledge to do themselves. However, selecting correct tool and applying correct methodology is very important.

Note: There is a poll embedded within this post, please visit the site to participate in this post’s poll.

Display IP Address Allocation Table According to Subnet Mask

Posted on in Categories Howto, Linux, Networking, Perl last updated March 8, 2008

If you need a tabular representation of relationships and source of the various variables representing a chunk from /32 to /0 subnets use iptab command. This is useful if you are allocating IPs to end users. Following information is displayed with the command:
=> CIDR notation

=> Network Mask

=> Available Networks

=> Available Hosts per network

=> Total usable hosts

$ iptab
Sample output:

+----------------------------------------------+
| addrs   bits   pref   class  mask            |
+----------------------------------------------+
|     1      0    /32          255.255.255.255 |
|     2      1    /31          255.255.255.254 |
|     4      2    /30          255.255.255.252 |
|     8      3    /29          255.255.255.248 |
|    16      4    /28          255.255.255.240 |
|    32      5    /27          255.255.255.224 |
|    64      6    /26          255.255.255.192 |
|   128      7    /25          255.255.255.128 |
|   256      8    /24      1C  255.255.255.0   |
|   512      9    /23      2C  255.255.254.0   |
|    1K     10    /22      4C  255.255.252.0   |
|    2K     11    /21      8C  255.255.248.0   |
|    4K     12    /20     16C  255.255.240.0   |
|    8K     13    /19     32C  255.255.224.0   |
|   16K     14    /18     64C  255.255.192.0   |
|   32K     15    /17    128C  255.255.128.0   |
|   64K     16    /16      1B  255.255.0.0     |
|  128K     17    /15      2B  255.254.0.0     |
|  256K     18    /14      4B  255.252.0.0     |
|  512K     19    /13      8B  255.248.0.0     |
|    1M     20    /12     16B  255.240.0.0     |
|    2M     21    /11     32B  255.224.0.0     |
|    4M     22    /10     64B  255.192.0.0     |
|    8M     23     /9    128B  255.128.0.0     |
|   16M     24     /8      1A  255.0.0.0       |
|   32M     25     /7      2A  254.0.0.0       |
|   64M     26     /6      4A  252.0.0.0       |
|  128M     27     /5      8A  248.0.0.0       |
|  256M     28     /4     16A  240.0.0.0       |
|  512M     29     /3     32A  224.0.0.0       |
| 1024M     30     /2     64A  192.0.0.0       |
| 2048M     31     /1    128A  128.0.0.0       |
| 4096M     32     /0    256A  0.0.0.0         |
+----------------------------------------------+

iptab is nothing but a perl script and part of perl-Net-IP package. Here is script listing (download link):

#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use Net::IP;
use strict;

print "+----------------------------------------------+
| addrs   bits   pref   class  mask            |
+----------------------------------------------+
";

my ($ip,$size,$class,$bits,$len);

my $ip = new Net::IP('0');

for my $len (reverse (0..32))
{

        $ip->set("0.0.0.0/$len");

        $size = $ip->size();

        if ($size >=1048576) # 1024*1024
        {
                $size /= 1048576;
                $size .= 'M';
        }
        elsif ($size >= 1024)
        {
                $size /= 1024;
                $size .= 'K';
        };

        $len = $ip->prefixlen();
        $bits = 32 - $len;

        if ($bits >= 24)
        {
                $class = 2**($bits-24);
                $class.= 'A';
        }
        elsif ($bits >= 16)
        {
                $class = 2**($bits-16);
                $class.= 'B';
        }
        elsif ($bits >= 8)
        {
                $class = 2**($bits-8);
                $class.= 'C';
        }

        printf ("| %5s %6s %6s %7s  %-15s |\n",
                $size,$bits,'/'.$len,$class,$ip->mask());


};

print "+----------------------------------------------+\n";

Shell Script: Create Linux Bootable USB Sticks

Posted on in Categories Howto, Linux, Linux desktop, Linux distribution, Perl last updated February 27, 2008

This may come handy, from the project page:

Mk-boot-usb is a perl script to create multiple-bootable usb sticks (usb keys / usb flash drives). It wipes out an entire usb stick, partitions it, creates file systems on it, installs grub, and installs a minimal linux on it. Mk-boot-usb is meant to speed up and lower the barrier of entry for creating bootable usb sticks. The usb stick will immediately become bootable (using the minimal linux), and more useful distributions can then be installed into other partitions manually simply by (1) copying any Live CD into each partition (2) modifying grub’s configuration file.

=> Mk-boot-usb: a Script to Create Multiple-Bootable USB Sticks

Related: How to Create Bootable Linux CD

Happy 20th Birthday Perl!

Posted on in Categories Links, Linux, News, Perl, UNIX, Windows last updated December 19, 2007

Perl is a dynamic programming language created by Larry Wall and first released in 1987. Perl is used in many sys admin and web related projects. Perl 1 was released to the public by Larry Wall 20 years ago today. Perl 5.10 isn’t just a bug fix version: it’s full of new features that I’m eager to use: named captures in regular expressions, state variables for subroutines, the defined-or operator, a switch statement (called given-when, though), a faster regex engine, and more. You can read more here and here.

Quick tip: Perl One Liners

Posted on in Categories Links, Linux, Perl, UNIX last updated July 2, 2007

Practical Extraction and Report Language is hackers and sys admin’s # 1 choice language 🙂

This site offers examples – perl one liners for command line use, a summary of important perl command line arguments, and how to convert between 1-liners and full Perl scripts. This page assumes the reader has a reasonable amount of Perl experience.

Perl One Liners

Howto write a better and efficient Perl program

Posted on in Categories Howto, Linux, Perl, UNIX, Windows last updated April 13, 2007

This is an excellent list of top five things that every Perl programmer should be aware of. A great article with good tips.

From the article:

Inside every tangle of obfuscated Perl code is a clean, well-architected gem struggling to emerge from its cocoon. brian d foy has spent a lot of time thinking about this for his new book, Mastering Perl, and has come up with a Top Five list of things that every Perl programmer should be thinking about when writing code.

Five Ways to Improve Your Perl Programming [onlamp.com]

Perl script to monitor disk space and send an email

Posted on in Categories Debian Linux, File system, FreeBSD, Gentoo Linux, Howto, Linux, Monitoring, OpenBSD, OS X, Perl, RedHat/Fedora Linux, Sys admin, Tips, Ubuntu Linux, UNIX last updated February 21, 2007

Here is a quick question by one of our regular reader :

How to write a perl script that can monitor my disk space under UNIX or Linux and send me an email alert?

There is a nice perl system routine called Perl df or Filesys::DiskSpace. This routine displays information on a file system such as its type, the amount of disk space occupied, the total disk space and the number of inodes etc.

Task: Install Filesys::DiskSpace

First you need to install this perl module using apt-get or from cpan (Comprehensive Perl Archive Network).
$ sudo apt-get install libfilesys-diskspace-perl

Perl script code to monitor disk space

Now write a perl script called df.pl:
$ vi df.pl
Append following code:

#!/usr/bin/perl
use strict;
use warnings;
use Filesys::DiskSpace;
 
# file system /home or /dev/sda5
my $dir = "/home";
 
# get data for /home fs
my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir;
 
# calculate free space in %
my $df_free = (($avail) / ($avail+$used)) * 100.0;
 
# display message
my $out = sprintf("Disk space on $dir == %0.2f\n",$df_free);
print $out;

Save and close the file. Run this script as follows:
$ chmod +x df.pl
$ ./df.pl

Output:

Disk space on /home == 75.35

So /home has 75.35% free disk space. Next logical step is to compare this number to limit so that you can send an email if only 10% free disk space is left on /home file system. Here is the code with

#!/usr/bin/perl
use strict;
use warnings;
use Filesys::DiskSpace;
 
my $dir = "/home";
 
# warning level 10%
my $warning_level=10;
 
my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir;
my $df_free = (($avail) / ($avail+$used)) * 100.0;
 
# compare free disk space with warning level
if ($df_free < $warning_level) {
my $out = sprintf("Send an Email - Disk space on $dir => %0.2f%% (WARNING Low Disk Space)\n",$df_free);
print $out;
}
else
{
my $out = sprintf("Disk space on $dir => %0.2f%% (OK)\n",$df_free);
print $out;
}

Run script as follows:
$ ./df.pl
Output:

Send an Email - Disk space on /home => 3.99% (WARNING Low Disk Space)

Here is final code that send an email alert ( download):

#!/usr/bin/perl
# Available under BSD License. See url for more info:
# http://www.cyberciti.biz/tips/howto-write-perl-script-to-monitor-disk-space.html
use strict;
use warnings;
use Filesys::DiskSpace;
 
# file system to monitor
my $dir = "/home";
 
# warning level
my $warning_level=10;
 
# email setup
my $to=[email protected]';
my $from=[email protected]';
my $subject='Low Disk Space';
 
# get df
my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir;
 
# calculate
my $df_free = (($avail) / ($avail+$used)) * 100.0;
 
# compare
if ($df_free < $warning_level) {
my $out = sprintf("WARNING Low Disk Space on $dir : %0.2f%% ()\n",$df_free);
 
# send email using UNIX/Linux sendmail
open(MAIL, "|/usr/sbin/sendmail -t");
 
## Mail Header
print MAIL "To: $to\\n";
print MAIL "From: $from\\n";
print MAIL "Subject: $subject\\n";
 
## Mail Body
print MAIL $out;
 
close(MAIL);
}

You can run this script as a cron job:
@hourly /path/to/df.pl

Recommended readings

=> Read man page of this module by typing following command:
$ man filesys::diskspace

=> CPAN filesys::diskspace webpage

=> Sending mail with Perl mail script and How do I send html email from Perl?

=> Shell script to monitor or watch the disk space