0

我必须通过 SFTP 文件从服务器上传到另一个

这是我的 sftp() 函数:

function transfert_curl_sftp($local_filename, $distant_filename, $host_destination, $user_destination,$pubkey_filename,$privkey_filename,$port) {
if ( !extension_loaded('curl') ) return 'no_curl_extension';
$distant_filename = ltrim($distant_filename,'/');

$fp = fopen($local_filenam, 'r');
$sftp_server = $host_destination.'/'.$distant_filename;
$curl = curl_init();
curl_setopt($curl, CURLOPT_UPLOAD, TRUE);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_SFTP); 
curl_setopt($curl, CURLOPT_NOPROGRESS, FALSE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);

$trace = tempnam( dirname($local_filenam),'temp_curl_' );
$fptrace = fopen($trace, 'w');
curl_setopt($curl, CURLOPT_FILE, $fptrace);
curl_setopt($curl, CURLOPT_STDERR, $fptrace);

curl_setopt($curl, CURLOPT_URL, 'sftp://@'.$sftp_server);
curl_setopt($curl, CURLOPT_PORT, $port);
curl_setopt($curl, CURLOPT_USERPWD, $user_destination.':');
curl_setopt($curl, CURLOPT_SSH_PUBLIC_KEYFILE, $pubkey_filename);
curl_setopt($curl, CURLOPT_SSLENGINE, '');
curl_setopt($curl, CURLOPT_SSLKEY, $privkey_filename);
curl_setopt($curl, CURLOPT_SSLKEYPASSWD, '');

curl_setopt($curl, CURLOPT_INFILESIZE, filesize($local_file));
curl_setopt($curl, CURLOPT_INFILE, $fp);

$info = curl_getinfo($curl);
$start_error_no = curl_errno($curl);
$valid_operation = curl_exec($curl);   
$final_error_no = curl_errno($curl);
curl_close($curl);
fclose($fp);
fclose($fptrace);

echo '<pre>trace:',file_get_contents($trace),'<hr>'; var_dump($start_error_no,$valid_operation,$final_error_no);

return true;
}

该文件永远不会上传:-(

当我查看跟踪文件时,我看到* SSH 身份验证方法可用:公钥、密码 * 使用 ssh 公钥文件 /var/www/xxx/yyy/upload/dsa-zzz.pub * 使用 ssh 私钥文件 id_dsa * SSH 公钥身份验证失败:回调返回错误* 所以我认为'CURLOPT_SSLKEY'参数没有真正设置......我所有的关键文件都可以阅读......

它是一个 PHP 错误吗?还是我写东西失败了?

4

1 回答 1

1

SFTP 协议使用 SSH2 来保护连接,因此您需要提供 SSH 私钥,而不是 SSL 的。SSH 和 SSL 是保护连接的 2 种不同方法(有关它们区别的更多详细信息)。

所以你应该更换:

curl_setopt($curl, CURLOPT_SSLENGINE, '');
curl_setopt($curl, CURLOPT_SSLKEY, $privkey_filename);
curl_setopt($curl, CURLOPT_SSLKEYPASSWD, '');

经过 :

curl_setopt($curl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PUBLICKEY);
curl_setopt($curl, CURLOPT_SSH_PUBLIC_KEYFILE, $pubkey_filename); // you already did it
curl_setopt($curl, CURLOPT_SSH_PRIVATE_KEYFILE, $privkey_filename);
curl_setopt($curl, CURLOPT_KEYPASSWD, '');
于 2013-05-02T16:56:15.247 回答