微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用php和ssh2从sftp服务器获取文件

如何解决使用php和ssh2从sftp服务器获取文件

最近,对于一个项目,我一直在尝试使用 ssh2 扩展名和 PHP 从 sftp 网络服务器获取一些文件。到目前为止,我已经设法连接到服务器并列出特定目录中的所有文件,但是当我尝试使用 ssh2_scp_recv 获取它们时,我总是得到 “警告:ssh2_scp_recv():无法在...中接收远程文件”。我使用了另一种与 fread 一起工作的实现,但传输速度太慢,我需要更快的速度。

在我一直在研究的实现中,我尝试在循环中使用引用函数,将文件名/路径传递为:

ssh2_scp_recv($connection,"/download/file.json","C:\Users\User\file.json");

但没有运气。有没有人知道实现目标或超越这个问题的更好方法

编辑:

<?PHP

$url = 'server.url.com';
$port = 22;
$username = "username";
$password = "password";

// Make our connection
$connection = ssh2_connect($url);
 
// Authenticate
if (!ssh2_auth_password($connection,$username,$password)) throw new Exception('Unable to connect.');
 
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');

$localDir  = 'C:\Users\User';
$remoteDir = '/download';

// download all the files
$files    = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
      ssh2_scp_recv($connection,"$remoteDir/$file","$localDir\\$file");
    }
  }
}

?>

这是我正在使用的代码,我得到了这个输出

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

Warning: ssh2_scp_recv(): Unable to receive remote file in C:\xampp\htdocs\teste1.PHP on line 26

正如我所说,我怀疑问题可能出在我使用 Windows 时的 localdir 路径上,但不确定,因为我尝试了许多替代方法,但都没有奏效。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。