修正web播放录像时的录像文件路径,避免core服务设置了非默认重放文件路径后web出现找不到文件的问题。

pull/32/merge
apexliu 2017-03-29 02:56:05 +08:00
parent 349d679742
commit 61c1b69cd9
14 changed files with 57 additions and 714 deletions

View File

@ -171,7 +171,7 @@ class PYSBaseWin(PYSBase):
super()._copy_modules()
def _make_py_ver_file(self):
# 在python.zip尾部追加一个字符串补零到64字节指明python动态库的文件名这样壳在加载时才知道如何加载python动态库
# 指明python动态库的文件名这样壳在加载时才知道如何加载python动态库
out_file = os.path.join(self.base_path, 'python.ver')
_data = struct.pack('=64s', self._get_py_dll_name().encode())
f = open(out_file, 'wb')
@ -179,7 +179,6 @@ class PYSBaseWin(PYSBase):
f.close()
def _get_py_dll_name(self):
#return 'python{}{}.dll'.format(PY_VER[0], PY_VER[1])
return 'python{}.dll'.format(env.py_ver_str)

View File

@ -374,8 +374,6 @@ ExIniSection* ExIniFile::GetSection(const ex_wstr& strName, bool bCreateIfNotExi
if (!bCreateIfNotExists)
return NULL;
ExIniSection* pSec = new ExIniSection(strName);
m_secs.insert(std::make_pair(strName, pSec));
return pSec;

View File

@ -4,8 +4,6 @@
#include "ts_crypto.h"
#include "ts_web_rpc.h"
//#include <sqlite3.h>
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
int ts_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
@ -130,7 +128,7 @@ void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_dat
ex_astr uri;
uri.assign(hm->uri.p, hm->uri.len);
EXLOGV("got request: %s\n", uri.c_str());
EXLOGD("got request: %s\n", uri.c_str());
if (uri == "/rpc")
{
@ -145,7 +143,7 @@ void TsHttpRpc::_mg_event_handler(struct mg_connection *nc, int ev, void *ev_dat
}
else
{
EXLOGV("[core-rpc] got request method `%s`\n", method.c_str());
EXLOGD("[core-rpc] got request method `%s`\n", method.c_str());
_this->_process_request(method, json_param, ret_buf);
}
}
@ -198,8 +196,6 @@ ex_rv TsHttpRpc::_parse_request(struct http_message* req, ex_astr& func_cmd, Jso
json_str = &sztmp[0];
Json::Reader jreader;
if (!jreader.parse(json_str.c_str(), json_param))
@ -289,6 +285,10 @@ void TsHttpRpc::_rpc_func_get_config(const Json::Value& json_param, ex_astr& buf
{
Json::Value jr_data;
ex_astr _replay_name;
ex_wstr2astr(g_env.m_replay_path, _replay_name);
jr_data["replay-path"] = _replay_name;
ExIniFile& ini = g_env.get_ini();
ex_ini_sections& secs = ini.GetAllSections();
ex_ini_sections::iterator it = secs.begin();

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
import os
import configparser
import os
from eom_common.eomcore.logger import *
@ -17,8 +17,7 @@ class AttrDict(dict):
try:
return self[name]
except KeyError:
# print(self.__class__.__name__)
raise
return None
def __setattr__(self, name, val):
self[name] = val
@ -39,7 +38,7 @@ class ConfigFile(AttrDict):
self['core']['telnet']['enable'] = False
self['core']['telnet']['port'] = 52389
def load_web(self, cfg_file):
def load(self, cfg_file):
if not os.path.exists(cfg_file):
log.e('configuration file does not exists: [{}]\n'.format(cfg_file))
return False
@ -90,6 +89,7 @@ class ConfigFile(AttrDict):
def update_core(self, conf_data):
try:
self['core'] = AttrDict()
self['core']['ssh'] = AttrDict()
self['core']['ssh']['enable'] = False
self['core']['ssh']['port'] = 52189
@ -110,6 +110,9 @@ class ConfigFile(AttrDict):
if 'telnet' in conf_data:
self['core']['telnet']['enable'] = conf_data['telnet']['enable']
self['core']['telnet']['port'] = conf_data['telnet']['port']
self['core']['replay_path'] = conf_data['replay-path']
except IndexError:
log.e('invalid core config.\n')
return False

View File

@ -1,23 +1,19 @@
# -*- coding: utf-8 -*-
import os
# import sys
import json
import os
import urllib.parse
import urllib.request
import eom_common.eomcore.utils as utils
import tornado.httpserver
import tornado.ioloop
import tornado.netutil
import tornado.process
import tornado.web
# from eom_common.eomcore.eom_mysql import get_mysql_pool
from eom_common.eomcore.eom_sqlite import get_sqlite_pool
import eom_common.eomcore.utils as utils
from eom_common.eomcore.logger import log
from .const import *
from .configs import app_cfg
from .const import *
from .db import get_db
from .session import web_session
@ -39,7 +35,7 @@ class WebServerCore:
cfg.cfg_path = os.path.abspath(options['cfg_path'])
_cfg_file = os.path.join(cfg.cfg_path, 'web.ini')
if not cfg.load_web(_cfg_file):
if not cfg.load(_cfg_file):
return False
cfg.log_path = os.path.abspath(options['log_path'])
@ -61,12 +57,7 @@ class WebServerCore:
if not web_session().init():
return False
# TODO: 这里不要初始化数据库接口,需要根据配置文件来决定使用什么数据库(初始安装时还没有配置数据库信息)
# get_mysql_pool().init(cfg.mysql_ip, cfg.mysql_port, cfg.mysql_user, cfg.mysql_pass)
# db_path = os.path.join(cfg.data_path, 'ts_db.db')
get_sqlite_pool().init(cfg.data_path)
# get_db().init_sqlite(os.path.join(cfg.data_path, 'ts_db.db'))
# TODO: 根据配置文件来决定使用什么数据库(初始安装时还没有配置数据库信息)
_db = get_db()
if not _db.init({'type': _db.DB_TYPE_SQLITE, 'file': os.path.join(cfg.data_path, 'ts_db.db')}):
log.e('initialize database interface failed.\n')
@ -111,17 +102,13 @@ class WebServerCore:
'autoescape': 'xhtml_escape',
# 'ui_modules': ui_modules,
# 'debug': True,
'debug': False,
# Debug Mode.
'compiled_template_cache': True,
'static_hash_cache': True,
# 不开启模板和静态文件的缓存,这样一旦模板文件和静态文件变化,刷新浏览器即可看到更新。
'compiled_template_cache': False,
'static_hash_cache': False,
}
if cfg.debug:
settings['compiled_template_cache'] = False
settings['static_hash_cache'] = False
from eom_app.controller import controllers
web_app = tornado.web.Application(controllers, **settings)

View File

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*-
import json
import os
import shutil
import json
from eom_common.eomcore.logger import log
@ -75,7 +76,6 @@ class DatabaseUpgrade:
return False
# 移除旧的表(暂时改名而不是真的删除)
# str_sql = 'ALTER TABLE ts_sys_user RENAME TO _bak_ts_sys_user;'
_step = self.step_begin(' - 移除不再使用的数据表...')
if not self.db.exec('ALTER TABLE `{}sys_user` RENAME TO `_bak_ts_sys_user`;'.format(self.db.table_prefix)):
self.step_end(_step, 0)
@ -108,10 +108,6 @@ class DatabaseUpgrade:
return True
self.step_end(_step, 0, '需要升级到v3')
# log.v('upgrade database to version 1.5.217.9 ...\n')
# bak_file = '{}.before-1.5.217.9'.format(db_file)
# if not os.path.exists(bak_file):
# shutil.copy(db_file, bak_file)
if self.db.db_source['type'] == self.db.DB_TYPE_SQLITE:
_step = self.step_begin(' - 备份数据库文件')
_bak_file = '{}.before-v2-to-v3'.format(self.db.db_source['file'])
@ -340,12 +336,7 @@ class DatabaseUpgrade:
if host_info_alt is not None:
new_host_info.append(host_info_alt)
# print('=====================================')
# for i in range(len(new_host_info)):
# print(new_host_info[i])
# 现在有了新的ts_host_info表重构ts_auth_info表
# 'SELECT id, host_id, pro_type, auth_mode, user_name, user_pswd, cert_id, encrypt, log_time FROM ts_auth_info;'
if auth_info_ret is not None:
for i in range(len(auth_info_ret)):
auth_info = {}
@ -367,9 +358,6 @@ class DatabaseUpgrade:
if found:
new_auth_info.append(auth_info)
# for i in range(len(new_auth_info)):
# print(new_auth_info[i])
# 最后重构ts_auth表
if auth_ret is not None:
for i in range(len(auth_ret)):
@ -386,9 +374,6 @@ class DatabaseUpgrade:
if found:
new_auth.append(auth)
# for i in range(len(new_auth)):
# print(new_auth[i])
self.step_end(_step, 0)
_step = self.step_begin(' - 重新整理认证数据表结构及数据...')
@ -450,7 +435,6 @@ class DatabaseUpgrade:
new_auth_info[i]['user_name'], new_auth_info[i]['user_pswd'], new_auth_info[i]['user_param'],
new_auth_info[i]['cert_id'], new_auth_info[i]['encrypt'], '1'
)
# print(str_sql)
if not self.db.exec(sql):
self.step_end(_step, -1, '无法调整数据(2)')
return False
@ -542,5 +526,3 @@ class DatabaseUpgrade:
log.e('failed.\n')
self.step_end(_step, -1)
return False

View File

@ -1,20 +1,16 @@
# -*- coding: utf-8 -*-
import builtins
import os
import sqlite3
import threading
import datetime
import builtins
from eom_common.eomcore import utils
from eom_common.eomcore.logger import log
from eom_common.eomcore import utils
# from .configs import app_cfg
from .database.create import create_and_init
from .database.upgrade import DatabaseUpgrade
# cfg = app_cfg()
__all__ = ['get_db', 'DbItem']
@ -63,14 +59,12 @@ class TPDatabase:
# 看看数据库中是否存在指定的数据表(如果不存在,可能是一个空数据库文件),则可能是一个新安装的系统
ret = self.is_table_exists('{}group'.format(self._table_prefix))
if ret is None or not ret:
# if ret is None or ret[0][0] == 0:
log.w('database need create.\n')
self.need_create = True
return True
# 尝试从配置表中读取当前数据库版本号(如果不存在,说明是比较旧的版本了)
ret = self.query('SELECT `value` FROM `{}config` WHERE `name`="db_ver";'.format(self._table_prefix))
# log.w(ret)
if ret is None or 0 == len(ret):
self.current_ver = 1
else:
@ -124,6 +118,8 @@ class TPDatabase:
return ret
def create_and_init(self, step_begin, step_end):
log.v('start database create and initialization process.\n')
if self.db_source['type'] == self.DB_TYPE_SQLITE:
db_path = os.path.dirname(self.db_source['file'])
if not os.path.exists(db_path):
@ -133,17 +129,21 @@ class TPDatabase:
return False
if create_and_init(self, step_begin, step_end):
log.v('database created.\n')
self.need_create = False
return True
else:
log.e('database create and initialize failed.\n')
return False
def upgrade_database(self, step_begin, step_end):
log.v('start database upgrade process.\n')
if DatabaseUpgrade(self, step_begin, step_end).do_upgrade():
# if upgrade_database(self, step_begin, step_end):
log.v('database upgraded.\n')
self.need_upgrade = False
return True
else:
log.e('database upgrade failed.\n')
return False
def alter_table(self, table_names, field_names=None):

View File

@ -51,7 +51,10 @@ controllers = [
(r'/user/list', user.GetListHandler),
# add another path to static-path
# todo: 重放数据路径是动态从core服务的json-rpc接口获取的因此这里的数据获取方式需要改变
(r"/log/replay/(.*)", tornado.web.StaticFileHandler, {"path": os.path.join(cfg.data_path, 'replay')}),
(r'/log/list', record.LogList),
(r'/log/record/(.*)/(.*)', record.RecordHandler),
(r'/log/command-log/(.*)/(.*)', record.ComandLogHandler),

View File

@ -6,13 +6,10 @@ import os
import platform
from eom_app.app.configs import app_cfg
# from eom_app.module import host
from eom_app.module import record
from eom_app.module import user
from .base import TPBaseAdminAuthHandler, TPBaseAdminAuthJsonHandler
cfg = app_cfg()
def get_free_space_bytes(folder):
""" Return folder/drive free space (in bytes)
@ -33,16 +30,14 @@ def get_free_space_bytes(folder):
class LogHandler(TPBaseAdminAuthHandler):
def get(self):
total_size, free_size = get_free_space_bytes(cfg.data_path)
total_size, free_size = get_free_space_bytes(app_cfg().data_path)
# ts_server = '""'
param = {
'user_list': user.get_user_list(with_admin=True),
'total_size': total_size,
'free_size': free_size,
}
# self.render('log/index.mako', user_list=user_list, total_size=total_size, free_size=free_size, ts_server=ts_server)
self.render('log/index.mako', page_param=json.dumps(param))
@ -64,7 +59,7 @@ class RecordHandler(TPBaseAdminAuthHandler):
# # self.render('log/record.mako', record_id=record_id)
# # return
# # pass
# filename = os.path.join(cfg.data_path, 'replay', 'rdp', '{}'.format(record_id), 'tp-rdp.tpr')
# filename = os.path.join(cfg.core.replay_path, 'replay', 'rdp', '{}'.format(record_id), 'tp-rdp.tpr')
class ComandLogHandler(TPBaseAdminAuthHandler):
@ -78,7 +73,7 @@ class ComandLogHandler(TPBaseAdminAuthHandler):
if protocol == 1:
pass
elif protocol == 2:
record_path = os.path.join(cfg.data_path, 'replay', 'ssh', '{:06d}'.format(int(record_id)))
record_path = os.path.join(app_cfg().core.replay_path, 'ssh', '{:06d}'.format(int(record_id)))
file_info = os.path.join(record_path, 'tp-ssh-cmd.txt')
try:
file = open(file_info, 'r')
@ -101,12 +96,9 @@ class RecordGetHeader(TPBaseAdminAuthJsonHandler):
header = record.read_record_head(record_id)
if header is None:
return self.write_json(-1)
# term = record.read_record_term(record_id)
# if term is None:
# return self.write_json(-1)
ret = dict()
ret['header'] = header
# ret['term'] = term
self.write_json(0, data=ret)

View File

@ -1,19 +1,16 @@
# -*- coding: utf-8 -*-
import tornado.gen
import json
import urllib.parse
from eom_app.app.session import web_session
import tornado.gen
from eom_app.app.configs import app_cfg
from eom_app.app.session import web_session
from eom_app.app.util import async_post_http
from eom_app.module import host, record
from eom_common.eomcore.logger import *
from .base import TPBaseJsonHandler
cfg = app_cfg()
class RpcHandler(TPBaseJsonHandler):
@tornado.gen.coroutine
@ -27,7 +24,6 @@ class RpcHandler(TPBaseJsonHandler):
@tornado.gen.coroutine
def post(self):
# curl -X POST --data '{"method":"get_auth_info","param":{"authid":0}}' http://127.0.0.1:7190/rpc
req = self.request.body.decode('utf-8')
if req == '':
self.write_json(-1, message='need request param.')
@ -43,7 +39,6 @@ class RpcHandler(TPBaseJsonHandler):
if 'method' not in _req or 'param' not in _req:
self.write_json(-1, message='invalid request format.')
return
except:
self.write_json(-1, message='invalid json format.')
return
@ -120,8 +115,10 @@ class RpcHandler(TPBaseJsonHandler):
if 'rpc' not in param:
return self.write_json(-1)
cfg.core_server_rpc = param['rpc']
app_cfg().core_server_rpc = param['rpc']
# 获取core服务的配置信息
req = {'method': 'get_config', 'param': []}
_yr = async_post_http(req)
return_data = yield _yr
@ -132,7 +129,7 @@ class RpcHandler(TPBaseJsonHandler):
if return_data['code'] != 0:
return self.write_json(return_data['code'])
cfg.update_core(return_data['data'])
app_cfg().update_core(return_data['data'])
self.write_json(0)

View File

@ -11,7 +11,7 @@ from eom_common.eomcore.utils import timestamp_utc_now
def read_record_head(record_id):
record_path = os.path.join(app_cfg().data_path, 'replay', 'ssh', '{:06d}'.format(int(record_id)))
record_path = os.path.join(app_cfg().core.replay_path, 'ssh', '{:06d}'.format(int(record_id)))
header_file_path = os.path.join(record_path, 'tp-ssh.tpr')
file = None
try:
@ -58,7 +58,7 @@ def read_record_head(record_id):
# def read_record_term(record_id):
# record_path = os.path.join(cfg.data_path, 'replay', 'ssh', '{}'.format(record_id))
# record_path = os.path.join(cfg.core.replay_path, 'ssh', '{}'.format(record_id))
# term_file_path = os.path.join(record_path, 'term.init')
# # term_file_path = r"E:\GitWork\teleport\share\data\replay\ssh\103\term.init"
#
@ -126,7 +126,7 @@ def read_record_head(record_id):
def read_record_info(record_id, file_id):
record_path = os.path.join(app_cfg().data_path, 'replay', 'ssh', '{:06d}'.format(int(record_id)))
record_path = os.path.join(app_cfg().core.replay_path, 'ssh', '{:06d}'.format(int(record_id)))
file_info = os.path.join(record_path, 'tp-ssh.{:03d}'.format(int(file_id)))
file = None
try:
@ -196,13 +196,14 @@ def delete_log(log_list):
if not ret:
return False
# TODO: 此处应该通过json-rpc接口通知core服务来删除重放文件。
for item in log_list:
log_id = int(item)
try:
record_path = os.path.join(app_cfg().data_path, 'replay', 'ssh', '{:06d}'.format(log_id))
record_path = os.path.join(app_cfg().core.replay_path, 'ssh', '{:06d}'.format(log_id))
if os.path.exists(record_path):
shutil.rmtree(record_path)
record_path = os.path.join(app_cfg().data_path, 'replay', 'rdp', '{:06d}'.format(log_id))
record_path = os.path.join(app_cfg().core.replay_path, 'rdp', '{:06d}'.format(log_id))
if os.path.exists(record_path):
shutil.rmtree(record_path)
except Exception:

View File

@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-
import hashlib
from eom_app.app.const import *
from eom_app.app.configs import app_cfg
from eom_app.app.const import *
from eom_app.app.db import get_db, DbItem
from eom_app.app.util import sec_generate_password, sec_verify_password
# from eom_common.eomcore.logger import log
# from .common import *
def verify_user(name, password):

View File

@ -1,617 +0,0 @@
# -*- coding: utf-8 -*-
import json
import os
import shutil
import sys
from eom_env import *
from eom_common.eomcore.eom_sqlite import get_sqlite_pool
from eom_common.eomcore.logger import *
log.set_attribute(min_level=LOG_DEBUG, log_datetime=False, trace_error=log.TRACE_ERROR_FULL)
db_file = os.path.join(PATH_DATA, 'ts_db.db')
def main():
if not os.path.exists(db_file):
log.v('\n')
log.v('Teleport Server Database Creation\n')
# 如果数据库文件尚未存在,则直接创建之
get_sqlite_pool().init(PATH_DATA)
if not create_base_db():
return 1
else:
log.v('\n')
log.v('Teleport Server Upgrade\n')
if not get_sqlite_pool().init(PATH_DATA):
log.e('upgrade failed.\n')
return 1
if not upgrade_to_1_2_102_3():
log.e('failed to upgrade database to version 1.2.102.3 ...\n')
return 1
if not upgrade_to_1_5_217_9():
log.e('failed to upgrade database to version 1.5.217.9 ...\n')
return 1
if not upgrade_to_1_6_224_3():
log.e('failed to upgrade database to version 1.6.224.3 ...\n')
return 1
return 0
def create_base_db():
try:
# f = open(db_file, 'w')
# f.close()
sql_file = os.path.join(PATH_DATA, 'main.sql')
if not os.path.exists(sql_file):
log.e("sql file not exists.\n")
return False
f = open(sql_file, 'r', encoding='utf-8')
sql = f.read()
f.close()
sql_con = get_sqlite_pool().get_tssqlcon()
sql_con.ExecManyProcNonQuery(sql)
except Exception:
return False
return True
def upgrade_to_1_2_102_3():
# 服务端升级到版本1.2.102.3时,管理员后台和普通用户后台合并了,数据库略有调整
try:
sql_con = get_sqlite_pool().get_tssqlcon()
# 如果存在名为 ts_sys_user 的表,说明是旧版本,需要升级
str_sql = 'SELECT COUNT(*) FROM sqlite_master where type="table" and name="ts_sys_user";'
db_ret = sql_con.ExecProcQuery(str_sql)
if (db_ret[0][0] == 0):
return True
log.v('upgrade database to version 1.2.102.3 ...\n')
bak_file = '{}.before-1.2.102.3'.format(db_file)
if not os.path.exists(bak_file):
shutil.copy(db_file, bak_file)
# 将原来的普通用户的account_type从 0 改为 1
str_sql = 'UPDATE ts_account SET account_type=1 WHERE account_type=0;'
sql_con.ExecProcNonQuery(str_sql)
# 将原来的管理员合并到用户账号表中
str_sql = 'SELECT * FROM ts_sys_user;'
db_ret = sql_con.ExecProcQuery(str_sql)
if db_ret is None:
return True
for i in range(len(db_ret)):
user_name = db_ret[i][1]
user_pwd = db_ret[i][2]
str_sql = 'INSERT INTO ts_account (account_type, account_name, account_pwd, account_status, ' \
'account_lock, account_desc) VALUES (100,"{}","{}",0,0,"{}");'.format(user_name, user_pwd, '超级管理员')
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not found super admin account.\n')
return False
# 移除旧的表(暂时改名而不是真的删除)
str_sql = 'ALTER TABLE ts_sys_user RENAME TO _bak_ts_sys_user;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_sys_user`.\n')
return False
except:
return False
return True
def upgrade_to_1_5_217_9():
# 服务端升级到版本1.5.217.9时,为了支持一机多用户多协议,数据库结构有较大程度改动
try:
sql_con = get_sqlite_pool().get_tssqlcon()
# 如果不存在名为 ts_host_info 的表,说明是旧版本,需要升级
str_sql = 'SELECT COUNT(*) FROM sqlite_master where type="table" and name="ts_host_info";'
db_ret = sql_con.ExecProcQuery(str_sql)
if (db_ret[0][0] == 1):
return True
log.v('upgrade database to version 1.5.217.9 ...\n')
bak_file = '{}.before-1.5.217.9'.format(db_file)
if not os.path.exists(bak_file):
shutil.copy(db_file, bak_file)
# 将原来的 ts_auth 表中增加一个字段
str_sql = 'ALTER TABLE ts_auth ADD host_auth_id INTEGER;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not modify table `ts_auth`.\n')
return False
# 为新增字段进行赋值
str_sql = 'UPDATE ts_auth SET host_auth_id=host_id;'
ret = sql_con.ExecProcNonQuery(str_sql)
# print(ret)
if not ret:
log.e('can not update table `ts_auth`.\n')
return False
# 新建两个表,用于拆分原来的 ts_host 表
str_sql = '''CREATE TABLE "ts_host_info" (
"host_id" integer PRIMARY KEY AUTOINCREMENT,
"group_id" int(11) DEFAULT 0,
"host_sys_type" int(11) DEFAULT 1,
"host_ip" varchar(32) DEFAULT '',
"pro_port" varchar(256) NULL,
"host_lock" int(11) DEFAULT 0,
"host_desc" varchar(128) DEFAULT ''
);'''
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not create table `ts_host_info`.\n')
return False
str_sql = '''CREATE TABLE "ts_auth_info" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"host_id" INTEGER,
"pro_type" INTEGER,
"auth_mode" INTEGER,
"user_name" varchar(256),
"user_pswd" varchar(256),
"cert_id" INTEGER,
"encrypt" INTEGER,
"log_time" varchar(60)
);'''
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not create table `ts_auth_info`.\n')
return False
# 将原来的 ts_host 表改名
str_sql = 'ALTER TABLE ts_host RENAME TO _bak_ts_host;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_host`.\n')
return False
# 从原来 ts_host 表中查询出所有数据
str_sql = 'SELECT * FROM _bak_ts_host;'
db_ret = sql_con.ExecProcQuery(str_sql)
if db_ret is not None:
for i in range(len(db_ret)):
host_id = db_ret[i][0]
group_id = db_ret[i][1]
host_sys_type = db_ret[i][2]
host_ip = db_ret[i][3]
host_pro_port = db_ret[i][4]
host_user_name = db_ret[i][5]
host_user_pwd = db_ret[i][6]
host_pro_type = db_ret[i][7]
cert_id = db_ret[i][8]
host_lock = db_ret[i][9]
host_encrypt = db_ret[i][10]
host_auth_mode = db_ret[i][11]
host_desc = db_ret[i][12]
_pro_port = {}
_pro_port['ssh'] = {}
_pro_port['ssh']['enable'] = 0
_pro_port['ssh']['port'] = 22
_pro_port['rdp'] = {}
_pro_port['rdp']['enable'] = 0
_pro_port['rdp']['port'] = 3389
if (host_pro_type == 1):
_pro_port['rdp']['enable'] = 1
_pro_port['rdp']['port'] = host_pro_port
elif (host_pro_type == 2):
_pro_port['ssh']['enable'] = 1
_pro_port['ssh']['port'] = host_pro_port
pro_port = json.dumps(_pro_port)
str_sql = 'INSERT INTO ts_host_info (host_id, group_id, host_sys_type, host_ip, pro_port, host_lock, host_desc) ' \
'VALUES ({}, {}, {}, \'{}\', \'{}\', {}, \'{}\');'.format(host_id, group_id, host_sys_type, host_ip, pro_port, host_lock, host_desc)
# print(str_sql)
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not insert item into `ts_host_info`.\n')
return False
str_sql = 'INSERT INTO ts_auth_info (host_id, pro_type, auth_mode, user_name, user_pswd, cert_id, encrypt, log_time) ' \
'VALUES ({}, {}, {}, \'{}\', \'{}\', {}, {}, \'{}\');'.format(host_id, host_pro_type, host_auth_mode, host_user_name, host_user_pwd, cert_id, host_encrypt, '1')
# print(str_sql)
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not insert item into `ts_auth_info`.\n')
return False
str_sql = 'ALTER TABLE ts_log add protocol INTEGER;'
# print(str_sql)
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not upgrade database table `ts_log`.\n')
return False
str_sql = 'UPDATE ts_log SET protocol=1 WHERE sys_type=1;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not fix database table `ts_log`.\n')
return False
str_sql = 'UPDATE ts_log SET protocol=2 WHERE sys_type=2;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not fix database table `ts_log`.\n')
return False
str_sql = 'UPDATE ts_log SET ret_code=9999 WHERE ret_code=0;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not fix database table `ts_log`.\n')
return False
except:
return False
return True
# def upgrade_to_1_6_224_3():
# # 服务端升级到版本1.6.224.3时加入telnet支持数据库有调整
# try:
# sql_con = get_sqlite_pool().get_tssqlcon()
#
# # # 如果ts_config表中没有ts_server_telnet_port项则增加默认值52389
# # str_sql = 'SELECT * FROM ts_config WHERE name="ts_server_telnet_port";'
# # db_ret = sql_con.ExecProcQuery(str_sql)
# # if len(db_ret) == 0:
# # log.v('upgrade database to version 1.6.224.3 ...\n')
# #
# # str_sql = 'INSERT INTO ts_config (name, value) VALUES (\'ts_server_telnet_port\', \'52389\');'
# # db_ret = sql_con.ExecProcNonQuery(str_sql)
# # if not db_ret:
# # log.e('can not add telnet default port into `ts_config`.\n')
# # return False
# #
#
# # 如果ts_host_info表中还有pro_port字段说明是旧版本需要处理
# str_sql = 'SELECT pro_port FROM ts_host_info LIMIT 0;'
# db_ret = sql_con.ExecProcQuery(str_sql)
# if db_ret is not None:
# # 发现旧版本
#
# log.v('upgrade database to version 1.6.224.3 ...\n')
# bak_file = '{}.before-1.6.224.3'.format(db_file)
# if not os.path.exists(bak_file):
# shutil.copy(db_file, bak_file)
#
# # 删除所有的表,重建新的
# # os.remove(db_file)
# str_sql = '''
# ALTER TABLE ts_account RENAME TO __bak_ts_account;
# ALTER TABLE ts_auth RENAME TO __bak_ts_auth;
# ALTER TABLE ts_cert RENAME TO __bak_ts_cert;
# ALTER TABLE ts_config RENAME TO __bak_ts_config;
# ALTER TABLE ts_group RENAME TO __bak_ts_group;
# ALTER TABLE ts_host_info RENAME TO __bak_ts_host_info;
# ALTER TABLE ts_auth_info RENAME TO __bak_ts_auth_info;
# ALTER TABLE ts_log RENAME TO __bak_ts_log;
# '''
# sql_con.ExecManyProcNonQuery(str_sql)
#
# return create_base_db()
#
#
# except:
# log.e('failed.\n')
# return False
#
# return True
def upgrade_to_1_6_224_3():
# 服务端升级到版本1.6.224.3时加入telnet支持数据库有调整
try:
sql_con = get_sqlite_pool().get_tssqlcon()
# 如果ts_config表中没有ts_server_telnet_port项则增加默认值52389
str_sql = 'SELECT * FROM ts_config WHERE name="ts_server_telnet_port";'
db_ret = sql_con.ExecProcQuery(str_sql)
if len(db_ret) == 0:
# log.v('upgrade database to version 1.6.224.3 ...\n')
str_sql = 'INSERT INTO ts_config (name, value) VALUES (\'ts_server_telnet_port\', \'52389\');'
db_ret = sql_con.ExecProcNonQuery(str_sql)
if not db_ret:
log.e('can not add telnet default port into `ts_config`.\n')
return False
# 如果ts_host_info表中还有pro_port字段说明是旧版本需要处理
str_sql = 'SELECT pro_port FROM ts_host_info LIMIT 0;'
db_ret = sql_con.ExecProcQuery(str_sql)
if db_ret is None:
return True
# 发现旧版本
log.v('upgrade database to version 1.6.224.3 ...\n')
bak_file = '{}.before-1.6.224.3'.format(db_file)
if not os.path.exists(bak_file):
shutil.copy(db_file, bak_file)
str_sql = 'SELECT id, host_id, pro_type, auth_mode, user_name, user_pswd, cert_id, encrypt, log_time FROM ts_auth_info;'
auth_info_ret = sql_con.ExecProcQuery(str_sql)
# if auth_info_ret is not None:
# for i in range(len(auth_info_ret)):
# #host_id = db_ret[i][0]
# print(auth_info_ret[i])
str_sql = 'SELECT auth_id, account_name, host_id, host_auth_id FROM ts_auth;'
auth_ret = sql_con.ExecProcQuery(str_sql)
# if auth_ret is not None:
# for i in range(len(auth_ret)):
# #host_id = db_ret[i][0]
# print(auth_ret[i])
max_host_id = 0
new_host_info = []
new_auth_info = []
new_auth = []
# 从原来的表中查询数据
str_sql = 'SELECT host_id, group_id, host_sys_type, host_ip, pro_port, host_lock, host_desc FROM ts_host_info;'
host_info_ret = sql_con.ExecProcQuery(str_sql)
if host_info_ret is not None:
# 先找出最大的host_id这样如果要拆分一个host就知道新的host_id应该是多少了
for i in range(len(host_info_ret)):
# print(host_info_ret[i])
#j = json.loads(host_info_ret[i][4])
if host_info_ret[i][0] > max_host_id:
max_host_id = host_info_ret[i][0]
max_host_id += 1
# 然后构建新的host列表
for i in range(len(host_info_ret)):
host_info = {}
host_info_alt = None
protocol = json.loads(host_info_ret[i][4])
host_info['host_id'] = host_info_ret[i][0]
host_info['group_id'] = host_info_ret[i][1]
host_info['host_sys_type'] = host_info_ret[i][2]
host_info['host_ip'] = host_info_ret[i][3]
host_info['host_lock'] = host_info_ret[i][5]
host_info['host_desc'] = host_info_ret[i][6]
host_info['_old_host_id'] = host_info_ret[i][0]
host_info['host_port'] = 0
host_info['protocol'] = 0
have_rdp = False
have_ssh = False
if auth_info_ret is not None:
for j in range(len(auth_info_ret)):
if auth_info_ret[j][1] == host_info['host_id']:
if auth_info_ret[j][2] == 1: # 用到了此主机的RDP
have_rdp = True
elif auth_info_ret[j][2] == 2: # 用到了此主机的SSH
have_ssh = True
if have_rdp and have_ssh:
# 需要拆分
host_info['protocol'] = 1
host_info['host_port'] = protocol['rdp']['port']
host_info_alt = {}
host_info_alt['host_id'] = max_host_id
max_host_id += 1
host_info_alt['group_id'] = host_info_ret[i][1]
host_info_alt['host_sys_type'] = host_info_ret[i][2]
host_info_alt['host_ip'] = host_info_ret[i][3]
host_info_alt['host_lock'] = host_info_ret[i][5]
host_info_alt['host_desc'] = host_info_ret[i][6]
host_info_alt['_old_host_id'] = host_info_ret[i][0]
host_info_alt['host_port'] = protocol['ssh']['port']
host_info_alt['protocol'] = 2
elif have_rdp:
host_info['protocol'] = 1
host_info['host_port'] = protocol['rdp']['port']
elif have_ssh:
host_info['host_port'] = protocol['ssh']['port']
host_info['protocol'] = 2
new_host_info.append(host_info)
if host_info_alt is not None:
new_host_info.append(host_info_alt)
# print('=====================================')
# for i in range(len(new_host_info)):
# print(new_host_info[i])
# 现在有了新的ts_host_info表重构ts_auth_info表
# 'SELECT id, host_id, pro_type, auth_mode, user_name, user_pswd, cert_id, encrypt, log_time FROM ts_auth_info;'
if auth_info_ret is not None:
for i in range(len(auth_info_ret)):
auth_info = {}
auth_info['id'] = auth_info_ret[i][0]
auth_info['auth_mode'] = auth_info_ret[i][3]
auth_info['user_name'] = auth_info_ret[i][4]
auth_info['user_pswd'] = auth_info_ret[i][5]
auth_info['cert_id'] = auth_info_ret[i][6]
auth_info['encrypt'] = auth_info_ret[i][7]
auth_info['log_time'] = auth_info_ret[i][8]
auth_info['user_param'] = 'ogin:\nassword:'
found = False
for j in range(len(new_host_info)):
if auth_info_ret[i][1] == new_host_info[j]['_old_host_id'] and auth_info_ret[i][2] == new_host_info[j]['protocol']:
found = True
auth_info['host_id'] = new_host_info[j]['host_id']
auth_info['_old_host_id'] = new_host_info[j]['_old_host_id']
break
if found:
new_auth_info.append(auth_info)
# for i in range(len(new_auth_info)):
# print(new_auth_info[i])
# 最后重构ts_auth表
if auth_ret is not None:
for i in range(len(auth_ret)):
auth = {}
auth['auth_id'] = auth_ret[i][0]
auth['account_name'] = auth_ret[i][1]
found = False
for j in range(len(new_auth_info)):
if auth_ret[i][2] == new_auth_info[j]['_old_host_id'] and auth_ret[i][3] == new_auth_info[j]['id']:
found = True
auth['host_id'] = new_auth_info[j]['host_id']
auth['host_auth_id'] = new_auth_info[j]['id']
break
if found:
new_auth.append(auth)
# for i in range(len(new_auth)):
# print(new_auth[i])
# 将整理好的数据写入新的临时表
# 先创建三个临时表
str_sql = '''CREATE TABLE "ts_auth_tmp" (
"auth_id" INTEGER PRIMARY KEY AUTOINCREMENT,
"account_name" varchar(256),
"host_id" INTEGER,
"host_auth_id" int(11) NOT NULL
);'''
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not create table `ts_auth_tmp`.\n')
return False
str_sql = '''CREATE TABLE "ts_host_info_tmp" (
"host_id" integer PRIMARY KEY AUTOINCREMENT,
"group_id" int(11) DEFAULT 0,
"host_sys_type" int(11) DEFAULT 1,
"host_ip" varchar(32) DEFAULT '',
"host_port" int(11) DEFAULT 0,
"protocol" int(11) DEFAULT 0,
"host_lock" int(11) DEFAULT 0,
"host_desc" DEFAULT ''
);'''
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not create table `ts_host_info_tmp`.\n')
return False
str_sql = '''CREATE TABLE "ts_auth_info_tmp" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"host_id" INTEGER,
"auth_mode" INTEGER,
"user_name" varchar(256),
"user_pswd" varchar(256),
"user_param" varchar(256),
"cert_id" INTEGER,
"encrypt" INTEGER,
"log_time" varchar(60)
);'''
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not create table `ts_auth_info_tmp`.\n')
return False
for i in range(len(new_host_info)):
str_sql = 'INSERT INTO ts_host_info_tmp (host_id, group_id, host_sys_type, host_ip, host_port, protocol, host_lock, host_desc) ' \
'VALUES ({}, {}, {}, \'{}\', {}, {}, {}, \'{}\');'.format(
new_host_info[i]['host_id'], new_host_info[i]['group_id'], new_host_info[i]['host_sys_type'],
new_host_info[i]['host_ip'], new_host_info[i]['host_port'], new_host_info[i]['protocol'],
new_host_info[i]['host_lock'], new_host_info[i]['host_desc']
)
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not insert item into `ts_host_info`.\n')
return False
for i in range(len(new_auth_info)):
str_sql = 'INSERT INTO ts_auth_info_tmp (id, host_id, auth_mode, user_name, user_pswd, user_param, cert_id, encrypt, log_time) ' \
'VALUES ({}, {}, {}, \'{}\', \'{}\', \'{}\', {}, {}, \'{}\');'.format(
new_auth_info[i]['id'], new_auth_info[i]['host_id'], new_auth_info[i]['auth_mode'],
new_auth_info[i]['user_name'], new_auth_info[i]['user_pswd'], new_auth_info[i]['user_param'],
new_auth_info[i]['cert_id'], new_auth_info[i]['encrypt'], '1'
)
# print(str_sql)
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not insert item into `ts_auth_info`.\n')
return False
for i in range(len(new_auth)):
str_sql = 'INSERT INTO ts_auth_tmp (auth_id, account_name, host_id, host_auth_id) ' \
'VALUES ({}, \'{}\', {}, {});'.format(
new_auth[i]['auth_id'], new_auth[i]['account_name'], new_auth[i]['host_id'], new_auth[i]['host_auth_id']
)
# print(str_sql)
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not insert item into `ts_auth`.\n')
return False
# 表改名
str_sql = 'ALTER TABLE ts_auth RENAME TO __bak_ts_auth;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_auth` to `__bak_ts_auth`.\n')
return False
str_sql = 'ALTER TABLE ts_auth_info RENAME TO __bak_ts_auth_info;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_auth_info` to `__bak_ts_auth_info`.\n')
return False
str_sql = 'ALTER TABLE ts_host_info RENAME TO __bak_ts_host_info;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_host_info` to `__bak_ts_host_info`.\n')
return False
str_sql = 'ALTER TABLE ts_auth_tmp RENAME TO ts_auth;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_auth_tmp` to `ts_auth`.\n')
return False
str_sql = 'ALTER TABLE ts_auth_info_tmp RENAME TO ts_auth_info;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_auth_info_tmp` to `ts_auth_info`.\n')
return False
str_sql = 'ALTER TABLE ts_host_info_tmp RENAME TO ts_host_info;'
ret = sql_con.ExecProcNonQuery(str_sql)
if not ret:
log.e('can not rename table `ts_host_info_tmp` to `ts_host_info`.\n')
return False
except:
log.e('failed.\n')
return False
return True
if __name__ == '__main__':
sys.exit(main())

View File

@ -71,7 +71,7 @@
ywl.add_page_options(${page_param});
var danger_cmd = ['rm', 'su', 'sudo', 'kill'];
var danger_cmd = ['chmod', 'chown', 'kill', 'rm', 'su', 'sudo'];
var info_cmd = ['exit'];
ywl.on_init = function (cb_stack, cb_args) {