用WEB浏览器管理你的Linux服务器

我们先上一张效果图

上一篇文章讲到如果连接windows,这篇文章我们来聊下Linux如何连接,同样,我们先得了解几个概念

1、SSH简介

1.SSH是安全的加密协议,用于远程连接Linux服务器                
2.SSH的默认端口是22,安全协议版本是SSH2                
3.SSH服务器端主要包含2个服务功能SSH连接和SFTP服务器                
4.SSH客户端包含ssh连接命令和远程拷贝scp命令等 

2、Xterm.js

Xterm.js是一个用TypeScript编写的前端组件,它允许应用程序在浏览器中为用户提供功能齐全的终端。它被VS Code,Hyper和Theia等热门项目所使用。


连接Linux不需要任何服务器上装依赖,通过node服务器我们就可以轻松访问到~

const net = require('net')
var utf8 = require('utf8');
var SSHClient = require('ssh2').Client;

const linux_port = 22;

class Ws extends Base {
  constructor() {
    super();
    this.conn2 = this.conn2.bind(this)
    this.sshConn = this.sshConn.bind(this)
    this.decodeBuffer = this.decodeBuffer.bind(this)
  }

  	
  async conn2(client, req) {
    const { id } = req.query
    if (!id) {
      client.close();
      return
    }
    try {
      const ssh = new SSHClient();
      ssh.on('ready', function () {
        client.send('\r\n*** SSH CONNECTION ESTABLISHED ***\r\n');
        ssh.shell(function (err, stream) {
          if (err) {
            remove(id)
            return client.send('\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
          }
          client.on('message', function (data) {
            remove(id)
            stream.write(data);
          });
          stream.on('data', function (d) {
            remove(id)
            client.send(utf8.decode(d.toString('binary')));
          }).on('close', function () {
            ssh.end();
          });
        })
      }).on('close', function () {
        try {
          // client.send('\r\n*** SSH CONNECTION CLOSED ***\r\n');
          client.close();
        } catch (error) {

        }
      }).on('error', function (err) {
        try {
          client.send('\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
        } catch (error) {

        }
      }).connect({
        host: addr,
        port: linux_port,
        username: 'root',
        password: 'xxx'
      });

      client.on('close', (code, reason) => {
        console.log('WebSocket client disconnected: ' + code + ' [' + reason + ']');
        ssh.end();
        push(id);
      });
    } catch (error) {
      console.log(error)
      client.close();
    }
  }


}

module.exports = new Ws();

写好服务端的逻辑,然后我们开始对前端的逻辑

import React from 'react';
import { Spin } from 'antd';
import Xterm from './Xterm'

const url = `ws://localhost:8089/ss`

class Linux extends React.Component {
  state = {
    screenLoading: true,
    tip: '实验环境连接中...',
  }

  term2 = null;

  count = 0;

  componentDidMount() {
    this.term = this.term2.getTerm();
    this.term.focus();
    this.createServer();
  }

  createServer = () => {
    const { id } = this.props;
    const ws = new WebSocket(`${url}?id=${id}`);
    ws.onopen = (evt) => {

    };
    this.term.on("data", (data) => {
      ws.send(data)
    })
    ws.onmessage = ({ data }) => {
      this.setState({
        screenLoading: false
      })
      this.term.write(data)
    };
    ws.onclose = (evt) => {
      console.log('连接已断开')
      setTimeout(() => {
        this.createServer();
      }, 2000)
    };
  }

  render() {
    const {
      screenLoading,
      tip,
    } = this.state
    return (
      <div>
        <Spin spinning={screenLoading} tip={tip}>
          <Xterm ref={(term2) => { this.term2 = term2 }} id="net2" />
        </Spin>
      </div>
    )
  }
}

export default Linux

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

class Xterm 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,
      rows: 36,
     });
    this.term.open(terminalContainer);
    this.term.fit();
  }

}

export default Xterm

好了,我们就可以愉快的在浏览器访问我们的服务器啦~

评论 抢沙发

表情
  1. #1

    来自天津南开的用户 8天前
    信息量好大

  2. #2

    来自四川成都的用户 24天前
    点赞,前排摸大佬沾点技术

  3. #3

    来自浙江杭州的用户 30天前
    老衲喜欢这篇文章