Question

I want to execute a command on a remote machine and store the out of that command in a variable using php

Here is what i tried

$command = 'exec("whoami")';
$connection = ssh2_connect($ip,$port); 
ssh2_auth_password($connection,$user,$pass); 
$test = ssh2_shell($connection,$command); 
echo $test; 

According to me $test should output root However nothing is return , I am sure i am missing something..... php-pecl-ssh2 is already installed and no error is returned

Was it helpful?

Solution

I guess your command is incorrect :

$command = 'whoami';

And you should also add this 2 lines to the end to get your output :

if ( $connection = ssh2_connect($ip,$port) ) {
    echo 'Error occured while connecting to server via ssh';
}
if (!ssh2_auth_password($connection,$user,$pass)) {
    echo 'Error occured while authenticating via ssh';
}
if(!$test = ssh2_shell($connection,$command)){
    echo 'Error occured while executing remote command via ssh';
} else {
    stream_set_blocking($test, true);
    echo stream_get_contents($test);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top