我尝试将所有文件从SFTP文件夹移动到本地文件夹。
我使用以下脚本:
$connection = ssh2_connect('x.x.x.x', 22);
if (!ssh2_auth_password($connection, 'User_login', 'User_Pass')) {
throw new Exception('Impossible de ce connencter.');
}
if (!$sftp = ssh2_sftp($connection)) {
throw new Exception('Impossible de ce connencter.');
}
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp/01_Folder/");
while (false !== ($file = readdir($dirHandle))) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
谢谢大家。
答案 0 :(得分:2)
您可以使用exec函数从Php运行rsync。它会询问您远程服务器的用户名和密码。您可以使用SSHPass命令行工具绕过它。它允许非交互式登录。以下命令使用sshpass运行rsync:
rsync --rsh="sshpass -p myPassword ssh -l username" server.example.com:/var/www/html/ /backup/
可以使用exec函数
从Php运行该命令答案 1 :(得分:1)
如果要将所有文件从SFTP目录下载到本地目录 - local ,从PHP脚本开始(如果这就是你所谓的“em>”FTP服务器“):
$connection = ssh2_connect('sftp.example.com');
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$dirhandle = opendir("ssh2.sftp://$sftp/remote/folder/");
while (false !== ($file = readdir($dirhandle)))
{
if (($file != '.') && ($file != '..'))
{
$remotehandle = fopen("ssh2.sftp://$sftp/remote/folder/$file", 'r');
$localhandle = fopen("/local/folder/$file", 'w');
stream_copy_to_stream($remotehandle, $localhandle);
fclose($remotehandle);
fclose($localhandle);
}
}
添加错误检查!
答案 2 :(得分:1)
感兴趣的人的解决方案==>
//connecxion
$connection = ssh2_connect('remote.server.com', 22);
// Authentication
if (!ssh2_auth_password($connection, 'Login_user', 'Password')) {
throw new Exception('Impossible de ce connencter.');
}
// Creation de la source SFTP
if (!$sftp = ssh2_sftp($connection)) {
throw new Exception('Impossible de ce connencter.');
}
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp/Remote_folder/");
while (false !== ($file = readdir($dirHandle))) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
if (count($files)) {
foreach ($files as $fileName) {
// Dossier Change
if (!$remoteStream = @fopen("ssh2.sftp://$sftp/Remote_folder/$fileName", 'r')) {
throw new Exception("Unable to open remote file: $fileName");
}
// Dossier Local
if (!$localStream = @fopen("/local_folder/$fileName", 'w')) {
throw new Exception("Unable to open local file for writing: /var/www/change_files/$fileName");
}
// Ecriture du dossier change dans le dossier Local
$read = 0;
$fileSize = filesize("ssh2.sftp://$sftp/Remote_folder/$fileName");
while ($read < $fileSize && ($buffer = fread($remoteStream, $fileSize - $read))) {
$read += strlen($buffer);
// Ecriture du dossier
if (fwrite($localStream, $buffer) === FALSE) {
throw new Exception("Unable to write to local file: /local_folder/$fileName");
}
}
// Fermeture des Connexions
fclose($localStream);
fclose($remoteStream);
}
}