mdserver-web/route/__init__.py

670 lines
19 KiB
Python
Raw Normal View History

2018-10-25 04:40:45 -04:00
# coding:utf-8
2018-12-24 21:52:39 -05:00
import sys
import io
import os
import time
import shutil
2018-12-25 10:48:29 -05:00
import uuid
2022-11-19 09:03:55 -05:00
import json
2022-07-04 23:39:46 -04:00
import traceback
2018-12-24 21:52:39 -05:00
2021-04-30 23:45:29 -04:00
# reload(sys)
# sys.setdefaultencoding('utf-8')
2019-01-09 11:52:03 -05:00
2019-02-18 03:21:31 -05:00
2018-12-25 02:12:59 -05:00
from datetime import timedelta
2018-12-24 21:52:39 -05:00
from flask import Flask
from flask import render_template
2018-12-25 04:43:28 -05:00
from flask import make_response
from flask import Response
from flask import session
from flask import request
2018-12-25 10:48:29 -05:00
from flask import redirect
from flask import url_for
2022-03-23 03:30:28 -04:00
from flask import render_template_string, abort
2019-12-08 08:10:22 -05:00
from flask_caching import Cache
2018-12-25 10:48:29 -05:00
from flask_session import Session
2018-12-24 21:52:39 -05:00
from whitenoise import WhiteNoise
2018-12-24 21:52:39 -05:00
sys.path.append(os.getcwd() + "/class/core")
2019-12-08 08:10:22 -05:00
2018-12-25 10:48:29 -05:00
import db
2020-07-10 03:57:25 -04:00
import mw
2019-01-18 04:11:29 -05:00
import config_api
2018-12-24 21:52:39 -05:00
app = Flask(__name__, template_folder='templates/default')
2019-01-18 04:11:29 -05:00
app.config.version = config_api.config_api().getVersion()
2021-01-30 00:32:26 -05:00
app.wsgi_app = WhiteNoise(app.wsgi_app, root="route/static/", prefix="static/", max_age=604800)
2019-12-08 08:10:22 -05:00
cache = Cache(config={'CACHE_TYPE': 'simple'})
cache.init_app(app, config={'CACHE_TYPE': 'simple'})
2019-02-18 03:21:31 -05:00
2018-12-25 10:48:29 -05:00
try:
from flask_sqlalchemy import SQLAlchemy
2019-02-21 22:47:56 -05:00
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/mw_session.db'
2018-12-25 10:48:29 -05:00
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SESSION_TYPE'] = 'sqlalchemy'
app.config['SESSION_SQLALCHEMY'] = sdb
app.config['SESSION_SQLALCHEMY_TABLE'] = 'session'
2019-02-21 22:47:56 -05:00
sdb = SQLAlchemy(app)
sdb.create_all()
2018-12-25 10:48:29 -05:00
except:
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SESSION_FILE_DIR'] = '/tmp/py_mw_session_' + \
str(sys.version_info[0])
app.config['SESSION_FILE_THRESHOLD'] = 1024
app.config['SESSION_FILE_MODE'] = 384
2022-07-04 08:15:38 -04:00
mw.execShell("pip install flask_sqlalchemy &")
2018-12-25 10:48:29 -05:00
2021-01-30 00:32:26 -05:00
app.secret_key = uuid.UUID(int=uuid.getnode()).hex[-12:]
2018-12-28 00:07:21 -05:00
app.config['SESSION_PERMANENT'] = True
2018-12-25 10:48:29 -05:00
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_KEY_PREFIX'] = 'MW_:'
app.config['SESSION_COOKIE_NAME'] = "MW_VER_1"
2021-01-30 00:32:26 -05:00
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=31)
2021-11-03 11:56:47 -04:00
# Session(app)
2018-12-25 10:48:29 -05:00
2022-11-19 09:03:55 -05:00
# 设置BasicAuth
basic_auth_conf = 'data/basic_auth.json'
app.config['BASIC_AUTH_OPEN'] = False
if os.path.exists(basic_auth_conf):
try:
ba_conf = json.loads(mw.readFile(basic_auth_conf))
print(ba_conf)
app.config['BASIC_AUTH_USERNAME'] = ba_conf['basic_user']
app.config['BASIC_AUTH_PASSWORD'] = ba_conf['basic_pwd']
app.config['BASIC_AUTH_OPEN'] = ba_conf['open']
app.config['BASIC_AUTH_FORCE'] = True
except Exception as e:
print(e)
2019-02-18 11:01:30 -05:00
# socketio
from flask_socketio import SocketIO, emit, send
socketio = SocketIO()
socketio.init_app(app)
2021-11-08 05:31:00 -05:00
# from gevent.pywsgi import WSGIServer
# from geventwebsocket.handler import WebSocketHandler
# http_server = WSGIServer(('0.0.0.0', '7200'), app,
# handler_class=WebSocketHandler)
# http_server.serve_forever()
2018-12-25 10:48:29 -05:00
2018-12-28 00:15:03 -05:00
# debug macosx dev
2022-11-05 10:41:37 -04:00
if mw.isDebugMode():
2018-12-28 00:15:03 -05:00
app.debug = True
app.config.version = app.config.version + str(time.time())
2018-12-27 22:31:08 -05:00
import common
common.init()
2018-12-25 02:12:59 -05:00
2022-11-05 10:41:37 -04:00
# ---------- error function start -----------------
def getErrorNum(key, limit=None):
key = mw.md5(key)
num = cache.get(key)
if not num:
num = 0
if not limit:
return num
if limit > num:
return True
return False
def setErrorNum(key, empty=False, expire=3600):
key = mw.md5(key)
num = cache.get(key)
if not num:
num = 0
else:
if empty:
cache.delete(key)
return True
cache.set(key, num + 1, expire)
return True
# ---------- error function end -----------------
2018-12-25 02:12:59 -05:00
def funConvert(fun):
block = fun.split('_')
func = block[0]
for x in range(len(block) - 1):
suf = block[x + 1].title()
func += suf
return func
2018-12-24 21:52:39 -05:00
2022-11-19 09:03:55 -05:00
def sendAuthenticated():
# 发送http认证信息
request_host = mw.getHostAddr()
result = Response(
'', 401, {'WWW-Authenticate': 'Basic realm="%s"' % request_host.strip()})
if not 'login' in session and not 'admin_auth' in session:
session.clear()
return result
@app.before_request
def requestCheck():
# Flask请求勾子
2022-11-19 09:03:55 -05:00
if app.config['BASIC_AUTH_OPEN']:
auth = request.authorization
if request.path in ['/download', '/hook', '/down']:
return
if not auth:
return sendAuthenticated()
salt = '_md_salt'
if mw.md5(auth.username.strip() + salt) != app.config['BASIC_AUTH_USERNAME'] \
or mw.md5(auth.password.strip() + salt) != app.config['BASIC_AUTH_PASSWORD']:
return sendAuthenticated()
2022-12-02 22:49:20 -05:00
domain_check = mw.checkDomainPanel()
if domain_check:
return domain_check
2018-12-24 21:52:39 -05:00
2018-12-25 10:48:29 -05:00
def isLogined():
2021-01-30 00:56:08 -05:00
# print('isLogined', session)
2018-12-27 10:16:12 -05:00
if 'login' in session and 'username' in session and session['login'] == True:
2022-06-11 11:48:05 -04:00
userInfo = mw.M('users').where(
"id=?", (1,)).field('id,username,password').find()
2022-11-05 10:41:37 -04:00
# print(userInfo)
2022-06-11 11:48:05 -04:00
if userInfo['username'] != session['username']:
return False
2022-06-11 12:06:54 -04:00
now_time = int(time.time())
2022-06-12 13:02:29 -04:00
if 'overdue' in session and now_time > session['overdue']:
2022-06-11 12:06:54 -04:00
# 自动续期
session['overdue'] = int(time.time()) + 7 * 24 * 60 * 60
return False
2022-11-05 10:58:42 -04:00
if 'tmp_login_expire' in session and now_time > int(session['tmp_login_expire']):
2022-11-05 10:57:59 -04:00
session.clear()
return False
2018-12-25 10:48:29 -05:00
return True
2021-01-30 01:54:37 -05:00
if os.path.exists('data/api_login.txt'):
content = mw.readFile('data/api_login.txt')
session['login'] = True
session['username'] = content
os.remove('data/api_login.txt')
2018-12-25 10:48:29 -05:00
return False
2018-12-25 01:30:51 -05:00
def publicObject(toObject, func, action=None, get=None):
2018-12-25 02:41:46 -05:00
name = funConvert(func) + 'Api'
2019-02-17 01:42:51 -05:00
try:
if hasattr(toObject, name):
efunc = 'toObject.' + name + '()'
data = eval(efunc)
return data
2022-03-23 03:45:38 -04:00
data = {'msg': '404,not find api[' + name + ']', "status": False}
return mw.getJson(data)
2019-02-17 01:42:51 -05:00
except Exception as e:
2022-07-04 23:39:46 -04:00
# API发生错误记录
print(traceback.print_exc())
2019-02-17 01:42:51 -05:00
data = {'msg': '访问异常:' + str(e) + '!', "status": False}
2020-07-10 03:57:25 -04:00
return mw.getJson(data)
2018-12-25 01:30:51 -05:00
2018-12-25 02:41:46 -05:00
2022-11-02 12:11:16 -04:00
# @app.route("/debug")
# def debug():
# print(sys.version_info)
# print(session)
# os = mw.getOs()
# print(os)
# return mw.getLocalIp()
# 仅针对webhook插件
@app.route("/hook")
def webhook():
input_args = {
'access_key': request.args.get('access_key', '').strip(),
'params': request.args.get('params', '').strip()
}
wh_install_path = mw.getServerDir() + '/webhook'
if not os.path.exists(wh_install_path):
return mw.returnJson(False, '请先安装WebHook插件!')
sys.path.append('plugins/webhook')
import index
return index.runShellArgs(input_args)
2018-12-25 04:43:28 -05:00
2019-02-21 10:05:09 -05:00
@app.route('/close')
def close():
if not os.path.exists('data/close.pl'):
return redirect('/')
data = {}
2020-07-10 03:57:25 -04:00
data['cmd'] = 'rm -rf ' + mw.getRunDir() + '/data/close.pl'
2019-02-21 10:05:09 -05:00
return render_template('close.html', data=data)
2018-12-25 04:43:28 -05:00
@app.route("/code")
def code():
import vilidate
vie = vilidate.vieCode()
codeImage = vie.GetCodeImage(80, 4)
2021-05-01 02:17:42 -04:00
# try:
# from cStringIO import StringIO
# except:
# from StringIO import StringIO
2018-12-25 04:43:28 -05:00
2021-05-01 02:17:42 -04:00
out = io.BytesIO()
2018-12-25 04:43:28 -05:00
codeImage[0].save(out, "png")
2021-05-09 10:48:23 -04:00
# print(codeImage[1])
2021-05-01 02:17:42 -04:00
2020-07-10 03:57:25 -04:00
session['code'] = mw.md5(''.join(codeImage[1]).lower())
2018-12-25 04:43:28 -05:00
img = Response(out.getvalue(), headers={'Content-Type': 'image/png'})
return make_response(img)
@app.route("/check_login", methods=['POST'])
2018-12-25 02:41:46 -05:00
def checkLogin():
2018-12-27 04:22:11 -05:00
if isLogined():
return "true"
return "false"
2018-12-25 01:30:51 -05:00
2018-12-25 04:43:28 -05:00
@app.route("/do_login", methods=['POST'])
def doLogin():
login_cache_count = 5
login_cache_limit = cache.get('login_cache_limit')
filename = 'data/close.pl'
if os.path.exists(filename):
return mw.returnJson(False, '面板已经关闭!')
2018-12-25 04:43:28 -05:00
username = request.form.get('username', '').strip()
password = request.form.get('password', '').strip()
code = request.form.get('code', '').strip()
2021-05-09 10:50:27 -04:00
# print(session)
if 'code' in session:
if session['code'] != mw.md5(code):
if login_cache_limit == None:
login_cache_limit = 1
else:
login_cache_limit = int(login_cache_limit) + 1
if login_cache_limit >= login_cache_count:
mw.writeFile(filename, 'True')
return mw.returnJson(False, '面板已经关闭!')
cache.set('login_cache_limit', login_cache_limit, timeout=10000)
login_cache_limit = cache.get('login_cache_limit')
code_msg = mw.getInfo("验证码错误,您还可以尝试[{1}]次!", (str(
login_cache_count - login_cache_limit)))
2022-11-01 00:03:33 -04:00
mw.writeLog('用户登录', code_msg)
return mw.returnJson(False, code_msg)
2018-12-25 04:43:28 -05:00
2020-07-10 03:57:25 -04:00
userInfo = mw.M('users').where(
2018-12-25 04:43:28 -05:00
"id=?", (1,)).field('id,username,password').find()
2021-05-09 10:50:27 -04:00
# print(userInfo)
# print(password)
2020-07-10 03:57:25 -04:00
password = mw.md5(password)
2021-05-09 10:50:27 -04:00
# print('md5-pass', password)
2021-05-01 02:17:42 -04:00
2018-12-25 04:43:28 -05:00
if userInfo['username'] != username or userInfo['password'] != password:
2019-12-08 08:10:22 -05:00
msg = "<a style='color: red'>密码错误</a>,帐号:{1},密码:{2},登录IP:{3}", ((
'****', '******', request.remote_addr))
if login_cache_limit == None:
login_cache_limit = 1
else:
login_cache_limit = int(login_cache_limit) + 1
if login_cache_limit >= login_cache_count:
2020-07-10 03:57:25 -04:00
mw.writeFile(filename, 'True')
return mw.returnJson(False, '面板已经关闭!')
2019-12-08 08:10:22 -05:00
cache.set('login_cache_limit', login_cache_limit, timeout=10000)
login_cache_limit = cache.get('login_cache_limit')
2020-07-10 03:57:25 -04:00
mw.writeLog('用户登录', mw.getInfo(msg))
return mw.returnJson(False, mw.getInfo("用户名或密码错误,您还可以尝试[{1}]次!", (str(login_cache_count - login_cache_limit))))
2018-12-25 04:43:28 -05:00
2019-12-08 08:10:22 -05:00
cache.delete('login_cache_limit')
2018-12-25 04:43:28 -05:00
session['login'] = True
session['username'] = userInfo['username']
2022-06-11 12:06:54 -04:00
session['overdue'] = int(time.time()) + 7 * 24 * 60 * 60
# session['overdue'] = int(time.time()) + 7
2021-01-30 01:54:37 -05:00
# fix 跳转时,数据消失,可能是跨域问题
mw.writeFile('data/api_login.txt', userInfo['username'])
2020-07-10 03:57:25 -04:00
return mw.returnJson(True, '登录成功,正在跳转...')
2018-12-25 04:43:28 -05:00
2022-03-23 03:45:38 -04:00
@app.errorhandler(404)
2022-03-23 03:30:28 -04:00
def page_unauthorized(error):
2022-03-23 03:45:38 -04:00
return render_template_string('404 not found', error_info=error), 404
2022-03-23 03:30:28 -04:00
def get_admin_safe():
path = 'data/admin_path.pl'
if os.path.exists(path):
cont = mw.readFile(path)
cont = cont.strip().strip('/')
return (True, cont)
return (False, '')
2022-06-19 11:06:42 -04:00
def admin_safe_path(path, req, data, pageFile):
if path != req and not isLogined():
return render_template('path.html')
if not isLogined():
return render_template('login.html', data=data)
2022-06-19 11:06:42 -04:00
if not req in pageFile:
return redirect('/')
return render_template(req + '.html', data=data)
2022-11-05 10:41:37 -04:00
def login_temp_user(token):
if len(token) != 48:
return '错误的参数!'
skey = mw.getClientIp() + '_temp_login'
if not getErrorNum(skey, 10):
return '连续10次验证失败禁止1小时'
stime = int(time.time())
data = mw.M('temp_login').where('state=? and expire>?',
2022-11-05 10:57:59 -04:00
(0, stime)).field('id,token,salt,expire,addtime').find()
2022-11-05 10:41:37 -04:00
if not data:
setErrorNum(skey)
return '验证失败!'
2022-11-05 11:01:41 -04:00
if stime > int(data['expire']):
2022-11-05 10:57:59 -04:00
setErrorNum(skey)
return "过期"
2022-11-05 10:41:37 -04:00
r_token = mw.md5(token + data['salt'])
if r_token != data['token']:
setErrorNum(skey)
return '验证失败!'
userInfo = mw.M('users').where(
"id=?", (1,)).field('id,username').find()
session['login'] = True
session['username'] = userInfo['username']
session['tmp_login'] = True
session['tmp_login_id'] = str(data['id'])
2022-11-05 11:01:41 -04:00
session['tmp_login_expire'] = int(data['expire'])
2022-11-05 10:41:37 -04:00
session['uid'] = data['id']
login_addr = mw.getClientIp() + ":" + str(request.environ.get('REMOTE_PORT'))
mw.writeLog('用户登录', "登录成功,帐号:{1},登录IP:{2}",
(userInfo['username'], login_addr))
mw.M('temp_login').where('id=?', (data['id'],)).update(
{"login_time": stime, 'state': 1, 'login_addr': login_addr})
2022-11-05 10:49:44 -04:00
# print(session)
2022-11-05 10:41:37 -04:00
return redirect('/')
@app.route('/api/<reqClass>/<reqAction>', methods=['POST', 'GET'])
2022-11-27 07:46:31 -05:00
def api(reqClass=None, reqAction=None, reqData=None):
comReturn = common.local()
if comReturn:
return comReturn
import config_api
isOk, data = config_api.config_api().checkPanelToken()
if not isOk:
return mw.returnJson(False, '未开启API')
request_time = request.form.get('request_time', '')
request_token = request.form.get('request_token', '')
request_ip = request.remote_addr
token_md5 = mw.md5(str(request_time) + mw.md5(data['token_crypt']))
if not (token_md5 == request_token):
return mw.returnJson(False, '密钥错误')
if not mw.inArray(data['limit_addr'], request_ip):
return mw.returnJson(False, '非法请求')
if reqClass == None:
return mw.returnJson(False, '请指定请求方法类')
if reqAction == None:
return mw.returnJson(False, '请指定请求方法')
classFile = ('config_api', 'crontab_api', 'files_api', 'firewall_api',
'plugins_api', 'system_api', 'site_api', 'task_api')
className = reqClass + '_api'
if not className in classFile:
return "external api request error"
eval_str = "__import__('" + className + "')." + className + '()'
newInstance = eval(eval_str)
try:
return publicObject(newInstance, reqAction)
except Exception as e:
return mw.getTracebackInfo()
2022-11-27 07:46:31 -05:00
2018-12-24 21:52:39 -05:00
@app.route('/<reqClass>/<reqAction>', methods=['POST', 'GET'])
@app.route('/<reqClass>/', methods=['POST', 'GET'])
@app.route('/<reqClass>', methods=['POST', 'GET'])
@app.route('/', methods=['POST', 'GET'])
def index(reqClass=None, reqAction=None, reqData=None):
comReturn = common.local()
if comReturn:
return comReturn
2018-12-24 21:52:39 -05:00
# 页面请求
2018-12-24 21:52:39 -05:00
if reqAction == None:
import config_api
data = config_api.config_api().get()
if reqClass == None:
reqClass = 'index'
pageFile = ('config', 'control', 'crontab', 'files', 'firewall',
2022-11-14 08:39:46 -05:00
'index', 'plugins', 'login', 'system', 'site', 'cert', 'ssl', 'task', 'soft')
2022-11-05 10:41:37 -04:00
if reqClass == 'login':
token = request.args.get('tmp_token', '').strip()
if token != '':
return login_temp_user(token)
# 设置了安全路径
ainfo = get_admin_safe()
# 登录页
if reqClass == 'login':
2022-11-05 10:41:37 -04:00
2022-11-30 07:03:07 -05:00
signout = request.args.get('signout', '')
if signout == 'True':
session.clear()
session['login'] = False
session['overdue'] = 0
if ainfo[0]:
2022-06-19 11:06:42 -04:00
return admin_safe_path(ainfo[1], reqClass, data, pageFile)
return render_template('login.html', data=data)
if ainfo[0]:
2022-06-19 11:06:42 -04:00
return admin_safe_path(ainfo[1], reqClass, data, pageFile)
if not reqClass in pageFile:
return redirect('/')
2018-12-25 10:48:29 -05:00
if not isLogined():
return redirect('/login')
2019-01-02 00:29:29 -05:00
2019-01-02 03:27:18 -05:00
return render_template(reqClass + '.html', data=data)
2018-12-24 22:21:20 -05:00
if not isLogined():
return 'error request!'
# API请求
2021-11-14 06:34:57 -05:00
classFile = ('config_api', 'crontab_api', 'files_api', 'firewall_api',
'plugins_api', 'system_api', 'site_api', 'task_api')
2018-12-24 22:21:20 -05:00
className = reqClass + '_api'
2021-11-14 06:34:57 -05:00
if not className in classFile:
return "api error request"
2018-12-24 22:21:20 -05:00
2018-12-24 22:26:46 -05:00
eval_str = "__import__('" + className + "')." + className + '()'
newInstance = eval(eval_str)
2021-11-14 06:34:57 -05:00
2018-12-25 01:30:51 -05:00
return publicObject(newInstance, reqAction)
2019-02-18 03:21:31 -05:00
2022-06-24 03:08:18 -04:00
##################### ssh start ###########################
2019-02-18 03:21:31 -05:00
ssh = None
shell = None
2019-02-19 00:12:01 -05:00
def create_rsa():
2022-06-29 02:12:00 -04:00
# mw.execShell("rm -f /root/.ssh/*")
if not os.path.exists('/root/.ssh/authorized_keys'):
mw.execShell('touch /root/.ssh/authorized_keys')
if not os.path.exists('/root/.ssh/id_rsa.pub') and os.path.exists('/root/.ssh/id_rsa'):
mw.execShell(
'echo y | ssh-keygen -q -t rsa -P "" -f /root/.ssh/id_rsa')
else:
mw.execShell('ssh-keygen -q -t rsa -P "" -f /root/.ssh/id_rsa')
2020-07-10 03:57:25 -04:00
mw.execShell('cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys')
mw.execShell('chmod 600 /root/.ssh/authorized_keys')
2019-02-19 00:12:01 -05:00
2019-03-02 21:57:39 -05:00
def clear_ssh():
2022-06-24 02:16:26 -04:00
# 服务器IP
ip = mw.getHostAddr()
2019-03-02 21:57:39 -05:00
sh = '''
#!/bin/bash
PLIST=`who | grep localhost | awk '{print $2}'`
for i in $PLIST
do
2022-06-24 02:16:26 -04:00
ps -t /dev/$i |grep -v TTY | awk '{print $1}' | xargs kill -9
done
#getHostAddr
2022-06-24 02:49:20 -04:00
PLIST=`who | grep "${ip}" | awk '{print $2}'`
2022-06-24 02:16:26 -04:00
for i in $PLIST
do
ps -t /dev/$i |grep -v TTY | awk '{print $1}' | xargs kill -9
2019-03-02 21:57:39 -05:00
done
'''
2020-07-10 03:57:25 -04:00
if not mw.isAppleSystem():
info = mw.execShell(sh)
2021-04-30 23:45:29 -04:00
print(info[0], info[1])
2019-03-02 21:57:39 -05:00
2019-02-18 03:21:31 -05:00
def connect_ssh():
2019-03-14 00:58:28 -04:00
# print 'connect_ssh ....'
2022-06-24 03:20:48 -04:00
# clear_ssh()
2019-02-18 03:21:31 -05:00
global shell, ssh
2022-06-29 02:12:00 -04:00
if not os.path.exists('/root/.ssh/id_rsa') or not os.path.exists('/root/.ssh/id_rsa.pub'):
2019-02-19 00:12:01 -05:00
create_rsa()
2019-02-18 05:20:57 -05:00
2022-06-24 02:16:26 -04:00
# 检查是否写入authorized_keys
data = mw.execShell("cat /root/.ssh/id_rsa.pub | awk '{print $3}'")
2022-06-24 02:34:33 -04:00
if data[0] != "":
2022-06-24 02:16:26 -04:00
ak_data = mw.execShell(
2022-06-24 02:34:33 -04:00
"cat /root/.ssh/authorized_keys | grep " + data[0])
if ak_data[0] == "":
2022-06-24 02:16:26 -04:00
mw.execShell(
'cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys')
mw.execShell('chmod 600 /root/.ssh/authorized_keys')
2019-02-18 03:21:31 -05:00
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
2022-06-24 02:16:26 -04:00
2019-02-18 03:21:31 -05:00
try:
2022-06-26 23:56:05 -04:00
ssh.connect(mw.getHostAddr(), mw.getSSHPort(), timeout=5)
2019-02-18 03:21:31 -05:00
except Exception as e:
2022-06-26 23:56:05 -04:00
ssh.connect('127.0.0.1', mw.getSSHPort())
2022-06-24 02:16:26 -04:00
except Exception as e:
2022-06-26 23:56:05 -04:00
ssh.connect('localhost', mw.getSSHPort())
2022-06-24 14:13:00 -04:00
except Exception as e:
2022-06-24 02:16:26 -04:00
return False
2019-02-19 00:25:31 -05:00
shell = ssh.invoke_shell(term='xterm', width=83, height=21)
2019-02-18 03:21:31 -05:00
shell.setblocking(0)
return True
@socketio.on('webssh')
def webssh(msg):
2021-11-08 05:39:21 -05:00
# print('webssh ...')
2019-02-18 03:21:31 -05:00
if not isLogined():
emit('server_response', {'data': '会话丢失,请重新登陆面板!\r\n'})
return None
global shell, ssh
ssh_success = True
if not shell:
ssh_success = connect_ssh()
if not shell:
2019-02-19 00:12:01 -05:00
emit('server_response', {'data': '连接SSH服务失败!\r\n'})
2019-02-18 03:21:31 -05:00
return
if shell.exit_status_ready():
ssh_success = connect_ssh()
if not ssh_success:
2019-02-19 00:12:01 -05:00
emit('server_response', {'data': '连接SSH服务失败!\r\n'})
2019-02-18 03:21:31 -05:00
return
shell.send(msg)
try:
time.sleep(0.005)
recv = shell.recv(4096)
emit('server_response', {'data': recv.decode("utf-8")})
except Exception as ex:
2019-03-14 00:58:28 -04:00
pass
# print 'webssh:' + str(ex)
2019-02-18 03:21:31 -05:00
@socketio.on('connect_event')
def connected_msg(msg):
if not isLogined():
2019-08-01 20:30:14 -04:00
emit('server_response', {'data': '会话丢失,请重新登陆面板!\r\n'})
2019-02-18 03:21:31 -05:00
return None
global shell, ssh
2019-03-14 00:56:03 -04:00
ssh_success = True
if not shell:
ssh_success = connect_ssh()
2022-06-24 02:16:26 -04:00
# print(ssh_success)
2019-03-14 00:56:03 -04:00
if not ssh_success:
emit('server_response', {'data': '连接SSH服务失败!\r\n'})
return
2019-02-18 03:21:31 -05:00
try:
recv = shell.recv(8192)
2019-02-19 01:03:14 -05:00
# print recv.decode("utf-8")
2019-02-18 03:21:31 -05:00
emit('server_response', {'data': recv.decode("utf-8")})
except Exception as e:
2019-03-14 00:58:28 -04:00
pass
# print 'connected_msg:' + str(e)
2022-06-24 03:08:18 -04:00
2022-06-24 10:01:29 -04:00
if not mw.isAppleSystem():
try:
import paramiko
ssh = paramiko.SSHClient()
# 启动尝试时连接
2022-06-24 11:54:24 -04:00
# connect_ssh()
2022-06-24 10:01:29 -04:00
except Exception as e:
print("本地终端无法使用")
2022-06-24 03:08:18 -04:00
##################### ssh end ###########################