xterm實(shí)現(xiàn)單個(gè)頁面多個(gè)webssh

xterm是一個(gè)使用TypeScript編寫的前端終端組件。

1、demo主要介紹

本文demo主要實(shí)現(xiàn)一個(gè)頁面可以有webssh窗口,前端部分主要利用xterm通過socket.io-client和后端通信,后端部分使用nodejs+utf8+socket.io+ssh2。

界面效果

點(diǎn)擊界面中創(chuàng)建WEBSSH按鈕,即可新建一個(gè)webssh窗口。為了方便驗(yàn)證功能,本demo中后端連接的服務(wù)器信息是寫死的,可根據(jù)實(shí)際情況在前端在創(chuàng)建webssh調(diào)用addTerm方法時(shí),傳入服務(wù)器信息。
簡要流程

2、前端實(shí)現(xiàn)

基于vue項(xiàng)目,前端主要依賴包:xterm xterm-addon-fit socket.io-client,使用前請(qǐng)install。

<template>
  <div class="container">
    <p>
      <button type="button" @click="addSsh">創(chuàng)建WEBSSH</button>
      <small style="margin-left: 10px;">ws地址不變,可以創(chuàng)建多個(gè)webssh窗口,且這些窗口互不影響。</small>
    </p>
    <ul class="list">
      <li
        v-for="item in sshList"
        :key="item.label"
        :class="{active: sshActiveInfo.label === item.label}"
        @click="changeSsh(item)">
        {{item.label}}
      </li>
    </ul>
    <div style="flex: 1; display: flex; padding-bottom: 10px;">
      <div
        style="padding-left: 10px; padding-right: 10px;"
        v-for="item in sshList"
        :class="item.selector"
        v-show="sshActiveInfo.label === item.label">
      </div>
    </div>
  </div>
</template>

<script>
import 'xterm/css/xterm.css'
import io from 'socket.io-client';
import { Terminal } from 'xterm';
import { FitAddon } from "xterm-addon-fit";

export default {
  name: 'WebShell',
  data() {
    return {
      sshList: [],
      sshActiveInfo: {}
    }
  },
  methods: {
    addSsh() {
      let index = this.sshList.length + 1;
      let info = {
        label: `WEBSSH-${index}`,
        isActive: true,
        selector: `xterm-${index}`,
        term: null
      };
      this.sshList.push(info);
      this.sshActiveInfo = info;
      this.$nextTick(() => {
        this.addTerm(info);
      });
    },
    changeSsh(item) {
      this.sshActiveInfo = item;
      item.term.focus();
    },
    addTerm(item) {
      item.term = new Terminal({
        cursorBlink: true,
        // cols: 100,
        // rows: 20,
        scrollback: 50
      });
      item.fitAddon = new FitAddon();
      item.term.loadAddon(item.fitAddon);
      item.term.open(document.querySelector(`.${item.selector}`));
      item.fitAddon.fit();
      item.term.focus();

      // socket.on()方法 和 socket.emit()在前后端是成對(duì)出現(xiàn)的,通過監(jiān)聽的標(biāo)識(shí)符來顯示不同模塊的數(shù)據(jù),就不用一個(gè)頁面利用多個(gè)ws了。
      // socket.emit()用于向服務(wù)端(后端)發(fā)送數(shù)據(jù), 第一個(gè)參數(shù)為監(jiān)聽的標(biāo)識(shí)
      this.socket.emit("createNewServer", {
        msgId: item.selector,
        cols: item.term.cols,
        rows: item.term.rows
      });
      // 只要有鍵入 就會(huì)觸發(fā)該事件
      item.term.onData(data =>  {
        this.socket.emit(item.selector, data);
      });
      // socket.on()用于監(jiān)聽獲取服務(wù)端(后端)發(fā)送過來的數(shù)據(jù), 第一個(gè)參數(shù)為監(jiān)聽的標(biāo)識(shí)
      this.socket.on(item.selector, function (data) {
        // 用'\n'換行
        item.term.write(data);
      });
      window.addEventListener('resize', () => {
        item.fitAddon.fit()
        this.socket.emit('resize', { cols: item.term.cols, rows: item.term.rows });
      }, false);
    }
  },
  mounted() {
    this.socket = io('http://localhost:5000'); // ws://localhost:5000
  },
  beforeDestroy() {
    this.socket.close();
    this.sshList.map(item => item.term.dispose());
  }
}
</script>

<style scoped>
.list {
  padding: 0;
  margin: 0 0 15px 0;
  list-style: none;
}
.list::after {
  display: table;
  content: '';
}
.list li {
  float: left;
  margin-right: 20px;
  font-size: 14px;
  cursor: pointer;
}
.list li:hover {
  color: #60bb63;
}
.list li.active {
  color: #60bb63;
}
[class*="xterm-"] {
  flex: 1;
}
</style>

3、后端實(shí)現(xiàn)

前端主要依賴包:utf8 ssh2 socket.io,使用前請(qǐng)install。
ssh2用來實(shí)現(xiàn)nodejs和服務(wù)器進(jìn)行連接和通信。
utf8用來實(shí)現(xiàn)服務(wù)器返回的命令執(zhí)行結(jié)果解碼。
socket.io用來實(shí)現(xiàn)后端和前端ws全雙工通信,通過傳入不同的socket-msgId來實(shí)現(xiàn)信息標(biāo)識(shí),就可以實(shí)現(xiàn)單頁面多個(gè)webssh只利用一個(gè)websocket。后端使用ws這個(gè)庫也可以實(shí)現(xiàn)同樣的效果,只是使用ws庫要達(dá)到這個(gè)效果,客戶端會(huì)創(chuàng)建多個(gè)ws實(shí)例而已。

/**用來實(shí)現(xiàn)多個(gè)webssh功能**/
const http = require('http').Server(app);
const io = require('socket.io')(http, {cors: true});
const utf8 = require('utf8');
const SSHClient = require('ssh2').Client;

const serverInfo = {
  host: '192.168.18.141',
  port: 22,
  username: 'root',
  password: '就不告訴你'
};

function createNewServer(machineConfig, socket) {
  var ssh = new SSHClient();
  let {msgId} = machineConfig;
  ssh
    .on('ready', function () {
      socket.emit(msgId, '\r\n*** ' + serverInfo.host + ' SSH CONNECTION ESTABLISHED ***\r\n');
      // ssh設(shè)置cols和rows處理界面輸入字符過長顯示問題
      ssh.shell({cols: machineConfig.cols, rows: machineConfig.rows}, function (err, stream) {
        if (err) {
          return socket.emit(msgId, '\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
        }
        socket.on(msgId, function (data) {
          stream.write(data);
        });
        stream.on('data', function (d) {
          socket.emit(msgId, utf8.decode(d.toString('binary')));
        }).on('close', function () {
          ssh.end();
        });
        socket.on('resize', function socketOnResize (data) {
          stream.setWindow(data.rows, data.cols);
        });
      })
    })
    .on('close', function () {
      socket.emit(msgId, '\r\n*** SSH CONNECTION CLOSED ***\r\n');
    })
    .on('error', function (err) {
      console.log(err);
      socket.emit(msgId, '\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
    }).connect(serverInfo);
}

io.on('connection', function (socket) {
  socket.on('createNewServer', function (machineConfig) {
    // 新建一個(gè)ssh連接
    console.log("createNewServer")
    createNewServer(machineConfig, socket);
  })

  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
})

http.listen(5000, function () {
  console.log('listening on * 5000');
});

4、遺留問題

1、瀏覽器resize后,webshell窗口寬高自適應(yīng)、命令顯示的問題;

5、友情鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容