newspaint

Documenting Problems That Were Difficult To Find The Answer To

How to Upload a File over SSH Using Node.JS

The pure-JavaScript SSH2 Node.JS library available at https://github.com/mscdex/ssh2 allows a variety of SSH protocol client operations to be performed within a Node.JS script.

Specifically I wanted to know how to upload a file. Essentially, after creating a SSH connection to a server, it is a matter of opening a read stream from the local file system and opening a write stream to the SSH connection and then piping the two together.

The example code may provide illustration:

var fs = require('fs');
var ssh2 = require('/usr/local/node/node_modules/ssh2');

var conn = new ssh2();

conn.on(
    'connect',
    function () {
        console.log( "- connected" );
    }
);

conn.on(
    'ready',
    function () {
        console.log( "- ready" );

        conn.sftp(
            function (err, sftp) {
                if ( err ) {
                    console.log( "Error, problem starting SFTP: %s", err );
                    process.exit( 2 );
                }

                console.log( "- SFTP started" );

                // upload file
                var readStream = fs.createReadStream( "/proc/meminfo" );
                var writeStream = sftp.createWriteStream( "/tmp/meminfo.txt" );

                // what to do when transfer finishes
                writeStream.on(
                    'close',
                    function () {
                        console.log( "- file transferred" );
                        sftp.end();
                        process.exit( 0 );
                    }
                );

                // initiate transfer of file
                readStream.pipe( writeStream );
            }
        );
    }
);

conn.on(
    'error',
    function (err) {
        console.log( "- connection error: %s", err );
        process.exit( 1 );
    }
);

conn.on(
    'end',
    function () {
        process.exit( 0 );
    }
);

conn.connect(
    {
        "host": "10.0.0.1",
        "port": 22,
        "username": "root",
        "privateKey": "/home/root/.ssh/id_root"
    }
);

2 responses to “How to Upload a File over SSH Using Node.JS

  1. Slim Ben Ghalba June 16, 2015 at 5:14 pm

    Thank you! It works

  2. jasetom July 4, 2016 at 10:32 am

    Thanks a bunch, just what I needed!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: