Techno Logica


Monday, August 25, 2014

Use PHP and SSH to execute command on remote machine


I had a requirement of executing commands on remote machine. I needed to execute commands in both Windows and Linux platforms. There are a wide variety of communication softwares out there who can help you with this. But, I choose SSH as a communication protocol for my requirement.

Linux comes loaded with ssh enabled and for windows we can have cygwin ssh installed. This was perfect, I will have to only configure the windows based OS. 

My requirement was to trigger it using a web page, so i used php for my server processing. After some trial and error - phpseclib worked out great!!

The official link to the tutorial : http://phpseclib.sourceforge.net/ 

Below code will give you a head start:

set_include_path(get_include_path().'\phpseclib');
include('Net/SSH2.php');
include('Net/SFTP.php');

define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);

echo "\r\n========= Open Communication ==========\r\n";
//Open SSH Communication
$ssh = new Net_SSH2($server);
//$key = new Crypt_RSA();
//$key->loadKey(file_get_contents('privatekey'));

if (!$ssh->login($username, $password)) {
//if (!$ssh->login($username, $key)) {
    echo "\r\n Error Occured while logging in...\r\n";
    //echo "Username:$username\r\n";
    //echo "Password:$password\r\n";
exit(1);
}
echo "\r\n Successfully Opened SSH Communication...";

$cmd = "your_command";
$arg1 = "your_arg_1";
$command = 'perl '.$cmd.' '.$arg1;

//Adding the below code to get proper command return code
$command .= ';echo "[return_code:$?]"';
echo "\r\n". $command;

//Executing the command
$output = $ssh->exec($command);

//Extract Return code
preg_match( '/\[return_code:(.*?)\]/', $output, $match );
$return_code = $match[1];
echo "\r\n". $output;
echo "\r\n".$return_code;

if(($return_code != 0))
{
echo "\r\n Command Failed";
}
else
{
echo "\r\n Command Pass";
}
?>

No comments: