简体   繁体   English

从 php 执行 shell 脚本

[英]execute shell script from a php

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.在我的服务器中,我只需要输入:ssh username@distant_device 命令,我就会得到它的结果。 So i want to do this throught a php page.所以我想通过一个 php 页面来做到这一点。

I tried different methods and it didn't work for me.我尝试了不同的方法,但对我不起作用。

1 - 1 -

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

2 - executing shell script in the server 2 - 在服务器中执行 shell 脚本

script.sh :脚本.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.我得到了我的脚本发送的结果,但不是其中的 ssh 命令的结果。 When i execute the script directly i have the result.当我直接执行脚本时,我得到了结果。

3- 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例如,您可以使用shell_exec()

$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 :) Php 有一个很好的文档http://php.net/manual/en/function.shell-exec.php希望它有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM