js 实现telnet
使用 Node.js 实现 Telnet 客户端
在 JavaScript 中实现 Telnet 功能通常需要依赖 Node.js 环境,因为浏览器端的 JavaScript 无法直接建立 TCP 连接。以下是几种实现方式:
使用 net 模块(原生)
Node.js 的 net 模块可以创建原始的 TCP 连接:
const net = require('net');
const client = new net.Socket();
client.connect(23, 'example.com', () => {
console.log('Connected to Telnet server');
});
client.on('data', (data) => {
console.log('Received: ' + data);
});
client.on('close', () => {
console.log('Connection closed');
});
// 发送命令
client.write('ls\r\n');
使用 telnet-client 库
更高级的实现可以使用专门的 npm 包如 telnet-client:
const Telnet = require('telnet-client');
const connection = new Telnet();
const params = {
host: 'example.com',
port: 23,
shellPrompt: '/ # ',
timeout: 1500,
// 其他选项...
};
connection.connect(params)
.then(() => {
return connection.exec('ls');
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
处理 Telnet 协商选项
Telnet 协议需要处理各种协商选项,以下是一个简单示例:
const net = require('net');
const client = net.createConnection({ port: 23, host: 'example.com' }, () => {
client.write(Buffer.from([255, 251, 31])); // WILL NAWS
});
client.on('data', (data) => {
if (data[0] === 255) { // IAC
handleTelnetOption(data);
} else {
console.log(data.toString());
}
});
function handleTelnetOption(data) {
// 处理 Telnet 选项协商
const cmd = data[1];
const opt = data[2];
if (cmd === 253) { // DO
if (opt === 31) { // NAWS
const width = 80, height = 24;
const response = Buffer.from([
255, 250, 31,
width >> 8, width & 0xff,
height >> 8, height & 0xff,
255, 240
]);
client.write(response);
}
}
}
浏览器端的 WebSocket 代理方案
由于浏览器无法直接建立 Telnet 连接,可以通过 WebSocket 代理:
- 创建 Node.js 服务器作为中间层
- 浏览器通过 WebSocket 连接到 Node.js 服务器
- Node.js 服务器转发请求到实际的 Telnet 服务器
// 服务器端
const WebSocket = require('ws');
const net = require('net');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
const telnet = net.createConnection(23, 'example.com');
ws.on('message', (message) => {
telnet.write(message);
});
telnet.on('data', (data) => {
ws.send(data.toString());
});
});
安全注意事项
实现 Telnet 客户端时需要注意:
- Telnet 是明文协议,不建议传输敏感信息
- 考虑使用 SSH 作为更安全的替代方案
- 实现适当的超时和错误处理机制
- 对用户输入进行验证和清理
以上方法提供了从简单到复杂的 Telnet 实现方案,可以根据具体需求选择合适的实现方式。







