简体   繁体   English

如何使用 Magento 2 中的 sftp 将文件从一台服务器传输到另一台服务器?

[英]How to transfer file from one server to another using sftp in Magento 2?

I want to transfer all the images associated to that product from M1 to M2 using sftp.我想使用 sftp 将与该产品相关的所有图像从 M1 传输到 M2。 I can connect to M1 using sftp.我可以使用 sftp 连接到 M1。 But I am not getting how to transfer it.但我不知道如何转移它。

Here is a code to connect with sftp -这是与 sftp 连接的代码 -

//FTP Connection
public function connectFtp($host, $user, $password, $ssl=true, $passive=true){
        return $connect = $this->sftp->open(
            array(
                'host'      =>  $host,
                'user'      =>  $user,
                'password'  =>  $password,
                'ssl'       =>  $ssl,
                'passive'   =>  $passive
            )
        );
    }

//Downlaod images from M1 and transfer to M2 temp folder
    public function downloadImages($images){
        //Connecting to M1
        $connect = $this->connectFtp(SELF::M1_HOST, SELF::M1_USERNAME, SELF::M1_PASSWORD, SELF::M1_SSL, SELF::M1_PASSIVE);
        if($connect){
           /* Code to transfer */
        }
    }

How to achieve this file transfer?如何实现这种文件传输? As per some project requirements, we don't want to use any plugin.根据一些项目要求,我们不想使用任何插件。

Do you just want to transfer ALL the images from M1 to M2?您是否只想将所有图像从 M1 传输到 M2?

You can try to rsync the images across instead:您可以尝试将图像重新同步:

rsync user@m1.host:/path/to/copy user@m2.host:/path/to/copy

Working code for File transfer from SFTP server to Our Server.从 SFTP 服务器到我们的服务器的文件传输的工作代码。

  $sftp = $obj->create('Magento\Framework\Filesystem\Io\Sftp');
  $open =  $sftp->open(
       array(
           'host' => $sftp_hostname,
           'username' => $sftp_username,
           'password' => $sftp_password,
           'port'=>$sftp_port
       )
    );

    try{
        // Change directory and move to require directory
        $sftp->cd('/enter_your_sftp_file_path_here/');

        //Fetching/Listing all the files.
        $sftp_server_files = $sftp->ls();

        //File path to put files from SFTP Server to our local server
        $filepath = $dir->getRoot() . '/var/import/inventory/';

        foreach ($sftp_server_files as $file) {

            //Copy files from server
            $source = $file['text'];
            if(strpos($source, 'zip') !== false){
                $destination = $filepath.$source;
                $result = $sftp->read($source, $destination);
                if($result == 'true') {
                   $message[] = 'File read from SFTP server : '.$source;
                }
                else
                {
                  $message[] = 'File not able to read from SFTP server : '.$source;
                }
            }
        }
    } catch ( Exception $e) {
        echo $e->getMessage();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM