Как загрузить весь каталог на локальном компьютере на сервер, используя SSH NodeJS? - PullRequest
0 голосов
/ 12 мая 2019

Я действительно не знаю об этом, а просто делаю то, что мне говорят.Я пытаюсь загрузить всю папку в каталог на сервере с SSH NodeJS.У меня нет открытого / закрытого ключа и есть только пароль, я скопировал свой код по этой ссылке https://www.npmjs.com/package/node-ssh?fbclid=IwAR0HoJPSCP66RDjzzA2TkL7wzaOqwL9lX2jziryrdZgb6WhaiTR17c6yds0 и Перенос всего каталога с помощью ssh2 в Nodejs , но ни один из этих способов не работает для меня.Пока это мой код:

console.log("Begin deploy ...")

var path, node_ssh, ssh, fs

fs = require('fs')
path = require('path')
node_ssh = require('node-ssh')
ssh = new node_ssh()

const LOCAL_DIRECTORY = ''
const REMOTE_DIRECTORY = ''

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(remotePath);
    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,
              LOCAL_DIRECTORY,
              REMOTE_DIRECTORY,
              true,
              function(err) {
    if (err) throw err;
    console.log('Done transferring');
    conn.end();
  });
}).connect({
  host: '',
  port: 22,
  username: '',
  password: ''
});

console.log("End deploy ...")

Я также попробовал этот код по первой ссылке:

console.log("Begin deploy ...")

var path, node_ssh, ssh, fs

fs = require('fs')
path = require('path')
node_ssh = require('node-ssh')
ssh = new node_ssh()

const LOCAL_DIRECTORY = ''
const REMOTE_DIRECTORY = ''

ssh.connect({
  host: '',
  username: '',
  port: 22,
  password: '',
  tryKeyboard: true,
  onKeyboardInteractive: (name, instructions, instructionsLang, prompts, finish) => {
      if (prompts.length > 0 && prompts[0].prompt.toLowerCase().includes('password')) {
        finish([password])
      }
    }
})

.then(function() {  
  const failed = []
  const successful = []
  ssh.putDirectory(LOCAL_DIRECTORY, REMOTE_DIRECTORY, {
    recursive: true,
    concurrency: 10,
    validate: function(itemPath) {
      const baseName = path.basename(itemPath)
      return baseName.substr(0, 1) !== '.' &&
            baseName !== IGNORE_DIRS_FILES[0] &&
            baseName !== IGNORE_DIRS_FILES[1] &&
            baseName !== IGNORE_DIRS_FILES[2] &&
            baseName !== IGNORE_DIRS_FILES[3]
    },
    tick: function(localPath, remotePath, error) {
      if (error) {
        failed.push(LOCAL_DIRECTORY)
      } else {
        successful.push(LOCAL_DIRECTORY)
      }
    }
  })

  .then(function(status) {
    console.log('the directory transfer was', status ? 'successful' : 'unsuccessful')
    console.log('failed transfers', failed.join(', '))
    console.log('successful transfers', successful.join(', '))
  })
})

console.log("End deploy ...")

Но выходные данные обоих выглядят так: Первый код

Begin deploy ...
End deploy ...
Done transferring
Done in 1.01s

Время было слишком быстрое, поэтому я ошибаюсь, потому что размер папки ~ 300 МБ. Второй код

Begin deploy ...
End deploy ...
The directory transfer was successful
failed transfers
successful transfers

Пожалуйста, помогите мне.Спасибо за вашу помощь.

...