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 ?
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 ";
}
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 :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.