'How do I force PHP to load without waiting for ssh2
Currently I have a script that uses SSH2 to execute a c program on a server, however the webpage takes the x seconds to load that the script waits. Is there a way to make php send the command through ssh and not wait for the response? Thanks My current code:
<?php
$ssh = ssh2_connect('********', 22);
ssh2_auth_password($ssh, 'root', '**********');
$stream = ssh2_exec($ssh, './sr1 80 4 400 400 20');
fclose($stream);
?>
(Censored server IP and Password for obvious reasons)
Solution 1:[1]
Using http://phpseclib.sourceforge.net/ ...
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('********', 22);
$ssh->login('root', '**********');
$ssh->enablePTY();
$ssh->exec('nohup ./sr1 80 4 400 400 20 &');
You can try it with and without the nohup and & but my guess is that they're necessary.
Solution 2:[2]
You can run your code in a Thread in order to run it asynchronously:
<?php
class MySsh extends Thread {
public function run() {
$ssh = ssh2_connect('********', 22);
ssh2_auth_password($ssh, 'root', '**********');
$stream = ssh2_exec($ssh, './sr1 80 4 400 400 20');
fclose($stream);
}
}
$mySsh = new MySsh();
var_dump($mySsh->start());
?>
Note that to use Threads in php, you need to have the pthreads library installed.
Solution 3:[3]
ssh2_connect, ssh2_auth_password is required for ssh login.
ssh2_exec execute the command given second argument './sr1'. Can you please provide what exactly it does with snippets ?
Secondly, ssh2_exec : Execute a command on a remote server. and I think it will wait for your command to complete the execution and then return.
Can you try using ssh2_shell : Request an interactive shell
You can probably, open shell and invoke your command to run background or in different process and exit from shell. I think it can be more faster then ssh2_exec.
Solution 4:[4]
it works for me:
$connection = ssh2_connect('host', 22);
ssh2_exec($connection, "screen -dmS 'sr-script' ./sr1 80 4 400 400 20 2>&1");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | guruarena |
| Solution 2 | |
| Solution 3 | Sujal Sheth |
| Solution 4 | DividerBeam |
