How to run local bash script on remote server using php
<p>I store bash script as a string in db and I need to call it on user demand. Script should be executed on remote machine from php level. I found the following topics:</p>

<p>Two topics about ssh connection and calling remote script:</p>

<ol>
<li><a href="https://stackoverflow.com/questions/305035/how-to-use-ssh-to-run-shell-script-on-a-remote-machine">How to use SSH to run a shell script on a remote machine?</a></li>
<li><a href="https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password">https://serverfault.com/questions/241588/how-to-automate-ssh-login-with-password</a></li>
</ol>

<p>And two ways to use it in php:</p>

<ol>
<li><a href="https://stackoverflow.com/questions/11052162/run-bash-command-from-php">Run Bash Command from PHP</a></li>
<li><a href="https://stackoverflow.com/questions/12086474/get-result-from-ssh2-exec">get result from ssh2_exec</a> ,
<a href="http://php.net/manual/en/function.ssh2-exec.php" rel="nofollow noreferrer">http://php.net/manual/en/function.ssh2-exec.php</a></li>
</ol>

<p>I tried to use the following code in my symfony2 application:</p>

<p>First attempt:</p>

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

<p>Second:</p>

<pre><code>$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' &lt; test");
chdir($old_path);

or

$old_path = getcwd();
chdir('/path_to_script_directory');
$output = shell_exec("ssh user@server 'bash -s' &lt; ".$script);
chdir($old_path);
//result =&gt; output = null
</code></pre>

<p>As in examples above I tried two cases with "test" script and string script ($script variable). Second option is preffered by me. Both cases contains simple script:</p>

<pre><code>#!/bin/bash

ifconfig
</code></pre>

<p>Thank you in advance!</p>