1

I'm trying to get some commands executed on a distant device. I'm using public and private key to connect to distant device.

In my server i have just to type : ssh username@distant_device command and i get the result of it. So i want to do this throught a php page.

I tried different methods and it didn't work for me.

1 -

 $cmdline = escapeshellcmd("ssh username@distant_device command");
 system($cmdline);

2 - executing shell script in the server

script.sh :

#!/bin/bash

output=$(ssh username@distant_device command)
echo "$output" >> test.txt

exit 0

php code :

passthru('./script.sh',$result);
echo $result ;

I got result sending by my script but not the result of the ssh command in it. When i execute the script directly i have the result.

3-

system ("ssh username@distant_device command > test.txt");
system ("ssh -i /home/nagios/.ssh/id_rsa -o 'StrictHostKeyChecking no' username@distant_device command' > test.txt");

text file remain empty

What i'am doing wrong ?

2 Answers 2

1

I found a solution, here it is :

$host = "ip_address"; 
$port = 22; 
$conn = ssh2_connect($host, $port); 
$username = "username"; 
$pub_key = "/path/to/key/.ssh/id_rsa.pub"; 
$pri_key = "/path/to/key/.ssh/id_rsa"; 
if(ssh2_auth_pubkey_file( 
    $conn, 
    $username, 
    $pub_key, 
    $pri_key)) 
{ 
    echo "Authentication succeeded";
    $stdout_stream = ssh2_exec($conn, 'ping ip_address rapid routing-instance XXXXXXXXX');
    sleep(1);
    stream_set_blocking($stdout_stream, true);
    $stream_out = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDIO);
    echo '<pre>';
    echo stream_get_contents($stream_out);
    echo '</pre>';

} 
else 
{ 
   echo "Authentication failed "; 
} 
Sign up to request clarification or add additional context in comments.

Comments

0

You can use shell_exec() for example

$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";

Php has a good documentation on it http://php.net/manual/en/function.shell-exec.php hope it helps :)

1 Comment

i got the same empty result :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.