【问题标题】:execute shell script from a php从 php 执行 shell 脚本
【发布时间】:2016-07-02 16:02:34
【问题描述】:

我正在尝试在远程设备上执行一些命令。我正在使用公钥和私钥连接到远程设备。

在我的服务器中,我只需输入:ssh username@distant_device 命令,我就会得到它的结果。所以我想通过一个 php 页面来做到这一点。

我尝试了不同的方法,但对我不起作用。

1 -

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

2 - 在服务器中执行 shell 脚本

脚本.sh:

#!/bin/bash

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

exit 0

php 代码:

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

我收到了脚本发送的结果,但没有收到其中的 ssh 命令的结果。当我直接执行脚本时,我得到了结果。

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");

文本文件保持为空

我做错了什么?

【问题讨论】:

    标签: php shell ssh


    【解决方案1】:

    我找到了解决办法,这里是:

    $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 "; 
    } 
    

    【讨论】:

      【解决方案2】:

      例如,您可以使用shell_exec()

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

      Php 上有一个很好的文档http://php.net/manual/en/function.shell-exec.php 希望对你有帮助:)

      【讨论】:

      • 我得到了同样的空结果:(