unstdio.org

Not your standard io.

Php-cli Awesomeness

| Comments

I know, command line line php has been forever and it’s nothing new. I have been coding in php for over 5 years now but not until recently have I needed to use to use it for something more than web application development. In the past couple months I have been using the amazon AWS environment. There are a ton of tools built for AWS and a very good API but I have found some things that I have needed to do that arn’t made easy. One example is duplicating or copying an EC2 security group. Do to some infrastructure changes we wanted to duplicate an already existing security group with only minor changes. In our case the security group had a lot of custom firewall rules that would take too long to duplicate. So here is a script to copy EC2 groups:

<?php

echo "\n";

echo "#######################\n";

echo "Copy EC2 Security Group\n";

echo "#######################\n";

echo "\n";

echo "Enter security group you want to copy FROM: ";

$handle = fopen ("php://stdin","r");

$grp1 = fgets($handle);

$grp1 = trim($grp1);

echo "\n";

echo "Enter security group you want to copy TO: ";

$handle = fopen ("php://stdin","r");

$grp2 = fgets($handle);

$grp2 = trim($grp2);

echo "\n";

echo "You are going to copy settings from ".$grp1." to ".$grp2." Is this correct? (y/n):";

$handle = fopen ("php://stdin","r");

$response = fgets($handle);

$response = trim($response);

//echo $response;

if($response == 'y'){

echo "Getting settings from ".$grp1."...\n";

$cmd = "ec2-describe-group ".$grp1;

exec($cmd, $lines);

echo "Copying group settings...\n";

foreach($lines as $line){

//echo $line."\n";

$values = explode("\t",$line);

//foreach($values as $value){

//echo $value."\n";

//}

if(isset($values[4])){

if($values[4] == "icmp"){

$cmd = "ec2-authorize ".$grp2." -P icmp ".$values[5].":".$values[6]." -u ".$values[1]." -o ".$values[11];

//echo $cmd;

exec($cmd);

}elseif($values[4] == "tcp"){

if(isset($values[10])){

$cmd = "ec2-authorize ".$grp2." -P tcp -p ".$values[5]." -u ".$values[1]." -o ".$values[11];

//echo $cmd."\n";

exec($cmd);

}else{

$cmd = "ec2-authorize ".$grp2." -P tcp -p ".$values[5]." -s ".$values[9];

//echo $cmd."\n";

exec($cmd);

}

}elseif($values[4] == "udp"){

if(isset($values[10])){

$cmd = "ec2-authorize ".$grp2." -P udp -p ".$values[5]." -u ".$values[1]." -o ".$values[11];

//echo $cmd."\n";

exec($cmd);

}else{

$cmd = "ec2-authorize ".$grp2." -P udp -p ".$values[5]." -s ".$values[9];

//echo $cmd."\n";

exec($cmd);

}

}

}

}

}else{

echo "quit";

exit;

}

?>