通过SSH隧道使用gzip压缩包很快.比纯scp更快的速度,特别是对于许多小文件.以下是linux命令行的示例:
user@local# cd /source/ ; tar czf – * | ssh user@remote “cd /target/ ; tar xzf -“
更新:根据要求,这里你使用一个纯PHP解决方案 – 有一些乐趣摆弄这个棘手的位.
注意:您需要PHPs libssh extension才能工作.此外,STDIN似乎仅在使用SSH的流包装器时可用.
这几乎没有开销,因为它直接在流上运行,并且您的CPU很可能总是比您用于传输的网络链接更快.
要交换网络与CPU速度,可以从命令行中删除选项-z. (CPU使用率更低,但线路上的数据更多)
代码示例:
$local_cmd = "cd /tmp/source && tar -czf - *";
$remote_cmd = "tar -C /tmp/target -xzf -";
$ssh = new SSH_Connection('localhost');
$auth = $ssh->auth_password('gast', 'gast');
$bytes = $ssh->command_pipe($local_cmd, $remote_cmd);
echo "finished: $bytes bytes of data transfered\n";
class SSH_Connection {
private $link;
private $auth;
function __construct ($host, $port=22) {
$this->link = @ssh2_connect('localhost', 22);
}
function auth_password ($username, $password) {
if (!is_resource($this->link))
return false;
$this->auth = @ssh2_auth_password($this->link, $username, $password);
return $this->auth;
}
function command_pipe ($localcmd, $remotecmd) {
if (!is_resource($this->link) || !$this->auth)
return false;
// open remote command stream (STDIN)
$remote_stream = fopen("ssh2.exec://{$this->link}/$remotecmd", 'rw');
if (!is_resource($remote_stream))
return false;
// open local command stream (STDOUT)
$local_stream = popen($localcmd, 'r');
if (!is_resource($local_stream))
return false;
// connect both, pipe data from local to remote
$bytes = 0;
while (!feof($local_stream))
$bytes += fwrite($remote_stream,fread($local_stream,8192));
// close streams
fclose($local_stream);
fclose($remote_stream);
return $bytes;
}
function is_connected () { return is_resource($this->link); }
function is_authenticated () { return $this->auth; }
}