code snippets

I like code, shell script, perl script, whatever it takes to get the job done

Ever wanted to know in a script if a host is running a service ?
I like this little extract and have used it in many places, the example below is perl buried in a korn shell script but how you use it is up to you.
The bit below will try for three seconds to open a connection to the ssh port of 192.168.1.132 and return an error if that fails.
Its handy when you have a dullard version of ssh installed that chooses to hang forever rather than time out :rolleyes: and have to stick with such a version for “compatibility reasons”

is_host_up()
{
cat <<EOF|/usr/bin/perl –
use IO::Socket;
$remote = IO::Socket::INET -> new ( Proto => “tcp”, Timeout => 3, PeerAddr => “${1}”, PeerPort => “22” );
if ($remote) {exit 1}
EOF
}

host=192.168.1.132
is_host_up $host
stat=$?
if [ ${stat} -eq 1 ]
then
echo host up
else
echo host down
fi

Lottery number generator
This has generated two wins in three weeks!
You may be less lucky

perl -le ‘$n=6; $min=1; $max=50; $, = " "; print map { int(rand($max-$min))+$min } 1…$n’

This one was copied from http://www.catonmat.net/blog/perl-one-liners-explained-part-three/