| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Monday, September 28, 2009

Making a Bash Script into a Web App

I recently wrote a nice little bash script at work that would check to see if a specified bit of information had been properly propagated through several tracking systems. It reduced about 10 minutes of work to about 30 seconds and I was thrilled to have extra time to sip my coffee. When I showed it off to my boss, he said, "Cool, but can you make it a web app?"

After a bit of digging, I figured it out and it's remarkably simple. Here's what you'll need:
  1. A web server capable of running PHP. I'm rocking XAMPP.
  2. A functioning bash script. Just make sure it's working when you run it from the command line. The output you see there is what you'll see when it's been web-app'd.
For the purposes of this article, I'll post a simple bit of PHP that will produce a web app version of ping. This code can be easily modified to display the output of any Bash command on a web page.
<html>
<head>
<title>Web Ping</title>
<style type='text/css'>
pre {
background:black;
border:1px lime solid;
color:lime;
}
td {
font-family:monospace;
}
</style>
</head>
<body>
<?php

# clean the strings to prevent injection attacks
$BADCHARS='/[^\.\w]/';
$HOST=preg_replace($BADCHARS, '', $_GET['host']);
$C=preg_replace($BADCHARS, '', $_GET['c']);
$I=preg_replace($BADCHARS, '', $_GET['i']);

if ($I=="") { $I=1; } # assign default values
if ($C=="") { $C=4; } # assign default values

if ($HOST!="") { # this is where the magic happens
echo '<pre>';
$last_line = system('/bin/ping '.$HOST.' -c '.$C.' -i '.$I, $retval);
echo '</pre>';
}

?>
<form action='ping.php' method='get'>
<table>
<tr>
<td>Hostname/IP:</td><td><input type='text' name='host' value='<?php echo $HOST ?>'/></td>
</tr>
<tr>
<td>count:</td><td><input type='text' name='c' value='<?php echo $C ?>' /></td>
</tr>
<tr>
<td>interval:</td><td><input type='text' name='i' value='<?php echo $I ?>' /></td>
</tr>
<tr>
<td colspan='2'>
<input type='submit' value='Ping It' /><br><br><br>
</td>
</tr>
</table>
</form>
</body>
</html>


Enjoy!

0 comments: