Uploading files using SCP using phpseclib

snoopy76 picture snoopy76 · Apr 16, 2013 · Viewed 10.2k times · Source

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?

Answer

Mark Amery picture Mark Amery · Sep 30, 2014

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");
    }

?>