Gheek.net

February 28, 2011

Howto Make Script More Portable With #!/usr/bin/env As a Shebang

Filed under: expect, linux, nix, perl, php, shell scripts — lancevermilion @ 9:33 am

The following article is taken directly from http://www.cyberciti.biz/tips/finding-bash-perl-python-portably-using-env.html by VIVEK GITE.

You may have noticed that most shell and perl script starts with the following line:
#!/bin/bash
OR
#!/usr/bin/perl

It is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under UNIX and Linux execute using the interpreter specified on a first line.

However there is a small problem. BASH or Perl is not always in the same location (read as PATH) such as /bin/bash or /usr/bin/perl. If you want to make sure that script is portable across different UNIX like operating system you need to use /usr/bin/env command.

env command allows to run a program in a modified environment.

Find line
#!/bin/bash

Replace with
#!/usr/bin/env bash

For example here is a small script:

#!/usr/bin/env bash
x=5
y=10
echo "$x and $y"

OR

#!/usr/bin/env perl
use warnings;
print "Hello " x 5;
print "\\n";

Now you don’t have to search for a program via the PATH environment variable. This makes the script more portable. Also note that it is not foolproof method. Always make sure you have /usr/bin/env exists or use a softlink/symbolic link to point it to correct path. And yes your work (script) looks more professional with this hack 🙂

Advertisement

February 15, 2008

PHP Cheat Sheet

Filed under: cheatsheets, php — Tags: , , , — lancevermilion @ 3:07 pm

php_cheat_sheet

February 14, 2008

decoder_php.txt

Filed under: html, php — Tags: , , , , , , , , — lancevermilion @ 2:28 pm
 Modify -> Share (aka: GNU License)
 *
 * If you find youself unable to perform these tasks, this source code
 *   is *not* for you and should be deleted now.
 *
 */ // P.S. Donations are always appreciated. :-)
?>

TRANSLATOR, BINARY



.ff{font-size: 10px;
	font-family:verdana,arial,helvetica,sans;
	color: #333333;
	background: #eee;
	}
.btn{
	font-size: 8px;
	font-family:verdana,arial,helvetica,sans;
	color: #333333;
	background: #eee;
	}
BODY{
scrollbar-3dlight-color:#999999;
scrollbar-arrow-color:#999999;
scrollbar-base-color:#DDDDDD;
scrollbar-darkshadow-color:#999999;
scrollbar-face-color:#DDDDDD;
scrollbar-highlight-color:#DDDDDD;
scrollbar-shadow-color:#DDDDDD;
scrollbar-track-color:#CCCCCC;
}







TRANSLATOR, BINARY

Please note:
This application encodes and decodes ASCII and ANSI text.
Only codepoints < 128 are ASCII. This is provided for educational and entertainment use only.

<?/*
[ TEXT ]
$val){ $$key = stripslashes($val); } #$_POST[ascii] = str_replace("\\'","'",$_POST[ascii]); #$_POST[ascii] = str_replace("\\\"","\"",$_POST[ascii]); #$_POST[ascii] = str_replace("\\\\","\\",$_POST[ascii]); if($ascii != "") print htmlentities($ascii); else { if($binary != "") { $binary_ = preg_replace("/[^01]/","", $binary); for($i = 0; $i < strlen($binary_); $i = $i + 8) $ascii = $ascii.chr(bindec(substr($binary_, $i, 8))); } if($hex != "") { $hex_ = preg_replace("/[^0-9a-fA-F]/","", $hex); for($i = 0; $i
2 [ BINARY ]
<?php if($binary != "") echo $binary; else if($ascii != "") { $val = strval(decbin(ord(substr($ascii, 0, 1)))); echo str_repeat("0", 8-strlen($val)).$val; for($i = 1; $i
4 [ HEX ]
<?php if($hex != "") echo $hex; else if($ascii != "") { $val = dechex(ord(substr($ascii, 0, 1))); echo str_repeat("0", 2-strlen($val)).$val; for($i = 1; $i
3 [ OCT ]
<?php if($oct != "") echo $oct; else if($ascii != "") { $val = 0; for($i = 0; $i 0) echo oct_decode($val); } function b64_decode($val) { $tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; if($val >= 64) return oct_decode(intval($val / 64))."".substr($tab,$val%64,1); return substr($tab,$val,1); } function oct_decode($val) { if($val >= 8) return oct_decode(intval($val / 8))."".($val%8); return "".$val; } */ ?>
<? //?>
6 [ BASE64 ]

[ DEC / CHAR ]
<?php if($char != "") echo $char; else if($ascii != "") { echo ord(substr($ascii, 0, 1)); for($i = 1; $i
[ MESSAGE DIGEST / CHECK SUM ]
str_sha1($ascii))."\n"; echo "SHA1: "; $ascii = $sha->str_sha1($ascii); for($i = 1; $i
(This cannot be decoded*)
Amazon Honor System
*Cannot be decoded easily (within my lifespan). The source code for this page is available here.
Credit for this idea goes to http://nickciske.com/binary/ in its original form in 2000. <? function split32($text) { $string = ""; for($i = 0; $i < strlen($text); $i = $i + 32) { $string = "$string\n ".substr($text, $i, 32); } return $string; } function splitn($n,$text) { $string = ""; for($i = 0; $i

CalcNetworkBroadcastHostRange_php.txt

Filed under: php — Tags: , — lancevermilion @ 2:26 pm
#!/usr/local/bin/php
 " . long2ip($bc - 1)  . "\n";
?>

Produces the output:

IP Address:        172.14.1.57
Subnet Mask:        255.255.255.0
Network Address:    172.14.1.0
Broadcast Address:  172.14.1.255
Number of Hosts:    254
Host Range:        172.14.1.1 -> 172.14.1.254

CalcIPRange_php.txt

Filed under: php — Tags: , — lancevermilion @ 2:25 pm
function CalculateIPRange($iprange)
{
   // Daevid Vincent [daevid@daevid.com] 10.13.03
   //  This function will return an array of either a negative error code
   //  or all possible IP addresses in the given range.
   //  format is NNN.NNN.NNN.NNN - NNN.NNN.NNN.NNN  (spaces are okay)

   $temp = preg_split("/-/",$iprange, -1, PREG_SPLIT_NO_EMPTY);
   $QRange1 = $temp[0];
   $QRange2 = $temp[1];

   if ($QRange2 == "") return array($QRange1); //special case, they didn't put a second quad parameter

   //basic error handling to see if it is generally a valid IP in the form N.N.N.N
   if ( preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/",$QRange1) != 1 ) return array(-1);
   if ( preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/",$QRange2) != 1 ) return array(-1);

   $quad1 = explode(".",$QRange1);
   $quad2 = explode(".",$QRange2);

   reset ($quad1);
   while (list ($key, $val) = each ($quad1))
   {
         $quad1[$key] = intval($val);
         if ($quad1[$key]  255) return array(-2);
   }
   reset ($quad2);
   while (list ($key, $val) = each ($quad2))
   {
         $quad2[$key] = intval($val);
         if ($quad2[$key]  255) return array(-2);
   }

   $startIP_long = sprintf("%u",ip2long($QRange1));
   $endIP_long = sprintf("%u",ip2long($QRange2));
   $difference = $endIP_long - $startIP_long;
   //echo "startIP_long = ".$startIP_long." and endIP_long = ".$endIP_long." difference = ".$difference."
"; $ip = array(); $k = 0; for ($i = $startIP_long; $i 0 && $thisQuad[3] < 255) $ip[$k++] = $temp; } return $ip; } //CalculateIPRange()

bridgeimportip_php.txt

Filed under: ipplan, php, switchmap — Tags: , , — lancevermilion @ 2:24 pm
GetIPDetails($baseindex, $ipaddr)) {
//                // log the entire row to the auditlog for history - field
//                // is too small!
//                // probably better to rather just insert into a duplicate
//                // ipaddr table, or to have a trigger event do something
//                $row["event"]=130;
//                $row["user"]="Switchmap Bridge";
//                $row["action"]="log old row contents";
//                $row["baseindex"]=$baseindex;
//                $row["ip"]=inet_ntoa($ipaddr);
//                $this->AuditLog($row);
//
//                $this->ds->RowLock("ipaddradd", "baseindex=$baseindex AND ipaddr=$ipaddr");
//            }
//            $this->AddIPaddradd($ipaddr, $baseindex, $info);
//            //$this->AuditLog(array("event"=>131, "action"=>"modify ip details", "ip"=>inet_ntoa($ipaddr),
//            //        "user"=>getAuthUsername(), "ipaddr"=>$ipaddr, "baseindex"=>$baseindex,
//            //        "userinf"=>$user, "location"=>$location, "telno"=>$telno, "macaddr"=>$macaddr,
//            //        "descrip"=>$descrip, "hname"=>$hname));
//        }
//        else
//        {
//          //echo "ModifyIPaddradd: ERROR \$baseindex ($baseindex) is empty. Can not update template\n";
//          //echo "ModifyIPaddradd: ERROR \$ipaddr ($ipaddr) is empty. Can not update template\n";
//          //echo "ModifyIPaddradd: ERROR \$info ($info)is empty. Can not update template\n";
//        }
//    }
//
//// update an existing IP record - only updates relevant field
//    function UpdateIPaddrbridge($ipaddr, $baseindex, $field, $value) {
//
//        $userid = "Switchmap Bridge";
//
//        $result = &$this->ds->Execute("UPDATE ipaddr
//                           SET $field=".$this->ds->qstr($value).",
//                              lastmod=".$this->ds->DBTimeStamp(time()).",
//                              userid=".$this->ds->qstr($userid)."
//                           WHERE baseindex=$baseindex AND ipaddr=$ipaddr");
//        // record does not exist, error
//        return $this->ds->Affected_Rows();
//    }

//****END ADD TO class.dbflib.php****

require_once("../ipplanlib.php");
require_once("../adodb/adodb.inc.php");
require_once("../class.dbflib.php");
require_once("../class.templib.php");
require_once("../auth.php");
require_once("../xmllib.php");

$filename = $_SERVER["argv"][1];
$cust = "1";
$format = "text";

$ds=new IPplanDbf() or "Could not connect to database\n";
$rowcnt=0;
$ds->DbfTransactionStart();
if ($format=="text") {
    // open uploaded file for read
    $fp = @fopen ($filename, "r");
    // no real portable way to check if file was uploaded - php version
    // dependent
    if (!$fp) {
        echo "File could not be opened.\n";
    }

    // can we read the template?
    $template=FALSE;
    $template=new IPplanIPTemplate("iptemplate", $cust);
    if ($template->is_error() == TRUE) {
        echo "Template could not be opened.\n";
        $template=FALSE;   // use is_object later
    }

    //Clear out all previous configs from Switchmap
    $ds->WipeMacInfo();

    while ($data = fgetcsv ($fp, 4098, FIELDS_TERMINATED_BY)) {
        $rowcnt++;
        //echo "Importing row: $rowcnt\n";
        ProcessRow($ds, $cust, $w, $p, $data, $template);
    }
    fclose ($fp);
}
$ds->DbfTransactionEnd();


// $data is number indexed array that has format of ip, user, location,
// description, telephone
function ProcessRow($ds, $cust, &$w, &$p, $data, $template) {

    global $format;

    $num = count ($data);

    // blank row
    if (empty($data[0])) {
        echo "Row is blank - ignoring\n";
        return;
    }
    // bogus row
    if ($numDbfTransactionEnd();
        echo "Row not the correct format\n";
    }

    if (testIP($data[0])) {
        echo "Invalid IP Address\n";
        return;
    }

    $ip=inet_aton($data[0]);
    $macaddr=substr($data[1],0,12);
    $info="";
    if (is_object($template)) {
        // all columns over 6 are considered for adding to template fields
        $cnt=2;
        $userfld=array();
        foreach($template->userfld as $key=>$value) {
            // set fields in template only if field in import file exists, else make blank
            $userfld[$key]=isset($data[$cnt]) ? $data[$cnt] : "";
            $cnt++;
        }
        $template->Merge($userfld);
        $err=$template->Verify($w);
        if ($err) {
            // ok to save what has been imported already
            $ds->DbfTransactionEnd();
            echo "Row failed template verify.\n";
        }

        if ($template->is_blank() == FALSE) {
            $info=$template->encode();
        }
    }

    // NOTE: Test ip address
    $result=$ds->GetBaseFromIP($ip, $cust);
    if (!$row = $result->FetchRow()) {
        // ok to save what has been imported already
        $ds->DbfTransactionEnd();
        echo "Subnet could not be found for IP address $data[0]\n";
    }

    $baseindex=$row["baseindex"];
    $baseaddr=$row["baseaddr"];
    $subnetsize=$row["subnetsize"];

    if ($ds->UpdateIPaddrbridge($ip, $baseindex, "macaddr", $macaddr) == 0) {
        #echo " - IP address details could not be modified [macaddr = $macaddr]\n";
    }
    else {
        #echo " - Updating IP address details [macaddr = $macaddr]\n";
    }

    if ($ds->ModifyIPaddradd($baseindex, $ip, $info) == 0) {
        #echo " - IP address details could not be modified [info = $info]\n";
    }
    else {
        #echo " - Updating IP address details [info = $info]\n";
    }
}
?>

February 8, 2008

ipplansnmppoll_php.txt

Filed under: ipplan, php, snmp — Tags: , , — lancevermilion @ 12:56 pm
 'someNetworkcommunity', 'windows' => 'someNTcommunity', 'unix' => 'someUnixcommuity', 'na' => 'public' );
$oid = '.1.3.6.1.2.1.1.5.0'; //system.sysName.0
$hosts = array();
//$ips = array();
$ips = file('li.txt');
foreach ($ips as $ip)
{
  $ip = preg_replace("/\n|\r/", '', $ip);
  for ($count = 1; $count <= 254; $count++) {
  $jip = $ip . '.' . $count;
  array_push($hosts, $jip);
  }

$pids = array();

pcntl_signal(SIGCHLD,  "sig_handler");
echo "Forking " . sizeof($hosts) . " times\n";
for($i = 0; $i  $devcomm)
    {

      $output = snmpget($hosts[$i], $devcomm, $oid) . " :: $dns :: $devcomm";
      if (!$output)
      {
        $output = ":: Unknown :: $dns :: Timeout";
      }
      else
      {
        if ( preg_match("/^\s+::/", $output) )
        {
          $output = ":: Unknown :: $dns :: Timeout";
        }
        else
        {
          $output = ":: $output";
          break;
        }
      }
    }
//    $ping  = `ping -c 1 $hosts[$i] | grep loss | awk '{print $6}' | sed 's/%//'`;
//    if ( $ping > 0 )
//    {
//      if ($ping == 100)
//      {
//        $status = 'DOWN';
//      }
//      else
//      {
//        $status = 'UP - Packet loss';
//      }
//    }
//    else
//    {
//      $status = 'UP';
//    }
    $output = preg_replace('/\n/', '', $output);
    $output = preg_replace('/\r/', '', $output);
    //echo "$pids[$i] :: $hosts[$i] $output :: $status\n";
    echo "$hosts[$i] $output :: $status\n";
    //echo "$hosts[$i] $output\n";

    exit;
  }
}

for($i = 0; $i < sizeof($hosts); $i++) {
  pcntl_waitpid($pids[$i], $status, WUNTRACED);
}

// complete parent processing now all children have finished
while ( $totretchild 

Create a free website or blog at WordPress.com.