简体   繁体   中英

Uploading files using SCP using phpseclib

I need to create 2 functions: one to upload files using SFTP and another using SCP. I'm using phpseclib and the put method; I believe I have the SFTP function done.

Now, I'm trying to do the SCP function. Per http://adomas.eu/phpseclib-for-ssh-and-scp-connections-with-php-for-managing-remote-server-and-data-exchange/ , it seems like the following are the things I need to do:

In case of SCP:
1. Including the needed file: include('/path/to/needed/file/Net/SFTP.php');
2. Creating object and making connection:
$sftp = new Net_SFTP('host');
if (!$sftp->login('user', 'password')) { exit('Login Failed'); }
3. Reading contents of a file: $contents=$sftp->get('/file/on/remote/host.txt');
4. Copying file over sftp with php from remote to local host: $sftp->get('/file/on/remote/host.txt', '/file/on/local/host.txt');
5. Copying file over sftp with php from local to remote host: $sftp->put('/file/on/remote/host.txt', '/file/on/local/host.txt');
6. Writing contents to remote file: $sftp->get('/file/on/remote/host.txt', 'contents to write');

I need to do #5, but it looks like what I did for SFTP. SFTP and SCP aren't the same, right? Is the same code correct? If not, how do I do SCP?

As noted by neubert, phpseclib has SCP support now through the Net_SCP class.

You instantiate an Net_SCP object by passing it a Net_SSH2 or Net_SSH1 object in the constructor, and can then use the get() and put() methods to download or upload files via SCP.

Here's a simple example script showing me SCPing a file from my local machine to a remote AWS instance.

<?php

    set_include_path(get_include_path() .
                     PATH_SEPARATOR .
                     '/home/mark/phpseclib');

    require_once('Crypt/RSA.php');
    require_once('Net/SSH2.php');
    require_once('Net/SCP.php');

    $key = new Crypt_RSA();
    if (!$key->loadKey(file_get_contents('my_aws_key.pem')))
    {
        throw new Exception("Failed to load key");
    }

    $ssh = new Net_SSH2('54.72.223.123');
    if (!$ssh->login('ubuntu', $key))
    {
        throw new Exception("Failed to login");
    }

    $scp = new Net_SCP($ssh);
    if (!$scp->put('my_remote_file_name',
                   'my_local_file_name',
                   NET_SCP_LOCAL_FILE))
    {
        throw new Exception("Failed to send file");
    }

?>

Yes, the SCP is completely different protocol to the SFTP.

The phpseclib now supports the SCP in recent versions (since version 0.3.5, released in June 2013).

Alternatively, use the PHP PECL SSH2 functions for SCP upload/download:
https://www.php.net/manual/en/ref.ssh2.php

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