title: PHP SSH multiple commands
body: <p>I am trying to build a ssh script to run multiple commands on a host. My goal is get the output of each command. My target host is a cisco router and for the following script to execute more that one command i need to run it for each command i want to execute which is not a very elegant solution.</p>
  
  <pre><code>$cmd = array ('sh run int te 1/1', 'sh run int te 1/2');
  
  for ($i = 0; $i &lt;= 1; $i++) {
      $connection = ssh2_connect('10.1.1.1', 22);
      ssh2_auth_password($connection, 'user', 'pass');
      $stream = ssh2_exec($connection, $cmd[$i]);
      stream_set_blocking($stream, true);
      $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
      echo stream_get_contents($stream_out); }
  </code></pre>
  
  <p>I have created a loop because i was unable to get the output for each command in the same stream. Since i guess that the php is terminating the ssh connections at the end of each stream. </p>
  
  <p>What i would like to achieve is to execute several commands and get the output in the same stream (if posible). </p>
  
  <p>I am editing the post to answer the sugestions made by @Melvin Koopmans and @LSerni.</p>
  
  <p>if i change the code as sugested (this was someting i also tried before) the second command returns an error. here is the cli output:
  the script changed:</p>
  
  <pre><code>$cmds = array ('sh run int te 1/1', 'sh run int te 1/2');
  
  $connection = ssh2_connect('10.1.1.1', 22);
  ssh2_auth_password($connection, 'user', 'pass');
  
  foreach ($cmds as $cmd) {
      $stream = ssh2_exec( $connection, $cmd );
      stream_set_blocking( $stream, true );
      $stream_out = ssh2_fetch_stream( $stream, SSH2_STREAM_STDIO );
      echo stream_get_contents($stream_out);}
  </code></pre>
  
  <p>the output from cli</p>
  
  <pre><code>interface TenGigabitEthernet1/1
  description trunk
  switchport trunk allowed vlan 1,2,3,4,5,6,10
  switchport mode trunk
  auto qos trust
  storm-control broadcast include multicast
  storm-control broadcast level 1.00
  spanning-tree guard loop
  service-policy input AutoQos-4.0-Input-Policy
  service-policy output AutoQos-4.0-Output-Policy
  ip dhcp snooping trust
  end
  
  PHP Warning:  ssh2_exec(): Unable to request a channel from remote host       in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 13
  PHP Warning:  stream_set_blocking() expects parameter 1 to be resource, boolean given in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 14
  PHP Warning:  ssh2_fetch_stream() expects parameter 1 to be resource, boolean given in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 15
  PHP Warning:  stream_get_contents() expects parameter 1 to be resource, null given in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 16
  </code></pre>
  
  <p>I am only getting the output from the first command "sh run int te 1/1".</p>