Skip to content

Commit

Permalink
Merge pull request #585 from midoks/dev
Browse files Browse the repository at this point in the history
ssh终端提高稳定性。
  • Loading branch information
midoks authored May 31, 2024
2 parents be69e58 + c3103a2 commit 06e654a
Show file tree
Hide file tree
Showing 3 changed files with 140 additions and 26 deletions.
120 changes: 120 additions & 0 deletions class/core/ssh_local.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# coding: utf-8

# ---------------------------------------------------------------------------------
# MW-Linux面板
# ---------------------------------------------------------------------------------
# copyright (c) 2018-∞(https://github.com/midoks/mdserver-web) All rights reserved.
# ---------------------------------------------------------------------------------
# Author: midoks <[email protected]>
# ---------------------------------------------------------------------------------

# ---------------------------------------------------------------------------------
# SSH终端操作
# ---------------------------------------------------------------------------------

import json
import time
import os
import sys
import socket
import threading
import re

from io import BytesIO, StringIO

import mw
import paramiko

from flask_socketio import SocketIO, emit, send


class ssh_local(object):

__debug_file = 'logs/ssh_local.log'
__log_type = 'SSH终端'

__ssh = None

# lock
_instance_lock = threading.Lock()

def __init__(self):
pass

@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(ssh_local, "_instance"):
with ssh_local._instance_lock:
if not hasattr(ssh_local, "_instance"):
ssh_local._instance = ssh_local(*args, **kwargs)
return ssh_local._instance

def debug(self, msg):
msg = "{} - {}:{} => {} \n".format(mw.formatDate(),
self.__host, self.__port, msg)
if not mw.isDebugMode():
return
mw.writeFile(self.__debug_file, msg, 'a+')

def returnMsg(self, status, msg):
return {'status': status, 'msg': msg}


def connectSsh(self):
import paramiko
ssh = paramiko.SSHClient()
mw.createSshInfo()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

port = mw.getSSHPort()
try:
ssh.connect('127.0.0.1', port, timeout=5)
except Exception as e:
ssh.connect('localhost', port, timeout=5)
except Exception as e:
ssh.connect(mw.getHostAddr(), port, timeout=30)
except Exception as e:
return False

shell = ssh.invoke_shell(term='xterm', width=83, height=21)
shell.setblocking(0)
return shell

def send(self):
pass

def close(self):
try:
if self.__ssh:
self.__ssh.close()
except:
pass

def wsSend(self, recv):
try:
t = recv.decode("utf-8")
return emit('server_response', {'data': t})
except Exception as e:
return emit('server_response', {'data': recv})

def wsSendConnect(self):
return emit('connect', {'data': 'ok'})

def wsSendReConnect(self):
return emit('reconnect', {'data': 'ok'})


def run(self, info):
if not self.__ssh:
self.__ssh = self.connectSsh()

if self.__ssh.exit_status_ready():
self.__ssh = self.connectSsh()

self.__ssh.send(info)
try:
time.sleep(0.005)
recv = self.__ssh.recv(8192)
return self.wsSend(recv)
except Exception as ex:
return self.wsSend('')
15 changes: 13 additions & 2 deletions class/core/ssh_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
from flask_socketio import SocketIO, emit, send


class ssh_terminal:
class ssh_terminal(object):

__debug_file = 'logs/terminal.log'
__debug_file = 'logs/ssh_terminal.log'
__log_type = 'SSH终端'

# websocketio 唯一标识
Expand All @@ -55,10 +55,21 @@ class ssh_terminal:
__ssh_list = {}
__ssh_last_request_time = {}

# lock
_instance_lock = threading.Lock()

def __init__(self):
ht = threading.Thread(target=self.heartbeat)
ht.start()

@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(ssh_terminal, "_instance"):
with ssh_terminal._instance_lock:
if not hasattr(ssh_terminal, "_instance"):
ssh_terminal._instance = ssh_terminal(*args, **kwargs)
return ssh_terminal._instance

def debug(self, msg):
msg = "{} - {}:{} => {} \n".format(mw.formatDate(),
self.__host, self.__port, msg)
Expand Down
31 changes: 7 additions & 24 deletions route/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,45 +595,28 @@ def index(reqClass=None, reqAction=None, reqData=None):


##################### ssh start ###########################
shell = None
shell_client = None


@socketio.on('webssh_websocketio')
def webssh_websocketio(data):
if not isLogined():
emit('server_response', {'data': '会话丢失,请重新登陆面板!\r\n'})
return

global shell_client
if not shell_client:
import ssh_terminal
shell_client = ssh_terminal.ssh_terminal()

import ssh_terminal
shell_client = ssh_terminal.ssh_terminal.instance()
shell_client.run(request.sid, data)
return


@socketio.on('webssh')
def webssh(msg):
global shell
def webssh(data):
if not isLogined():
emit('server_response', {'data': '会话丢失,请重新登陆面板!\r\n'})
return None

if not shell:
shell = mw.connectSsh()

if shell.exit_status_ready():
shell = mw.connectSsh()

if shell:
shell.send(msg)
try:
time.sleep(0.005)
recv = shell.recv(4096)
emit('server_response', {'data': recv.decode("utf-8")})
except Exception as ex:
emit('server_response', {'data': str(ex)})
import ssh_local
shell = ssh_local.ssh_local.instance()
shell.run(data)
return

##################### ssh end ###########################

0 comments on commit 06e654a

Please sign in to comment.