1. 模拟连接(当前页面JS) 仅前端写死文本输出,没有任何网络请求,无法和真实服务器通信,纯演示界面。 2. 真实连接必备条件 ① 后端服务(Node/Java/Python)搭建WebSocket服务 ② 后端使用SSH库建立TCP SSH通道连接目标服务器 ③ 前端通过WebSocket向后端发送命令、接收返回流 ④ 服务器安全组放行22端口 + WebSocket端口
先安装依赖:npm install ssh2 ws xterm
// 后端WebSocket + SSH中转服务
const WebSocket = require('ws');
const { Client } = require('ssh2');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
let sshClient = new Client();
// 接收前端传来的ssh参数
ws.on('message', (msg) => {
const data = JSON.parse(msg);
// 初次握手连接服务器
if(data.type === 'connect') {
sshClient.connect({
host: data.host,
port: data.port,
username: data.user,
password: data.pwd
});
// SSH输出流转发给前端
sshClient.stdout.on('data', (buf) => {
ws.send(JSON.stringify({type:'output', text: buf.toString()}));
});
// 登录错误推送前端
sshClient.on('error', (err) => {
ws.send(JSON.stringify({type:'error', text: err.message}));
})
}
// 前端输入命令,转发到SSH
if(data.type === 'cmd') {
sshClient.exec(data.cmd, (err, stream) => {
stream.stdout.on('data', d => ws.send(JSON.stringify({type:'output', text:d.toString()})))
})
}
})
})
console.log("WebSocket SSH服务启动 ws://127.0.0.1:8080")
// 替换原有模拟connect点击事件,真实ws连接后端
let ws = null;
connectBtn.onclick = () => {
const host = sshHost.value.trim();
const port = sshPort.value.trim();
const user = sshUser.value.trim();
const pwd = sshPwd.value.trim();
if (!host || !port || !user || !pwd) {
terminalBox.textContent = "错误:地址、端口、账号、密码不能为空!";
return;
}
// 建立WebSocket连接后端
ws = new WebSocket("ws://127.0.0.1:8080");
ws.onopen = () => {
// 发送SSH连接参数给后端
ws.send(JSON.stringify({
type: "connect",
host, port, user, pwd
}))
}
// 接收后端转发的SSH输出
ws.onmessage = (ev) => {
const res = JSON.parse(ev.data);
if(res.type === 'output') {
terminalBox.textContent += res.text;
}
if(res.type === 'error') {
terminalBox.textContent += "\n连接失败:" + res.text;
}
}
}