需求: 业务系统众多,特需要一个系统来管理这些系统-- 一体化平台, 为了方便运维人员使用,特需要在前端页面可以连接远程终端,进行操作
方案: 可以通过xtermjs远程实现连接。
官方文档
Vue安装使用
安装xterm
npm install --save xterm
安装xterm-addon-fit
//xterm.js的插件,使终端的尺寸适合包含元素。
npm install --save xterm-addon-fit
安装xterm-addon-attach
//xterm.js的附加组件,用于附加到Web Socket
npm install --save xterm-addon-attach
使用
<template>
<div id="terminal" />
</template>
<script lang="ts">
import Vue from 'vue';
import { Component } from 'vue-property-decorator';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { AttachAddon } from 'xterm-addon-attach';
import 'xterm/css/xterm.css';
@Component
export default class WebTerminal extends Vue {
private ip: string=this.$route.query.ip as string
private term: Terminal|null=null
private socket: WebSocket|null = null
private mounted () {
const term = new Terminal();
// const term = new Terminal({
// rendererType: "canvas", //渲染类型
// rows: _this.rows, //行数
// cols: _this.cols, // 不指定行数,自动回车后光标从下一行开始
// convertEol: true, //启用时,光标将设置为下一行的开头
// scrollback: 50, //终端中的回滚量
// disableStdin: false, //是否应禁用输入
// cursorStyle: "underline", //光标样式
// cursorBlink: true, //光标闪烁
// theme: {
// foreground: "#ECECEC", //字体
// background: "#000000", //背景色
// cursor: "help", //设置光标
// });
const fitAddon = new FitAddon();
const socket = new WebSocket(`ws://${window.location.host}${window.location.pathname}/api/ws?ip=${this.ip}`);
const attachAddon = new AttachAddon(socket); // 建立websocket链接
term.loadAddon(attachAddon);
term.loadAddon(fitAddon);
term.open(document.getElementById('terminal') as HTMLElement);
fitAddon.fit();// 适应页面大小
term.focus();
socket.onopen = () => { socket.send('\n'); }; // 当连接建立时向终端发送一个换行符,不这么做的话最初终端是没有内容的,输入换行符可让终端显示当前用户的工作路径
window.onresize = function () { // 窗口尺寸变化时,终端尺寸自适应
fitAddon.fit();
};
this.term = term;
this.socket = socket;
}
private beforeDestroy () {
this.socket && this.socket.close();
this.term && this.term.dispose();
}
}
</script>
<style lang="scss" scoped>
#terminal{
height: 100%;
}
</style>
就可以了!!!