安装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)
}