node.js+react.js+xterm.js构建webssh

概述

先讲一下简单的原理:前端和后端的通信,使用的是socket.js,后端连接服务器,使用的是ssh2.js,页面显示出控制台这个操作页面,使用的是xterm.js。整个工作流程就是:前端在xterm.js里面输入文字,通过socket和后端通信,后端把前端传过来的命令,通过ssh2连接服务器,得到服务器返回的数据,通过socket传给前端,前端再显示出socket返回的内容。所以这里贴一下几个官网,可以先了解一下。
https://socket.io/
https://github.com/staltz/xst...
https://github.com/mscdex/ssh2
再讲一下需求:我这里要创建一个服务端,能够支持从前端得到要连接的服务器信息,再去创建ssh2连接,并且在页面上能够同时存在多个xterm窗口,这些窗口不存在信息的相互影响。

服务端代码

在收到前端的createNewServer信息时,会创建一个新的ssh连接。为了区分不同的服务器窗口,前端必须传递一个msgId,用于给后端发送消息。然后前端就能够监听不同的msgId,将socket传递过来的信息显示到不同的xterm窗口上。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var utf8 = require('utf8');
var 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.shell(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();
            });
        })
    }).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(8000, function() {
    console.log('listening on * 8000');
})

前端代码

前端主要是先打开socket.io连接,在点击创建按钮的时候,把服务器的信息和msgId传递给后台,让后台能够创建一个新的ssh连接,然后在xterm窗口输入数据的时候,把数据发送给服务端,并且监听服务器返回的消息显示到界面上来。
App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import NetWorkConfig from "./NetWorkConfig"
import "../node_modules/xterm/dist/xterm.css"
import 'antd/dist/antd.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <NetWorkConfig/>
      </div>
    );
  }
}

export default App;

NetWorkConfig.jsx

import React from "react"
import openSocket from 'socket.io-client';
import {Button} from "antd"
import XtermTest from "./XtermTest"

const socket = openSocket('http://localhost:8000');

class NetWorkConfig extends React.Component {
    constructor(props) {
        super(props);
        this.createServer1 = this.createServer1.bind(this);
        this.createServer2 = this.createServer2.bind(this);
        this.term1 = null;
        this.term2 = null;
    }

    createServer1() {
        socket.emit("createNewServer", {msgId: 'net1', ip: "192.168.79.100", username: "lss", password: "PassW0rd"});
        let term = this.term1.getTerm();
        term.on("data", function(data) {
            socket.emit('net1', data);
        })
        socket.on("net1", function (data) {
            console.log(data)
            term.write(data)
        })
    }

    createServer2() {
        socket.emit("createNewServer", {msgId: 'net2', ip: "192.168.79.100", username: "lss", password: "PassW0rd"});
        let term = this.term2.getTerm();
        term.on("data", function(data) {
            socket.emit('net2', data);
        })
        socket.on("net2", function (data) {
            term.write(data)
        })
    }

    render() {
        return <div>
                    <Button onClick={this.createServer1}>按钮1</Button>
                    <Button onClick={this.createServer2}>按钮2</Button>
                    <XtermTest ref={(term1) => {this.term1 = term1}} id="net1"/>
                    <XtermTest ref={(term2) => {this.term2 = term2}} id="net2"/>
                </div>

    }
    
}

export default NetWorkConfig

XtermTest.jsx

import React from "react"
import { Terminal } from 'xterm';
import * as fit from '../node_modules/xterm/dist/addons/fit/fit';



class XtermTest extends React.Component {
    constructor(props) {
        super(props)
        this.getTerm = this.getTerm.bind(this);
    }

    render() {
        return <div id={this.props.id}></div>
    }

    getTerm() {
        return this.term;
    }

    componentDidMount() {
        Terminal.applyAddon(fit);
        let {id} = this.props;
        let terminalContainer = document.getElementById(id);
        this.term = new Terminal({cursorBlink: true});
        this.term.open(terminalContainer);
        this.term.fit();
    }

}

export default XtermTest

启动说明

先node启动server.js,然后再正常启动react工程。目前还是一个比较粗糙的版本。效果如图:点击按钮1的时候初始化第一个窗口,点击按钮2的时候初始化第二个窗口。因为传递了不同的msgId,两个窗口不会有信息的干扰。

node.js+react.js+xterm.js构建webssh

相关推荐