Software Engineer

showmount – names instead of ips

· by jsnby · Read in about 1 min · (203 Words)
Computers

If you use nfs, you’re probably familiar with the showmount command. It usually results in output like this:

$ showmount -a
All mount points on nfs.example.com:
192.168.0.5:/nfs/path1
192.168.0.5:/nfs/some/other/path
192.168.0.6:/nfs/path1

This is fine and dandy with only a couple of machines, but with 50 or 100 different machines in a complex network, using ip addresses can get a bit frustrating….if only there was a way to get the hostname instead of the IP. Output like this would be nice:

$ jshowmount
All mount points on nfs.example.com:
server1.example.com:/nfs/path1
server1.example.com:/nfs/some/other/path
server2.example.com:/nfs/path1

I’m sure there’s a one-liner sed/awk/grep that could do the same thing, but I don’t mind writing a few lines of perl provided I can use it again and again (hence why it’s posted here). Without further delay, I give you jshowmount (I threw this in /usr/sbin/ so it would be in root’s path):

#!/usr/bin/perl

use strict;
use warnings;
use Socket;

open(PROC, "/usr/sbin/showmount -a|");

while(my $line=<PROC>)
{
    if($line=~m/(\d+\.\d+\.\d+\.\d+):(.+)$/) {
        my $ip = $1;
        my $name = _gethostbyaddr($ip);

        if(defined($name)) {
            $line=~s/$ip/$name/;
        }
    }

    print $line;
}

close PROC;

# translate an ip addr to a host name
sub _gethostbyaddr
{
    my ($ip) = @_;
    my $iaddr = inet_aton($ip);
    my $name  = gethostbyaddr($iaddr, AF_INET);
    return $name;
}

Is it the prettiest script? No. Could you do this in some other (probably simpler) way? Yes. This what I came up with and it worked for me. I share it here in the hopes that it might save you a couple of minutes should you ever need something like this.