如何使用php在远程服务器上运行本地bash脚本

时间:2016-07-23 19:50:27

标签: php bash ssh

我将bash脚本存储为db中的字符串,我需要根据用户需求调用它。脚本应该从php级别在远程机器上执行。我找到了以下主题:

关于ssh连接和调用远程脚本的两个主题:

  1. How to use SSH to run a shell script on a remote machine?
  2. https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password
  3. 在php中使用它的两种方法:

    1. Run Bash Command from PHP
    2. get result from ssh2_exechttp://php.net/manual/en/function.ssh2-exec.php
    3. 我尝试在symfony2应用程序中使用以下代码:

      首次尝试:

      $connection = ssh2_connect('IP_ADDRESS', 22);
      ssh2_auth_password($connection, 'user', 'password');
      $stream = ssh2_exec($connection, "'bash -s' < ".$script);
      stream_set_blocking($stream, true);
      $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
      $output = stream_get_contents($stream_out);
      //result => output = empty string
      

      第二

      $old_path = getcwd();
      chdir('/path_to_script_directory');
      $output = shell_exec("ssh user@server 'bash -s' < test");
      chdir($old_path);
      
      or
      
      $old_path = getcwd();
      chdir('/path_to_script_directory');
      $output = shell_exec("ssh user@server 'bash -s' < ".$script);
      chdir($old_path);
      //result => output = null
      

      如上例所示,我尝试了两个案例&#34; test&#34;脚本和字符串脚本($ script变量)。第二个选项由我提供。两种情况都包含简单的脚本:

      #!/bin/bash
      
      ifconfig
      

      提前谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个项目,可以在远程服务器上为您提供真正的bash shell:https://github.com/merlinthemagic/MTS

安装并运行以下命令:

//login to the remote server and get a shell:

$shellObj       = \MTS\Factories::getDevices()->getRemoteHost('ip_address')->setConnectionDetail('username', 'password')->getShell();

//rather than executing your script, just run the command:

$returnData = $shellObj->exeCmd("ifconfig");

echo $returnData; //string containing the interface config of the remote server.