note 125100 added to function.ssh2-exec
| From: | RainerPerske@php.net | Date: | Tue, 09 Jun 2020 14:50:31 +0000 |
| Subject: | note 125100 added to function.ssh2-exec | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214746@lists.php.net to get a copy of this message | ||
The following function can be used to read both stdout and stderr even if both streams contain
gigabytes of data. It solves most problems mentioned in other comments, like blocking, like further
using the existing connection etc.
function ssh2_run($ssh2,$cmd,&$out=null,&$err=null){
$result=false;
$out='';
$err='';
$sshout=ssh2_exec($ssh2,$cmd);
if($sshout){
$ssherr=ssh2_fetch_stream($sshout,SSH2_STREAM_STDERR);
if($ssherr){
# we cannot use stream_select() with SSH2 streams
# so use non-blocking stream_get_contents() and usleep()
if(stream_set_blocking($sshout,false) and
stream_set_blocking($ssherr,false)
){
$result=true;
# loop until end of output on both stdout and stderr
$wait=0;
while(!feof($sshout) or !feof($ssherr)){
# sleep only after not reading any data
if($wait)usleep($wait);
$wait=50000; # 1/20 second
if(!feof($sshout)){
$one=stream_get_contents($sshout);
if($one===false){ $result=false; break; }
if($one!=''){ $out.=$one; $wait=0; }
}
if(!feof($ssherr)){
$one=stream_get_contents($ssherr);
if($one===false){ $result=false; break; }
if($one!=''){ $err.=$one; $wait=0; }
}
}
}
# we need to wait for end of command
stream_set_blocking($sshout,true);
stream_set_blocking($ssherr,true);
# these will not get any output
stream_get_contents($sshout);
stream_get_contents($ssherr);
fclose($ssherr);
}
fclose($sshout);
}
return $result;
}
----
Server IP: 45.112.84.4
Probable Submitter: 103.51.166.36 (proxied: 109.91.241.218)
----
Manual Page -- http://php.net/manual/en/function.ssh2-exec.php
Edit -- https://master.php.net/note/edit/125100
Del: integrated -- https://master.php.net/note/delete/125100/integrated
Del: useless -- https://master.php.net/note/delete/125100/useless
Del: bad code -- https://master.php.net/note/delete/125100/bad+code
Del: spam -- https://master.php.net/note/delete/125100/spam
Del: non-english -- https://master.php.net/note/delete/125100/non-english
Del: in docs -- https://master.php.net/note/delete/125100/in+docs
Del: other reasons-- https://master.php.net/note/delete/125100
Reject -- https://master.php.net/note/reject/125100
Search -- https://master.php.net/manage/user-notes.php