PHP to solve problems

PHP make you think of web app’s right? … well, did you know you can run it from the CLI to?

Recently I’ve been doing a lot of spreadsheet and sub-netting type stuff, whilst doing this mundane work I’ve realised that I can get scripts to work for me. I’ve started to post a few PHP network functions to github which I’ve been using.

Here’s an example: I have a nokia firewall, the routing table in voyager is shown in the following format –

Network / CIDR Mask , Gateway
10.0.0.0 / 8 , 10.0.0.1

I need that same routing in a Cisco ASA format –

Network , Mask , Gateway
10.0.0.0, 255.0.0.0, 10.0.0.1

Now this is not a problem for a few routes but the firewall I’m looking at now has 177 static routes, which I don’t want to convert manually.

Roll in PHP!
Save the original routing table as a .csv file. ColA = ip/mask , ColB = gateway.

Save this a route_conv.php

<?php

	/**

		Change the below to your CSV File.

	**/

	$firewall_csv = "./routes_cdr.csv"; 

	/**

		Function to convert CIDRs such as "23" to decimall dotted like "255.255.254.0"
		I've got more of these: https://gist.github.com/1309388

	**/

	function cidr2mask($netmask) {

		$netmask_result="";
		for($i=1; $i <= $netmask; $i++) {
		  $netmask_result .= "1";
		}

		for($i=$netmask+1; $i <= 32; $i++) {
		    $netmask_result .= "0";
		}

		$netmask_ip_binary_array = str_split( $netmask_result, 8 );

		$netmask_ip_decimal_array = array();
		foreach( $netmask_ip_binary_array as $k => $v ){
		    $netmask_ip_decimal_array[$k] = bindec( $v ); // "100" => 4
		}

		$subnet = join( ".", $netmask_ip_decimal_array );

		return $subnet;

	}

	ini_set('auto_detect_line_endings', true); // detect CR

	if (file_exists($firewall_csv)) {

		$file = fopen($firewall_csv, 'r');

		$counter = 0; // array counter

		while (($data = fgetcsv($file)) !== FALSE) {
			
			list($ip, $netmask) = split( "/", $data[0] ); // SPLIT Col A into IP & Mask

			$netmask = cidr2mask($netmask); // Covert Mask

			$gateway = $data[1]; // Col B

			/**
				This echo is the CSV style output, but you could change this to echo "route add $ip $mask $ gateway \n" for unix style output.
			**/

			echo $ip . "," . $netmask . "," . $gateway . "\n";

		}

		fclose($file);

	} else {
		
		echo "404: $firewall_csv \n"; // FILE NOT FOUND.

	}
?>

from your CLI run “php route_conv.php” and enjoy the output!

 

rgds,

Nick