# code snippets

**URL:** <https://forums.teamphoenixrising.net/t/code-snippets/21647>\
**Category:** \*nix and other operating systems\
**Created:** [4 November 2011 00:14 UTC](https://forums.teamphoenixrising.net/t/code-snippets/21647 "2011-11-04T00:14:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![MrTFWitt](https://forums.teamphoenixrising.net/user_avatar/forums.teamphoenixrising.net/mrtfwitt/32/707_2.png) [@MrTFWitt](https://forums.teamphoenixrising.net/u/MrTFWitt)\
**Post date:** [4 November 2011 00:14 UTC](https://forums.teamphoenixrising.net/t/code-snippets/21647/1 "2011-11-04T00:14:33Z")

</div>

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/](http://www.catonmat.net/blog/perl-one-liners-explained-part-three/)
