Follow me!

LinkedIn Twitter

Port Report News Letter

Subscribe to this news letter if you want to be kept up2date on the newest updates on the Port Report Project.
Port Report Project


Receive HTML?
Thank you for subscribing to the Port Report Project News Letter.

Newest Downloads

calendar.gifJun.26

This program will create a host up/down report from nagios.log

calendar.gifMay.22

This Script will list all Virtual Machines in an ESX Server... Example below.. python listVMsInf...

calendar.gifMay.08

I'm really excited to introduce Port Report Update 1.9 aka the Switch Port Mapper Tool. We've...

calendar.gifMay.04

Here is a quick update..... I just add dns reverse lookups to the output of this script.. So if ...

Basics 101: ruby python bash perl expect php
Programming HowTo's - General How To's
Written by ikenticus   
Wednesday, 30 April 2008 22:10

Watch as a red snake breaks open an oyster anticipating a new designer drug...no, that's not what that title means. Actually, this is a scripting tutorial of some basic methods like getopts, variable manipulation, output formatting, conditionals and functions/subroutines. Scripting languages translate very much like Romance Languages --- usually the quickest way to learn a second one is to simply translate your knowledge of the first one. A year ago, I had written a Zenoss-v1 device script in python, perl and bash for a friend to adjust to python with his knowledge of perl.

Originally, I was going to post it as is in this community, but since I'm not sure if the latest version of Zenoss supports it anymore, I figured it would be better to simplify it and added two more languages in the mix. If there are additional requests, we can expand this to cover some additional methods. All scripts are designed to produce the same exact output (with the exception of the debug output, which is language-based) and are structured identically so that you can understand them side-by-side.


ruby:
#!/usr/bin/ruby

require 'getoptlong'
require 'net/http'
require 'pp'

$script = File.basename($0)


def usage (code=0)
printf("\nUsage: %s [-s|--switch]\n", $script)
print "
-h displays this help usage --help
-d debugging mode --debug
-s site website domain --site=site
-p path website path --path=path
\n"
Process.exit code
end


def test (site, path)
http = Net::HTTP.new(site)
uri = http.get(path, nil)
if Integer(uri.code) == 200
exists = true
else
exists = false
end
return exists
end


### main

# parse/process command line options/arguments
opts = GetoptLong.new(
[ '--help', '-h', GetoptLong::NO_ARGUMENT ],
[ '--debug', '-d', GetoptLong::NO_ARGUMENT ],
[ '--site', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
[ '--path', '-p', GetoptLong::OPTIONAL_ARGUMENT ]
)

dump = Array.new(ARGV)
site = path = debug = nil
opts.each do |opt, val|
case opt
when '--help': usage 0
when '--debug': debug = true
when '--path': path = val
when '--site': site = val
end
end

# check for the minimal options
if site == nil || path == nil
puts 'Missing arguments!'
usage 1
end

if debug == true
puts '--v-- DEBUG OPTS --v--'
pp dump
puts '--^-- DEBUG OPTS --^--'
end

state = test(site, path)
if state == true:
printf("\n%s%s retrieved\n\n", site, path)
else
printf("\n%s%s not found\n\n", site, path)
end

python:
#!/usr/bin/python

import os
import sys

script = os.path.basename(sys.argv[0])


def usage (code=0):
print '\nUsage: %s [-s|--switch]' % script
print '''
-h displays this help usage --help
-d debugging mode --debug
-s site website domain --site=site
-p path website path --path=path
'''
sys.exit(code)


def test (site, path):
import httplib
conn = httplib.HTTPConnection(site)
conn.request("GET", path)
uri = conn.getresponse()
conn.close()
if uri.status == 200:
exists = True
else:
exists = False
return exists


def main (args):

# parse/process command line options/arguments
import getopt
try:
opts, args = getopt.getopt(args, "hds:p:",
[ '--help', '--debug', 'site=', 'path=' ])
except getopt.error:
usage(0)

site = path = debug = state = None
for opt, val in opts:
if opt in ('-h', '--help'):
usage(0)
if opt in ('-d', '--debug'):
debug = True
if opt in ('-p', '--path'):
path = val
if opt in ('-s', '--site'):
site = val

# check for the minimal options
if site is None or path is None:
print 'Missing arguments!'
usage(1)

if debug is True:
print '--v-- DEBUG OPTS --v--'
print opts
print '--^-- DEBUG OPTS --^--'

state = test(site, path)
if state is True:
print '\n%s%s retrieved\n' % (site, path)
else:
print '\n%s%s not found\n' % (site, path)


if __name__ == "__main__":
main(sys.argv[1:])


bash:

#!/bin/bash

script=${0##*/}


usage() {
code=${1:-0}
cat << EOF

Usage: $script [-s]

-h displays this help usage
-d debugging mode
-s site website domain
-p path website path

EOF
exit $code
}


test() {
local site=
 path=
exists
local uri="http://$site$path"
wget -qO /dev/null $uri
local exists=$?
return $exists
}


### main

# parse/process command line options/arguments
unset site path debug state
while getopts "hds:p:" option; do
case $option in
h) usage 0 ;;
d) debug=1 ;;
p) path=$OPTARG ;;
s) site=$OPTARG ;;
esac
done

# check for the minimal options
if [ -z "$site" -o -z "$path" ]; then
echo "Missing arguments!";
usage 1;
fi

if [ -n "$debug" ]; then
echo "--v-- DEBUG OPTS --v--";
echo $*
echo "--^-- DEBUG OPTS --^--";
fi

test $site $path
state=$?
if [ $state -eq 0 ]; then
printf "\n%s%s retrieved\n\n" $site $path;
else
printf "\n%s%s not found\n\n" $site $path;
fi


perl:

#!/usr/bin/perl

use strict;
use Data::Dumper;
use File::Basename;
use Getopt::Std;
use LWP::Simple;

my $script = basename($0);


sub usage {
my $code = shift;
$code = 0 if (!$code);
print qq~
Usage: $script [-s]

-h displays this help usage
-d debugging mode
-s site website domain
-p path website path

~;
exit $code;
}


sub test {
my $site = shift;
my $path = shift;
my $uri = 'http://'.$site.$path;
my $exists = get($uri);
return $exists;
}


### main

# parse/process command line options/arguments
my %opt;
my $opts = 'hds:p:';
getopts( "$opts", \%opt ) or usage();

my ($site, $path, $state);
usage() if $opt{h};
$site = $opt{s} if $opt{s};
$path = $opt{p} if $opt{p};

# check for the minimal options
if (!$site || !$path) {
print "Missing arguments!\n";
usage(1);
}

if ($opt{d}) {
print "--v-- DEBUG OPTS --v--\n";
print Dumper(%opt);
print "--^-- DEBUG OPTS --^--\n";
}

$state = test($site, $path);
if ($state) {
printf "\n%s%s retrieved\n\n", $site, $path;
} else {
printf "\n%s%s not found\n\n", $site, $path;
}


expect:

#!/usr/bin/expect

exp_version -exit 5.0
exp_internal 0
log_user 0
set timeout 15

set script [ lindex [ split $argv0 "/" ] end ]


proc usage { code } {
global script
send_user [ format "\nUsage: %s \[-s\]\n" $script ]
send_user {
-h displays this help usage
-d debugging mode
-s site website domain
-p path website path\n

}
exit $code
}


proc test { site path } {
spawn telnet $site 80
expect {
timeout {
return 1
}
"Connection refused" {
return 1
}
"Escape character is '^]'.\r\r\n"
}
sleep 1
send "GET ${path} HTTP/1.0\r"
send "Host: ${site}\r"
send "User-Agent: Mozilla/4.0 (Test)\r"
send "Accept: */*\r"
send "\r"
expect {
timeout {
return 1
}
"HTTP/1.0 200 OK" {
return 0
}
}
return 1
}


### main

# parse/process command line options/arguments
regsub -- "^-" $argv "" args
regsub -all -- " -" $args "|" args

set site {}
set path {}
set debug 0
set state 0
# expect does not have a standard getopts, so parse it manually
foreach opts [ split $args "|" ] {
set opt [ lindex $opts 0 ]
set val [ lindex $opts 1 ]
switch $opt {
h { usage 0 }
d { set debug 1 }
p { set path $val }
s { set site $val }
}
}

# check for the minimal options
if { $site == "" || $path == "" } then {
send_user "Missing arguments!\n"
usage 1
}

if { $debug == 1 } then {
send_user -- "--v-- DEBUG OPTS --v--\n"
send_user -- "$argv\n"
send_user -- "--^-- DEBUG OPTS --^--\n"
}

set state [ test $site $path ]
if { $state == 0 } then {
send_user [ format "\n%s%s retrieved\n\n" $site $path ]
} else {
send_user [ format "\n%s%s not found\n\n" $site $path ]
}


php:

#!/usr/bin/php
<?php

include ("Console/Getopt.php");

$script = basename($_SERVER['PHP_SELF']);


function usage ($code) {
global $script;
if (empty($code)) { $code = 0; }
print "
Usage: $script [-s|--switch]

-h displays this help usage --help
-d debugging mode --debug
-s site website domain --site=site
-p path website path --path=path

";
exit($code);
}


function error($num, $str, $file, $line, $context) {
// trapping errors to avoid displaying onscreen
return;
}


function test ($site, $path) {
set_error_handler('error');
$exists = file_get_contents('http://'.$site.$path);
return $exists;
}


### main

// parse/process command line options/arguments
$cg = new Console_Getopt();
$args = $cg->readPHPArgv();
$getopt = $cg->getopt($args, "hds:p:",
array("help", "debug", "site=", "path="));
if (PEAR::isError($getopt)) {
// print_r ($getopt->getMessage() . "\n");
usage(1);
}

$site = $path = $debug = $state = false;
$opts = $getopt[0];
foreach ($opts as $opt) {
switch ($opt[0]) {

case 'h':
case '--help':
usage(0);
break;

case 'd':
case '--debug':
$debug = true;
break;

case 'p':
case '--path':
$path = $opt[1];
break;

case 's':
case '--site':
$site = $opt[1];
break;

}
}

// check for the minimal options
if (!$site || !$path) {
print "Missing arguments!\n";
usage(1);
}

if ($debug) {
print "--v-- DEBUG OPTS --v--\n";
print_r ($opts);
print "--^-- DEBUG OPTS --^--\n";
}

$state = test($site, $path);
if ($state) {
printf ("\n%s%s retrieved\n\n", $site, $path);
} else {
printf ("\n%s%s not found\n\n", $site, $path);
}

?>


Add this page to your favorite Social Bookmarking websites
Reddit! Del.icio.us! Mixx! Free and Open Source Software News Google! Live! Facebook! StumbleUpon! Yahoo! Free Joomla PHP extensions, software, information and tutorials.
Comments
Search RSS
Only registered users can write comments!

3.22 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."

Last Updated on Monday, 12 May 2008 20:09