Created
June 3, 2014 04:05
-
-
Save mscdex/c1a7199af2af9d3ceb1c to your computer and use it in GitHub Desktop.
transfer a directory over ssh with node.js/ssh2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just had to say thanks for sharing this. It was really helpful to me today.