1
3

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 3 years have passed since last update.

Node.js: ssh 接続

Posted at

Node.js で ssh 接続をする方法です。

ライブラリーのインストール

sudo npm install ssh2 -g
ssh_exec.js
# ! /usr/bin/node
//
//	ssh_exec.js
//
//					Jan/20/2022
// ---------------------------------------------------------------
const { readFileSync } = require('fs')

const { Client } = require('ssh2')
const dotenv = require('dotenv')

dotenv.config()
host = process.env.HOST
user = process.env.USER
command = process.env.COMMAND
key_private = process.env.KEY_PRIVATE

const conn = new Client()
conn.on('ready', () => {
console.log('Client :: ready')
conn.exec(command, (err, stream) => {
	if (err) throw err
	stream.on('close', (code, signal) => {
		console.log('Stream :: close :: code: ' + code + ', signal: ' + signal)
		conn.end()
	}).on('data', (data) => {
		console.log('STDOUT: ' + data)
	}).stderr.on('data', (data) => {
		console.log('STDERR: ' + data)
	})
})
}).connect({
	host: host,
	port: 22,
	username: user,
	privateKey: readFileSync(key_private)
})
// ---------------------------------------------------------------
.env
HOST = "example.com"
USER = "scott"
COMMAND = "cd /home/scott/tmp/jan20 ; ls -l"
KEY_PRIVATE = "/home/scott/.ssh/key_private"

実行スクリプト

export NODE_PATH=/usr/lib/node_modules
./ssh_exec.js
1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?