本次webssh实现参考博客
博客:使用纯Java实现一个WebSSH项目
github项目开源地址:https://github.com/NoCortY/WebSSH
首先把大佬的项目运行起来,效果如图:
由于大佬的前端不是使用vue,故进行修改如下:
前端Vue代码:
xterm.js为v3.1.0,与4版本写法不一致,请注意!
<template>
<div id="terminal" class="console">
</div>
</template>
<script>
import { Terminal } from 'xterm'
import * as fit from 'xterm/lib/addons/fit/fit'
import * as attach from 'xterm/lib/addons/attach/attach'
import 'xterm/dist/xterm.css'
Terminal.applyAddon(attach)
Terminal.applyAddon(fit)
export default {
// name: 'xterminal',
data() {
return {
term: null,
endpoint: null,
connection: null,
content: '',
protocol: null,
option: {
operate: 'connect',
host: '192.168.*.*',//你要连接的终端的ip
port: '22',
username: '*',//你要连接的终端的用户名和密码
password: '*'
}
}
},
mounted() {
if (window.location.protocol === 'https:') {
this.protocol = 'wss://'
} else {
this.protocol = 'ws://'
}
this.endpoint = this.protocol + '192.168.123.117:8089/webssh'
const terminalContainer = document.getElementById('terminal')
this.term = new Terminal({
// 光标闪烁
cursorBlink: true
})
this.term.on('data', (data) => {
// 键盘输入时的回调函数
this.connection.send(JSON.stringify({ 'operate': 'command', 'command': data }))
})
this.term.open(terminalContainer, true)
this.term.write('Connecting...')
if (window.WebSocket) {
// 如果支持websocket
console.log(this.endpoint)
this.connection = new WebSocket(this.endpoint)//后端接口位置
} else {
// 否则报错
this.onError('WebSocket Not Supported')
}
this.connection.onopen = this.onConnect
// this.connection.onmessage = (evt) => {
// 接收推送的消息
// this.onData(evt.data.toString())
// }
this.connection.onclose = this.onClose
this.connection.onerror = this.onError
this.term.attach(this.connection)
// this.term._initialized = true
},
beforeDestroy() {
this.connection.close()
this.term.destroy()
},
methods: {
send(data) {
this.connection.send(JSON.stringify(data))
},
onError(error) {
// 连接失败回调
this.term.write('Error: ' + error + '\r\n')
console.log('Error: ' + error + '\r\n')
},
onConnect() {
// 连接成功回调
this.connection.send(JSON.stringify(this.option))
},
onClose() {
// 连接关闭回调
this.term.write('\rconnection closed')
console.log('\rconnection closed')
},
onData(data) {
// 收到数据时回调
this.term.write(data)
console.log(data)
}
}
}
</script>
<style lang="scss">
</style>
结果如下图:
后端
由我们团队的后端大佬把后端代码拆分出来放在我们自己的项目中,仿佛没改什么代码