LoginSignup
27
26

More than 5 years have passed since last update.

node.jsでSFTP(SSH)する

Last updated at Posted at 2016-02-11

node.jsのスクリプト中でSFTP(SSH)したい。どうやらssh2というライブラリで簡単にできるようなのでそれを利用してみます。

他にもいろいろパッケージがあるようでしたが、認証にkeyが使えることなどから、ssh2をチョイスしました。

環境

  • node.jsはこの機会にLTSの4.3.0を利用しました。
  • テストはMac上で、本番はCentOS6.x(6.7)です。

インストール

  • ssh2のインストール
  • sshのkeyを指定するのに必要なのでfsもインストールします。
npm install chokidar --save
npm install fs

実装

sftp.jsというファイルを用意し、下記のように記述しました。
とりあえずローカルからリモートへのアップロードがしたいので、それをテストしてみました。

var Client = require('ssh2').Client;

var conn = new Client();
conn.on('ready',function(){

    //ready
    console.log('ready sftp...');

    //sftp
    conn.sftp(function(err,sftp){

        //throw if error
        if(err) throw err;

        //file path
        var local = "./test.txt";
        var remote = "./test_up.txt";

        //upload
        sftp.fastPut(local,remote,{},function(err){
            if(err){
                console.log("upload error.");
            }else{
                console.log("uploaded.");
            }
        });
    });

//connection
}).connect({
    host: 'servername',
    port:22,
    username:'hoge',
    privateKey:require('fs').readFileSync('/Users/hoge/.ssh/id_rsa'),
    passphrase:'hoge'
});

実行

下記のように実行します。

node sftp.js

リモートサーバーにtest_up.txtというファイルがアップロードされていればOKです。

27
26
1

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
27
26