Tuesday, September 13, 2011

Calculate IP's between specified range

If you want to calculate all IP's between the specified range then following perl script can be used.
#!/usr/bin/perl
$numArgs = $#ARGV + 1;
if ($numArgs ne "2"){
        print "USAGE: perl $0 <start ip address> <end ip address>\n";
        exit;
}

$sip=$ARGV[0];
$eip=$ARGV[1];

($sip1,$sip2,$sip3,$sip4)=split(/[.]/,$sip);
($eip1,$eip2,$eip3,$eip4)=split(/[.]/,$eip);

$next_ip=$sip;
$end_ip=$eip;
while ($next_ip ne $end_ip){

        $next_ip="$sip1.$sip2.$sip3.$sip4";
        print $next_ip."\n";

        $sip4++;
        if ( $sip4 > 255){
                $sip4=0;
                $sip3 =$sip3 + 1;
        }

        if ( $sip3 > 255){
                $sip3=0;
                $sip2 =$sip2 + 1;
        }

       if ( $sip2 > 255){
                $sip2=0;
                $sip1 =$sip1 + 1;
        }

}
Usage
perl create_ip_ranges.pl 192.168.0.0  192.168.0.2
will return
192.168.0.0
192.168.0.1
192.168.0.2

How to run mysql from Linux command line

Following code connects to MySql server and show all databases in mysql with column delimited by tab
mysql -hHOST -uUSER -pPASSWORD -e "show databases" -N -s
-N means do *not* display the column names
-s option means display raw data with no formatting
To run multiple commands, delimit them by semicolon.
To read command from a file run
mysql -hHOST -uUSER -pPASSWORD < batch-fileor
mysql -hHOST -uUSER -pPASSWORD-e "source batch-file"

How to encrypt and decrypt a file in Linux

You can use command gpg to encrypt and decrypt a file in Linux

Following is an example of how you can encrypt a file using gpg
     gpg -c test.txt
This command will ask for a passwphrase and on successful execution will create file test.txt.gpg

Following is an example of how you can decrypt a file using gpg
   gpg -d test.txt.gpg > test.txt.tmp
NOTE: Do *not* decrypt file to test.txt because if you accidently provided wrong passphrase , decryption will fail and file test.txt will be empty and if you forgot the passphrase, there is no way to receover test.txt file