nodejs使用ssh2这个库可以实现操作ssh访问远程服务器.
将下面的连接地址修改成远程即可实现直接连接远程服务器,同时可以在本地执行各种命令.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36const Client = require("ssh2").Client;
const client = new Client();
client.on("ready", function () {
console.log('ssh已连接!');
client.shell(function (err, stream) {
if (err) throw err;
process.stdin.setEncoding('utf8');
let command = false;
process.stdin.on('readable', () => {
const chunk = process.stdin.read();
if (chunk !== null) {
command = true;
stream.write(chunk)
}
});
stream.on('close', function () {
console.log('关闭shell');
client.end();
}).on('data', function (data) {
if (!command) process.stdout.write(data);
command = false;
}).on("error", function (data) {
console.log('err: ' + data);
}).stderr.on('data', function (data) {
console.log('STDERR: ' + data);
});
});
}).connect({
host: '127.0.0.1',
port: 22,
username: 'root',
password: '123456'
});