简体   繁体   中英

How can I configure an SCP/SFTP file storage?

My Laravel application should copy files to another remote host. The remote host is accessible only via SCP with a private key. I would like to configure a new file storage ( similarly as FTP ), but I have found no information, how to define an SCP driver.

You'll need to install the SFTP driver for Flysystem, the library Laravel uses for its filesystem services:

composer require league/flysystem-sftp

Here's an example configuration that you can tweak. Add to the disks array in config/filesystems.php :

'sftp' => [
    'driver' => 'sftp',
    'host' => 'example.com',
    'port' => 21,
    'username' => 'username',
    'password' => 'password',
    'privateKey' => 'path/to/or/contents/of/privatekey',
    'root' => '/path/to/root',
    'timeout' => 10,
]

Extend Laravel's filesystem with the new driver by adding the following code to the boot() method of AppServiceProvider (or other appropriate service provider):

use Storage;
use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;
...
public function boot()
{
    Storage::extend('sftp', function ($app, $config) {
        return new Filesystem(new SftpAdapter($config));
    });
}

Then you can use Laravel's API as you would for the local filesystem:

Storage::disk('sftp')->put('path/filename.txt', $fileContents);

Now, official documentation has instructions for SFTP connection: https://laravel.com/docs/8.x/filesystem#sftp-driver-configuration

SFTP: composer require league/flysystem-sftp "~1.0"

SFTP Driver Configuration Laravel's Flysystem integrations work great with SFTP; however, a sample configuration is not included with the framework's default filesystems.php configuration file. If you need to configure an SFTP filesystem, you may use the configuration example below:

'sftp' => [
        'driver' => 'sftp',
        'host' => 'example.com',
        'username' => 'your-username',
        'password' => 'your-password',
    
        // Settings for SSH key based authentication...
        'privateKey' => '/path/to/privateKey',
        'password' => 'encryption-password',
    
        // Optional SFTP Settings...
        // 'port' => 22,
        // 'root' => '',
        // 'timeout' => 30,
    ],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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