Skip to content

Instantly share code, notes, and snippets.

@mscdex
Created June 3, 2014 04:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mscdex/c1a7199af2af9d3ceb1c to your computer and use it in GitHub Desktop.
Save mscdex/c1a7199af2af9d3ceb1c to your computer and use it in GitHub Desktop.
transfer a directory over ssh with node.js/ssh2
var tar = require('tar-fs');
var zlib = require('zlib');
function transferDir(conn, remotePath, localPath, compression, cb) {
var cmd = 'tar cf - "' + remotePath + '" 2>/dev/null';
if (typeof compression === 'function')
cb = compression;
else if (compression === true)
compression = 6;
if (typeof compression === 'number' && compression >= 1 && compression <= 9)
cmd += ' | gzip -' + compression + 'c 2>/dev/null';
else
compression = undefined;
conn.exec(cmd, function(err, stream) {
if (err)
return cb(err);
var exitErr;
var tarStream = tar.extract(localPath);
tarStream.on('finish', function() {
cb(exitErr);
});
stream
.on('exit', function(code, signal) {
if (typeof code === 'number' && code !== 0)
exitErr = new Error('Remote process exited with code ' + code);
else if (signal)
exitErr = new Error('Remote process killed with signal ' + signal);
}).stderr.resume();
if (compression)
stream = stream.pipe(zlib.createGunzip());
stream.pipe(tarStream);
});
}
var ssh = require('ssh2');
var conn = new ssh();
conn.on('ready', function() {
transferDir(conn,
'/home/foo',
__dirname + '/download',
true, // uses compression with default level of 6
function(err) {
if (err) throw err;
console.log('Done transferring');
conn.end();
});
}).connect({
host: '192.168.100.10',
port: 22,
username: 'foo',
password: 'bar'
});
@dominic-p
Copy link

Just had to say thanks for sharing this. It was really helpful to me today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment