简体   繁体   中英

PHP parallel/asynchronous SSH connections

I'm trying to open multiple connections (various devices) to run a command and get the output. The problem is that i have to run them "all at once"/parallel. If i wait for one result and then to run the other one it takes way too long and with a large number of devices that can go very bad.

I'm also using curl which I know that there is curl_multi and I was wondering if there was something similar with SSH for php.

I'm using Net_SSH2 for now.

You'll need to use two PHP libraries: https://robo.li/tasks/Remote/#ssh and https://github.com/cheprasov/php-parallel . Your class method might be something similar to the example below:

function runParallelSSH() {

   $parallel = new Parallel(new ApcuStorage());

   foreach ($credentials as $user => $host) {
      $connection = sprintf('%s@%s', $user, $host);
      $connections[] = $connection;
      $Parallel->run($connection, function() {  
         $gitTask = $this->taskGitStack()
             ->checkout('master')
             ->pull();          
      });
   }

   $results = $parallel->wait($connections);

}

Without using thirdparties like curl_multi you have to use PHP multithreading, for this you need an extension pthreads.

Look in the docs for PHP threading

The most interesting feature is using it like this (code modified from PHP.net)

class My extends Thread {
    public function run() {
        //curl_exec whatever
    }
}
$my = new My();

//start as many as you need
$my->start();

//wait for the threads to finnish and join one thread at a time with main-process-thread:
var_dump($my->join());:

Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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