0
场景:我需要一个函数来获取通过SSH异步运行的命令的STDOUT
。这有很多用途,包括(最重要的)通过SSH读取文件。 这个函数的一个重要特性是它是异步的,因此我可以显示从服务器返回的输出(或者估算文件下载进度)。这与使用ssh_move()
下载文件的常见方法不同。PHP fread ssh流显着慢
function ssh_exec($dsn, $cmd, $return=true, $size_est=null){
$BUFFER_SIZE = $return ? (1024 * 1024) : 1;
debug('ssh2_exec '.$cmd);
$stream = ssh2_exec(ssh_open($dsn), $cmd);
debug('stream_set_blocking');
stream_set_blocking($stream, true);
debug('ssh2_fetch_stream');
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
stream_set_blocking($stream_out, true);
debug('stream_get_contents');
$data = ''; $stime = $oldtime = microtime(true); $data_len = 0;
if(!$return){
write_message("\033[0m".' Execution Output:'.PHP_EOL.' ');
}
while(!feof($stream_out)){
$buff = fread($stream_out, $BUFFER_SIZE);
if($buff===false)throw new Exception('Unexpected result from fread().');
if($buff===''){
debug('Empty result from fread()...breaking.');
break;
}
$data .= $buff;
if($return){
$buff_len = strlen($buff);
$data_len += $buff_len;
$newtime = microtime(true);
debugo('stream_get_contents '.bytes_to_human($data_len)
.' @ '.bytes_to_human($buff_len/($newtime - $oldtime)).'/s'
.' ['.($size_est ? number_format($data_len/$size_est * 100, 2) : '???').'%]');
$oldtime = $newtime;
}else{
echo str_replace(PHP_EOL, PHP_EOL.' ', $buff);
}
}
if($return){
debugo('stream_get_contents Transferred '.bytes_to_human(strlen($data)).' in '.number_format(microtime(true) - $stime, 2).'s');
return $data;
}
}
用途:该功能用于像这样:
$dsn = 'ssh2.exec://root:[email protected]/';
$size = ssh_size($dsn, 'bigfile.zip');
$zip = ssh_exec($dsn, 'cat bigfile.zip', true, $size);
注1:的一些非标准的功能的说明:
debug($message)
- 写入调试消息控制台。ssh_open($dsn)
- 接收SSH URI并返回SSH连接句柄。bytes_to_human($bytes)
- 字节到人类可读的格式的数字转换(例如:6GB)debugo($message)
- 同为debug()
但重写最后一行。
注2:参数$size_est
在进度指示器被使用;通常你首先得到文件大小,然后尝试下载它(如我的例子)。它是可选的,因此当您只想运行SSH命令时可以忽略它。
问题:通过scp [email protected]:/bigfile.zip ./
运行相同的下载操作时,我得到速度可达1Mb/s的,而这个剧本似乎限制在70KB/S。我想知道为什么以及如何改善这一点。
编辑:此外,我想知道如何/如果$BUFFER_SIZE
有任何区别。