import { Client } from 'ssh2';
const shellCmd = 'cd /xxxx/xxxx/ xxxx/ sh xx.shell';
const conn = new Client();
conn.on('ready', async() => { // 准备就绪
const readyMsg = `++++++++Client :: ready: ${ip} ++++++++`;
conn.exec(shellCmd, async (err, stream) => { // 执行
if (err) { // 异常抛出
const errorMsg = 'shellCmd ERROR: ' + err.toString();
ctx.logger.info(errorMsg);
return;
}
stream.on('close', async (code, signal) => { // 结束 code: 代码 signal: 信号
const log = 'Stream :: close :: code: ' + code + ', signal: ' + signal;
if (code !== 0 ) {
const signalMsg = `脚本异常退出code: ${code},异常信号signal:${signal}`;
ctx.logger.info(signalMsg);
conn.end();
}
// 程序执行成功
// 自己的业务逻辑....
conn.end();
}).on('data', async data => { // 数据 程序执行中echo出的数据
const dataStr = 'STDOUT: ' + data.toString();
ctx.logger.info(dataStr);
}).stderr.on('data', async data => { // 标准错误
const dataStr = 'STDERR: ' + data.toString();
ctx.logger.info(dataStr);
});
});
}).on('error', async err => {
console.log('Client 链接错误' + err.toString())
}).connect({
host: '127.0.0.1',
port: 8080,
username: username,
password: password,
readyTimeout: 5000, // 握手超时实现限制 - 暂时设置5s
});
node使用ssh2
最新推荐文章于 2024-04-10 20:15:40 发布