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!

Unread Gmail on your OSX Desktop

1) Install GeekTool
2) Run this script….


USERNAME="me@gmail.com"
PASSWORD="password"

EMAIL=`curl -u $USERNAME:$PASSWORD --silent "https://mail.google.com/mail/feed/atom" | tr -d '\n' | awk -F '<entry>' '{for (i=2; i<=NF; i++) {print $i}}' | sed -n "s/<title>\(.*\)<\/title.*name>\(.*\)<\/name>.*/\2 - \1/p"`

if [ -n "$EMAIL" ]
	then

	echo "INBOX:"
	echo "-----------------------------------------"

	IFS=$'\n'
	for i in $EMAIL
	do
		len=${#i}
		if [ "$len" -gt 40 ]
			then
			echo ${i:0:37} "..."
		else
			echo $i
		fi
	done
fi

3) smile

F5 BigIP LTM VE works in Virtual Box

Something I discovered ages ago (so long ago that my trial license expired) but forgot to post is that you can get an LTM VE to work in Virtual Box.

To get started download the ESX image from the F5 VE Trial Page, when you get the download import the OVA into virtualbox.

The only thing I needed to tweak after the import was the interface settings, you need two intels and a PCNet, the PCNet is the management interface. Set the PCNet to host only networking, give your laptop/pc an ip address on the host only network a 192.168.1 address and you’re good to go!

You may experience HIGH CPU issues after boot, but since these boxes are based on linux, you can use the divider=10 centos trick.

Enjoy your virtual load balancing!

Lowing VirtualBox priorities

One of the things I’d really like is process priorities for virtual box. In the forum I posted a couple of shell commands that I regularly type… which gets a bit tedious, following a recent article on lifehacker reviewing mac text expanding I’ve been prompted to automate a few things… below is a little shell script to lower the priority (renice) of all running virtual machines.

The advantage of doing this is that your host machine stays snappy, responsive and won’t get too over-loaded by jobs on your VMs!

#!/bin/bash
ps -xo pid,command | grep -v grep | grep startvm | while read line ;
do
        procID=`echo $line | awk '{print $1}'`
        sudo renice +10 -p $procID
done

The above code works on a mac; although I haven’t tested it, I recon to get it running on Linux you need to update the PS command, by swapping the x for an e… like this….

#!/bin/bash
ps -eo pid,command | grep -v grep | grep startvm | while read line ;
do
        procID=`echo $line | awk '{print $1}'`
        sudo renice +10 -p $procID
done

Have fun, suggestions and improvements welcome.

Xcode for WordPress Plug-in Developers

This post is an extension to this excellent article except with a subtle difference, I’m not interested in hacking the WP core, I’m writing a plug-in :)

I’m going to assume that you’ve requested access to WordPress.org’s SVN repository, and you’ve found the admin panel and want to get your Xcode goodness hooked up to the WP SVN.

To get started create a new Empty Xcode project.

Screenshot of Xcode project chooser Empty XCode waiting for LINICKX LifeStream
Xcode project chooser Empty Project

From the menu bar select SCM then Configure Repositories, the window select the + to add a new repo, the username & password pair are your wordpress.org credentials, you can find the URL to your SVN repo on the wordpress.org site.

WordPress dot org Admin Interface
The WP.org admin interface

Next from the menu bar select SCM then Repositories, highlight the repo you’ve just created and choose checkout; you’re going to be asked for a folder to “save” the contents of the repo to, I chose inside my Xcode project folder.

Checking out with Xcode
Repo’ Config Code Checkout

You now need to add those “checked out” files to you project, in the tree on the left, right/control click the blue project icon at the top and select add existing files, accept the defaults and the repo should be imported.

Code imported
Imported Code

These files now in the project need to be associated with the repo, this is done by highlighting the blue project icon and clicking the “Info” button, then click “Configure Roots & SCM”; click the + button and choose your repo folder (again)… the dropdown on the right should automatically select the correct SCM.

Project LINICKX LifeStream Info WP Xcode Edit Project Root
Project Properties Project Roots

If you now change a file / add / delete / etc it will appear under the SCM tree, you can right/control click and commit to the repo…. job done :)

WP Xcode readme txt changed
Yay it works!

Very quickly you’re going to find out that you want to test your changes prior to commiting them, to do this you may want to copy your files upto a webserver…. I get Xcode to do that for me, using macfuse to mount my webroot via ssh but for this example I’ll create a directory on the desktop … you also need to create any subdirectories you may need.. I have to create “admin”.

To copy the files we’re use an Xcode target, from the menu bar choose Project then New Target then Copy Files Target, I called my new target CopyFile. Using the info button change the absolute path of the copy – e.g. /Users/Nick/Desktop/LL … now here I ran into a problem (suggestions welcome)… next I created extra copy build phases for each subdirectory. Control/right click your Target ( i.e CopyFiles) then choose Add, New Build Phase, New Copy Files Build Phase… I then set the absolute path of this “sub target” to /Users/nick/Desktop/LL/admin/ to represent my admin subdirectory.

Finally DRAG down the files into their correct target, all being well and a fair wind clicking “BUILD” will cause your files to be copied into your directory. You can now make changes, click build to test, and then commit them to subversion when you’re happy :)

WP Xcode - Finished
Finished!

The red sweater post that inspires this now talks about creating a RUN shortcut to automatically open a web browser for testing, however mine didn’t work… I got this error “The program being debugged is not being run“… suggestions to fix welcome!

Is Mac the Anti-Linux or the Answer?

So, I’ve been toying with the idea of buying a mac. Using WindowsXP is a no go for me, we’re just not friends; work haven’t yet rolled out Vista. I love linux, have been using it for years, and have upset many an I.T department by partitioning their loving-crafted standard Windows Build with my favourite flavour of linux but I’m getting the same old Gripes….

Hardware-Compatibility: Now don’t get me wrong, fedora has installed and pretty-much worked out of the box for years, but it’s the little niggles that get you, my hp nc6320 (company issued) has an intel wireless card, and quite frankly the fedora support is unreliable; if it’s not issues where by I can’t connect to hidden ssids, I can’t run leap, and even my broadcasted home wpa network can be a bit flakey (my n800 & ps3 use it fine so it’s definitely a laptop issue)…. top this off with the odd issue with graphics cards, very little support for mobile broadband, fingerpint authentication and it’s enough to drive anyone mad!

Work-Compatibility: Like most UK companies EVERYTHING has a windows focus, even down to the linux web-managed-appliances which have to be ie7 compatible. Open-office is great, but I can’t run the macro’s written by our marketing department (which format things) and even if I do manually make it look right the conversion to MS-Word is a bit “iffy”. Evolutions exchange-connector works most of the time, but archiving my mailbox from outlook screws it, changing my password (due to expiry) cause mail-notification to freak-out, and the built-in html formatting engine doesn’t set a font so if I reply to an HTML e-mail, all my text is in the nasty times roman.. and just another couple of points since I’m in full rant, share-point support in firefox! and what is everyone’s obsession is MSN and office communicator, what’s wrong with skype or google talk both of which have platform independent solutions. (Yes pidgin supports MSN, but it’s not feature complete)

So is a mac the answer? Those I’ve known an met whom own macs (and in the UK, unless you’re in media they’re few and far between) have all said “everything just works”… oh how I’ve longed for that… and the UI is nice, so all the compiz prettyness that I’ve gotten used to is kinda there. I’ve done some research, there’s an offical office for mac, which support exchange, there’s a communicator for LCS which includes msn support, there’s certianly more off the shelf software that supports mac than linux!

But is it out of the frying pan into the fire? Let’s look at why XP doesn’t work for me, 1stly the interface, it makes me feel unconfortable, I’ve tried themeing it, but that just covers up the bad colour scheme, themes ocasionally slow your machine down, some apps don’t accept the theme engine, and after-all you’re just painting a bad egg so even if it is easier on the eye the problems sill exist! All this aside, Vista is supposed to address the usability and eye-candy issues, so maybe I should be using that? So user-interfaces could be considered a shallow reason to choose your OS, and to be honest although how I interact with the PC is important (since it’s what I do for a living) it’s not what attracted me to linux in the 1st place. FREE, yes FREE is what attracts most of us to linux, windows licencing and cost is a nightmare, winzip & winrar are examples of stuff you expect to have as part of the OS, yes XP can open .zips but what about .tgz? … OK lets look at terminal emulation or ssh, finding a good one can be a problem putty is great but it’s a bit dis-jointed, the sftp function isn’t built into explorer tab’s is an extra add-on… what about the stuff you occasionaly use, so I re-size the odd image or convert .jpg to .png should I be paying for a tool I only use once a month, if I should, can I afford it?

The investment in a mac is not a small one, so my question is, can I get the best of both worlds? Can I buy the software I need, and download open-source alternative easily for the rest? Can I mix the “it just works” with the tech-tinkering that I’m used to? After purchasing a macbook, ms office for mac, vmware-fusion (I have vm-ware server on linux to run visio, I know this will be no-different on a mac) and topped that off with a backup-solution (work pay to backup windows, rsync does the job for linux) I’m going to have spent best part of £1,500… oh yeah this includes a special VGA cable so I can plug into a projector… apple are known for tying users in tightly, will that become my new bug-bear? which leads me to….

Is Mac the Anti-Linux?
Apple insist that their OS runs only on their hardware, the ipod only works with their software (itunes) and plays their music format, you need special cables to plug your laptop into a standard monitor/projector, the iphone only works with apples chosen provider… is all this restriction going to make things worse? Linux is about freedom, machine architectures range from pda’s to playstations, the interface that you use can easily be changed, nearly everything is open and if I were a programmer I could fix, change, anything I liked…. would I be jumping from complete democratic freedom to a dictatorship?

So there we have it, a million questions I just don’t know the answer to! I do know I don’t have a grand kicking about, so this won’t be something I tackle lightly, if I do I then have the politics at work to address, no booting into linux isn’t supported by IT, but the laptop is a standard-same-as-everyone-else-thingy if I bring in a shiny new apple it’s going to attract attention…. which will certainly upset someone! The windows of change are bring more macs to the UK, but is it just a fad? More thought is definitely needed, I just hope I can bring myself to a decision soon :)