Nodejs 使用ssh2模块连接远程服务器

E和弦的根音 · 2021-12-22 · 1260 次浏览

安装ssh2 npm i ssh2 -D

node脚本

const Client = require('ssh2').Client
const conn = new Client()

// 远程服务器命令执行
console.log('\x1b[32m 正在更新服务器资源 \x1b[;0m')
const user = {
  host: 'xxx',
  port: 22,
  username: 'root',
  password: 'xxx',
}

function Ready() {
  conn
    .on('ready', function () {
      console.log('Client :: ready')
      // 连接成功后执行 cd / && ll
      conn.exec('cd / && ll', function (err, stream) {
        if (err) throw err
        stream
          .on('close', function (code, signal) {
            console.log('Stream :: close :: code: ' + code + ', signal: ' + signal)
            conn.end()
          })
          .on('data', function (data) {
            console.log('STDOUT: ' + data)
          })
          .stderr.on('data', function (data) {
            console.error('STDERR: ' + data)
          })
      })
    })
    .connect(user)
}

try {
  Ready()
} catch (err) {
  console.log(err)
}
如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎评论,对作者也是一种鼓励。
查看评论 - 1 条评论