使用nodejs做客户端,执行服务端的命令或者上传下载文件,可以使用ssh2组件。
首先要安装ssh2这个组件
npm install ssh2 --save
然后可以使用密码或者密钥文件连接服务端ssh。
const { Client } = require('ssh2');
let conn = new Client();
conn.on('error', (err) => {
console.error('Connection error:', err);
});
conn.on('end', () => {
console.log('服务器关闭了连接');
});
conn.on('close',async () => {
console.log('连接已完全关闭');
});
conn.on('ready',async () => {
console.log('Client :: ready');
});
let connStr={
host: config.host,
port: config.port,
username: config.username
};
if(config.isPassword){
connStr.password=config.password;
}
else{
connStr.privateKey=require('fs').readFileSync(config.privateKey);
if(config.passphrase&&config.passphrase!=''){
connStr.passphrase=config.passphrase;
}
}
conn.connect(connStr);
其中,ready为连接成功后触发的事件方法,其他的close、error和end哪些方法可以用来记录连接的状态,有助你以后重连和判断连接状态。
执行命令的方法:
let command='cat xxxxxx';
conn.exec(command, function(err, stream) {
if (err) throw err;
stream.on('close', function(code, signal) {
//conn.end();
}).on('data', function(data) {
});
});
调用exec方法,即可执行命令。
958

被折叠的 条评论
为什么被折叠?



