基于Express+xterm.js的WebSSH

源文档地址:基于Express的WebSSH

后端基于基于nodeexpressssh2websocket

前端基于reactxterm.js

1. 服务端

1.1 下载npm
yarn add express-ws ssh2 utf8
1.2 服务端代码

src/utils/createNewServer.ts

const SSHClient = require('ssh2').Client;
const utf8 = require('utf8');


export const createNewServer = (machineConfig: any, socket: any) => {
  const ssh = new SSHClient();
  const { host, username, password } = machineConfig;
  // 连接成功
  ssh.on('ready', function () {

    socket.send('\r\n*** SSH CONNECTION SUCCESS ***\r\n');

    ssh.shell(function (err: any, stream: any) {
      // 出错
      if (err) {
        return socket.send('\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
      }

      // 前端发送消息
      socket.on('message', function (data: any) {
        stream.write(data);
      });

      // 通过sh发送消息给前端
      stream.on('data', function (d: any) {
        socket.send(utf8.decode(d.toString('binary')));

        // 关闭连接
      }).on('close', function () {
        ssh.end();
      });
    })

    // 关闭连接
  }).on('close', function () {
    socket.send('\r\n*** SSH CONNECTION CLOSED ***\r\n');

    // 连接错误
  }).on('error', function (err: any) {
    socket.send('\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');

    // 连接
  }).connect({
    port: 22,
    host,
    username,
    password
  });
}

src/main.ts

const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);

import { createNewServer } from './utils/createNewServer';


app.get('/', function (req: any, res: any, next: any) {
  res.end();
});

app.ws('/', function (ws: any, req: any) {
  createNewServer({
    host: '192.168.2.94',
    username: 'megaium',
    password: 'Megaium!'
  }, ws)
});

app.listen(3000)

2. 客户端

2.1 客户端代码

*.ts

import React, { useEffect, useState } from 'react';
import { Terminal } from 'xterm';
import { WebLinksAddon } from 'xterm-addon-web-links';
import { FitAddon } from 'xterm-addon-fit';

import 'xterm/css/xterm.css';
import styles from './index.less';

const FontSize: number = 14;
const Col = 80;

const WebTerminal = () => {
  const [webTerminal, setWebTerminal] = useState<Terminal | null>(null);
  const [ws, setWs] = useState<WebSocket | null>(null);

  useEffect(() => {
    // 新增监听事件
    if (webTerminal && ws) {
      // 监听
      webTerminal.onKey(e => {
        const { key } = e;
        ws.send(key);
      });

      // ws监听
      ws.onmessage = e => {
        console.log(e);

        if (webTerminal) {
          if (typeof e.data === 'string') {
            webTerminal.write(e.data);
          } else {
            console.error('格式错误');
          }
        }
      };
    }
  }, [webTerminal, ws]);

  useEffect(() => {
    // 初始化终端

    const ele = document.getElementById('terminal');
    if (ele) {
      const height = ele.clientHeight;
      // 初始化
      const terminal = new Terminal({
        cursorBlink: true,
        cols: Col,
        rows: Math.ceil(height / FontSize),
      });

      // 辅助
      const fitAddon = new FitAddon();
      terminal.loadAddon(new WebLinksAddon());
      terminal.loadAddon(fitAddon);

      terminal.open(ele);
      terminal.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
      fitAddon.fit();
      setWebTerminal(terminal);
    }

    // 初始化ws连接
    if (ws) ws.close();

    const socket = new WebSocket('ws://192.168.2.123:3000');
    socket.onopen = () => {
      socket.send('connect success');
    };

    setWs(socket);
  }, []);

  return <div id="terminal" className={styles.main} />;
};

export default WebTerminal;

3. 效果

web-ssh

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值