vue2 使用xterm+node實現(xiàn)webssh

前端使用xterm通過socket.io-client和后端通信,后端使用nodejs+utf8+socket.io+ssh2

前端代碼

基于vue2項目,前端主要依賴包:xterm xterm-addon-fit socket.io-client

<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" >
      <el-form-item label="連接地址" prop="host">
      <el-input v-model="queryParams.host"  autocomplete="off" />
    </el-form-item>
    <el-form-item label="用戶名" prop="username">
      <el-input v-model="queryParams.username"  autocomplete="off" />
    </el-form-item>
      <el-form-item label="密碼" prop="password">
      <el-input v-model="queryParams.password" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="addTerm"
        >連接</el-button>
    </el-form-item>
    </el-form>
    <div style="flex: 1; display: flex; padding-bottom: 10px">
      <div
        style="padding-left: 10px; padding-right: 10px"
        class="termbox"
      ></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 {
      queryParams:{
        host:'',
        username:'',
        password:''
      },
      term:null,
      socket:null,
      fitAddon:null
    };
  },
  methods: {
    addTerm() {
        this.term=null;
        this.term = new Terminal({
        cursorBlink: true
        // cols: 100,
        // rows: 20,
        scrollback: 50,
      });
      this.fitAddon = new FitAddon();
      this.term.loadAddon(this.fitAddon);
      document.querySelector(".termbox").innerHTML=''
      this.term.open(document.querySelector(".termbox"));
      this.fitAddon.fit();
      this.term.focus();
      // socket.on()方法 和 socket.emit()在前后端是成對出現(xiàn)的,通過監(jiān)聽的標識符來顯示不同模塊的數(shù)據(jù),就不用一個頁面利用多個ws了。
      // socket.emit()用于向服務端(后端)發(fā)送數(shù)據(jù), 第一個參數(shù)為監(jiān)聽的標識
      this.socket.emit("createNewServer", {
        msgId: "termbox",
        ip: this.queryParams.host,
        username: this.queryParams.username,
        password: this.queryParams.password,
        cols: 100,
        rows: 20
      });
      // 只要有鍵入 就會觸發(fā)該事件
      this.term.onData((data) => {
        this.socket.emit("termbox", data);
      });
      // socket.on()用于監(jiān)聽獲取服務端(后端)發(fā)送過來的數(shù)據(jù), 第一個參數(shù)為監(jiān)聽的標識
      this.socket.on("termbox", (data)=>{
        this.term.write(data)

      });
      window.addEventListener(
        "resize",
        () => {
          this.fitAddon.fit();
          this.socket.emit("resize", {
            cols: 100,
            rows: 20,
          });
        },
        false
      );
    },
  },
  mounted() {
    this.socket = io("http://localhost:5000");
  },
};
</script>

后端代碼

1、先創(chuàng)建一個文件夾npm init 一個新項目
2、安裝依賴express 、utf8、socket.io、ssh2
3、index.js里面代碼如下
4、啟動服務 node ./index.js

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


function createNewServer(machineConfig, socket) {
  var ssh = new SSHClient();
  let {msgId, ip, username, password} = machineConfig;
  ssh
    .on('ready', function () {
      socket.emit(msgId, '\r\n*** ' + ip + ' 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({
      host: ip,
      port: 22,
      username: username,
      password: password
  });
}

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

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

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

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

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