1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Node.js]sftpでも「ls -R」したい

Posted at

はじめに

sftp接続しか出来ない環境でファイルリストをとってくるっていうのをPythonでやってるのを見てnode.jsでも出来るかなと思ってやってみました。
sftpだとlsコマンドが再帰的に実行できないっぽくてコマンド一発とはいかないのが少し困りますね。

準備

sftp接続に使うモジュールをインストール

npm install --save ssh2-sftp-client

実装

const SftpClient = require('ssh2-sftp-client');
const fs = require('fs');

const sftp = new SftpClient();

(async () => {

  let result = {};

  await sftp.connect({
    host: "", //接続IP
    port: "", //接続ポート
    username: "", //ID
    password: "", //パスワード
  })

  await lsR("/"); //探索開始ディレクトリを指定

  await fs.writeFileSync('result.json', JSON.stringify(result,null,2)); //結果をjsonファイルに出力する

  sftp.end();

  async function lsR(path){
    let list = await sftp.list(path);

    console.log(path);

    result[path] = list;

    for(let i=0; i<list.length; i++){
      let item = list[i];
      if(item.type === "d"){
        await lsR(path + item.name + "/")
      }
    }

  }
})();
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?