diff --git a/server/tp_core/core/tp_core.vs2015.vcxproj b/server/tp_core/core/tp_core.vs2015.vcxproj index 4c383d7..19427d9 100644 --- a/server/tp_core/core/tp_core.vs2015.vcxproj +++ b/server/tp_core/core/tp_core.vs2015.vcxproj @@ -100,7 +100,7 @@ Disabled WIN32;_DEBUG;_CONSOLE;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions) true - ../../../common/libex/include;../../../external/sqlite;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose + ../../../common/libex/include;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose MultiThreadedDebug @@ -136,7 +136,7 @@ true WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;_WINSOCK_DEPRECATED_NO_WARNINGS;MG_ENABLE_THREADS;MG_DISABLE_HTTP_DIGEST_AUTH;MG_DISABLE_MQTT;MG_DISABLE_SSI;MG_DISABLE_FILESYSTEM;%(PreprocessorDefinitions) true - ../../../common/libex/include;../../../external/sqlite;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose + ../../../common/libex/include;../../../external/jsoncpp/include;../../../external/mbedtls/include;../../../external/mongoose MultiThreaded @@ -182,7 +182,6 @@ - @@ -206,8 +205,6 @@ - - diff --git a/server/tp_core/core/tp_core.vs2015.vcxproj.filters b/server/tp_core/core/tp_core.vs2015.vcxproj.filters index dc260ca..6ba5552 100644 --- a/server/tp_core/core/tp_core.vs2015.vcxproj.filters +++ b/server/tp_core/core/tp_core.vs2015.vcxproj.filters @@ -8,9 +8,6 @@ {0155895f-d6be-4e0f-970d-9b6b5c759502} - - {4d2bbfac-6b91-4054-a4e2-38231c443939} - {9c2d60b3-2932-485b-bccd-b66886b0286b} @@ -88,9 +85,6 @@ libex\src - - sqlite - mongoose @@ -171,12 +165,6 @@ Resource Files - - sqlite - - - sqlite - jsoncpp\header diff --git a/server/tp_core/core/ts_db.cpp b/server/tp_core/core/ts_db.cpp index d7bb04d..166a5b5 100644 --- a/server/tp_core/core/ts_db.cpp +++ b/server/tp_core/core/ts_db.cpp @@ -6,7 +6,6 @@ #include -//#include #include #include @@ -20,49 +19,49 @@ TsDB::TsDB() TsDB::~TsDB() { - ExThreadSmartLock locker(m_lock); - sqlite3Map::iterator it; - for (it = m_sqlite3Map.begin(); it != m_sqlite3Map.end(); it++) - { - if (it->second != NULL) - { - sqlite3_close(it->second); - it->second = NULL; - } - } - m_sqlite3Map.clear(); +// ExThreadSmartLock locker(m_lock); +// sqlite3Map::iterator it; +// for (it = m_sqlite3Map.begin(); it != m_sqlite3Map.end(); it++) +// { +// if (it->second != NULL) +// { +// sqlite3_close(it->second); +// it->second = NULL; +// } +// } +// m_sqlite3Map.clear(); } -sqlite3* TsDB::get_db() -{ - ex_astr db_path; - ex_wstr2astr(g_env.m_db_file, db_path); - - ex_u64 _tid = ex_get_thread_id(); - - { - ExThreadSmartLock locker(m_lock); - long tid = (long)_tid; - sqlite3Map::iterator it = m_sqlite3Map.find(tid); - if (it != m_sqlite3Map.end()) - return it->second; - - sqlite3* sql_db = NULL; - int ret = sqlite3_open(db_path.c_str(), &sql_db); - if (SQLITE_OK != ret) - { - EXLOGE("[core-db] can not open database: %s\n", sqlite3_errmsg(sql_db)); - sqlite3_close(sql_db); - sql_db = NULL; - return NULL; - } - - m_sqlite3Map[tid] = sql_db; - return sql_db; - } - - return NULL; -} +// sqlite3* TsDB::get_db() +// { +// ex_astr db_path; +// ex_wstr2astr(g_env.m_db_file, db_path); +// +// ex_u64 _tid = ex_get_thread_id(); +// +// { +// ExThreadSmartLock locker(m_lock); +// long tid = (long)_tid; +// sqlite3Map::iterator it = m_sqlite3Map.find(tid); +// if (it != m_sqlite3Map.end()) +// return it->second; +// +// sqlite3* sql_db = NULL; +// int ret = sqlite3_open(db_path.c_str(), &sql_db); +// if (SQLITE_OK != ret) +// { +// EXLOGE("[core-db] can not open database: %s\n", sqlite3_errmsg(sql_db)); +// sqlite3_close(sql_db); +// sql_db = NULL; +// return NULL; +// } +// +// m_sqlite3Map[tid] = sql_db; +// return sql_db; +// } +// +// return NULL; +// } bool TsDB::get_auth_info(int auth_id, Json::Value& jret) { @@ -74,30 +73,20 @@ bool TsDB::get_auth_info(int auth_id, Json::Value& jret) ex_astr json_param; json_param = json_writer.write(jreq); - - // char tmp[128] = { 0 }; - // ex_strformat(tmp, 127, "{\"method\":\"get_auth_info\",\"param\":[\"authid\":%d]}", auth_id); - // ex_astr param; - //ts_url_encode("{\"method\":\"get_auth_info\",\"param\":[]}", param); ts_url_encode(json_param.c_str(), param); ex_astr url = "http://127.0.0.1:7190/rpc?"; url += param; ex_astr body; - if (ts_http_get(url, body)) + if (!ts_http_get(url, body)) { - EXLOGV("request `get_auth_info` from web return: "); - EXLOGV(body.c_str()); - EXLOGV("\n"); +// EXLOGV("request `get_auth_info` from web return: "); +// EXLOGV(body.c_str()); +// EXLOGV("\n"); + return false; } - // {'account_lock': 0, 'encrypt': 1, 'account_name': 'apexliu', 'host_port': 22, 'cert_id': 0, 'user_name': 'root', - // 'auth_mode': 1, 'sys_type': 2, 'host_ip': '120.26.109.25', 'user_param': 'ogin:\nassword:', - // 'user_pswd': '40V4q3cT4/HT59YaSq8IVJjz0tBV2dmPbViZ4nCnWc4=', 'protocol': 2} - - // {'user_auth': '40V4q3cT4/HT59YaSq8IVJjz0tBV2dmPbViZ4nCnWc4=', 'protocol': 2, 'auth_mode': 1, 'user_name': 'root', 'account_lock': 0, 'user_param': 'ogin:\nassword:', 'host_ip': '120.26.109.25', 'sys_type': 2, 'encrypt': 1, 'account_name': 'apexliu', 'host_port': 22} - // {"message": "", "code" : 0, "data" : {"user_auth": "40V4q3cT4/HT59YaSq8IVJjz0tBV2dmPbViZ4nCnWc4=", "protocol": 2, "auth_mode": 1, "user_name": "root", "account_lock": 0, "user_param": "ogin : \nassword : ", "host_ip": "120.26.109.25", "sys_type": 2, "encrypt": 1, "account_name": "apexliu", "host_port": 22}} Json::Reader jreader; if (!jreader.parse(body.c_str(), jret)) @@ -125,19 +114,6 @@ bool TsDB::get_auth_info(int auth_id, Json::Value& jret) return false; } -// info.host_ip = jret["host_ip"].asString(); -// info.host_port = jret["host_port"].asInt(); -// info.host_lock = 0; -// info.sys_type = jret["sys_type"].asInt(); -// info.protocol = jret["protocol"].asInt(); -// info.is_encrypt = true; -// info.auth_mode = jret["auth_mode"].asInt(); -// info.account_lock = jret["account_lock"].asInt(); -// info.user_name = jret["user_name"].asString(); -// info.user_auth = jret["user_auth"].asString(); -// info.user_param = jret["user_param"].asString(); -// info.account_name = jret["account_name"].asString(); - return true; } @@ -381,521 +357,184 @@ bool TsDB::get_auth_info(int auth_id, Json::Value& jret) bool TsDB::update_reset_log() { -// int result = 0; -// char * errmsg = NULL; -// -// sqlite3* sql_exec = get_db(); -// if (sql_exec == NULL) -// return false; -// -// const char* szSQL = "UPDATE ts_log SET ret_code=7 WHERE ret_code=0;"; -// result = sqlite3_exec(sql_exec, szSQL, NULL, NULL, &errmsg); -// if (result != 0) -// { -// EXLOGE("[db] reset all running session status failed: %s.\n", errmsg); -// return false; -// } -// -// return true; - ex_astr param; ts_url_encode("{\"method\":\"session_fix\",\"param\":[]}", param); ex_astr url = "http://127.0.0.1:7190/rpc?"; url += param; ex_astr body; - if (ts_http_get(url, body)) - { - EXLOGV("request `session_fix` from web return: "); - EXLOGV(body.c_str()); - EXLOGV("\n"); - } - - // TODO: 根据返回的JSON数据的code判断是否操作成功 - - return true; + return ts_http_get(url, body); } -bool TsDB::session_begin(TS_SESSION_INFO& info, int& sid) +// bool TsDB::session_begin(TS_SESSION_INFO& info, int& sid) +// { +// int result; +// char * errmsg = NULL; +// char **dbResult; +// int nRow, nColumn; +// int index; +// +// sqlite3* sql_exec = get_db(); +// if (sql_exec == NULL) +// return false; +// +// int ret_code = 0; +// int begin_time = 0; +// int end_time = 0; +// +// struct tm _now; +// if (!ex_localtime_now(&begin_time, &_now)) +// return false; +// +// char szTime[64] = { 0 }; +// ex_strformat(szTime, 64, "%04d-%02d-%02d %02d:%02d:%02d", (1900 + _now.tm_year), (1 + _now.tm_mon), _now.tm_mday, _now.tm_hour, _now.tm_min, _now.tm_sec); +// +// char szSQL[1024] = { 0 }; +// ex_strformat(szSQL, 1024, +// "INSERT INTO ts_log (session_id, account_name,host_ip,sys_type, host_port,auth_type,\ +// user_name,ret_code,begin_time,end_time,log_time, protocol) \ +// VALUES (\'%s\', \'%s\',\'%s\', %d,%d,%d,\'%s\', %d, %d,%d, \'%s\', %d);", +// info.sid.c_str(), info.account_name.c_str(), info.host_ip.c_str(), info.sys_type, +// info.host_port, info.auth_mode, info.user_name.c_str(), ret_code, begin_time, end_time, +// szTime, info.protocol); +// +// result = sqlite3_exec(sql_exec, szSQL, NULL, NULL, &errmsg); +// if (result != 0) +// { +// EXLOGE("[db] insert new session failed: %s.\n", errmsg); +// return false; +// } +// +// ex_strformat(szSQL, 1024, "SELECT last_insert_rowid() as id;"); +// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); +// if (result != 0) +// { +// if (dbResult) +// sqlite3_free_table(dbResult); +// return false; +// } +// +// index = nColumn; +// if (nColumn != 1) +// { +// if (dbResult) +// sqlite3_free_table(dbResult); +// return false; +// } +// +// sid = atoi(dbResult[index]); +// +// sqlite3_free_table(dbResult); +// +// return true; +// } + +bool TsDB::session_begin(TS_SESSION_INFO& info, int& record_id) { - int result; - char * errmsg = NULL; - char **dbResult; - int nRow, nColumn; - int index; + Json::FastWriter json_writer; + Json::Value jreq; - sqlite3* sql_exec = get_db(); - if (sql_exec == NULL) - return false; +// ex_strformat(szSQL, 1024, +// "INSERT INTO ts_log (session_id, account_name,host_ip,sys_type, host_port,auth_type,\ +// user_name,ret_code,begin_time,end_time,log_time, protocol) \ +// VALUES (\'%s\', \'%s\',\'%s\', %d,%d,%d,\'%s\', %d, %d,%d, \'%s\', %d);", +// info.sid.c_str(), info.account_name.c_str(), info.host_ip.c_str(), info.sys_type, +// info.host_port, info.auth_mode, info.user_name.c_str(), ret_code, begin_time, end_time, +// szTime, info.protocol); - int ret_code = 0; - int begin_time = 0; - int end_time = 0; + jreq["method"] = "session_begin"; + jreq["param"]["sid"] = info.sid.c_str(); + jreq["param"]["account_name"] = info.account_name.c_str(); + jreq["param"]["host_ip"] = info.host_ip.c_str(); + jreq["param"]["sys_type"] = info.sys_type; + jreq["param"]["host_port"] = info.host_port; + jreq["param"]["auth_mode"] = info.auth_mode, + jreq["param"]["user_name"] = info.user_name.c_str(); + jreq["param"]["protocol"] = info.protocol; - struct tm _now; - if (!ex_localtime_now(&begin_time, &_now)) - return false; + ex_astr json_param; + json_param = json_writer.write(jreq); - char szTime[64] = { 0 }; - ex_strformat(szTime, 64, "%04d-%02d-%02d %02d:%02d:%02d", (1900 + _now.tm_year), (1 + _now.tm_mon), _now.tm_mday, _now.tm_hour, _now.tm_min, _now.tm_sec); + ex_astr param; + ts_url_encode(json_param.c_str(), param); + ex_astr url = "http://127.0.0.1:7190/rpc?"; + url += param; - char szSQL[1024] = { 0 }; - ex_strformat(szSQL, 1024, - "INSERT INTO ts_log (session_id, account_name,host_ip,sys_type, host_port,auth_type,\ -user_name,ret_code,begin_time,end_time,log_time, protocol) \ -VALUES (\'%s\', \'%s\',\'%s\', %d,%d,%d,\'%s\', %d, %d,%d, \'%s\', %d);", - info.sid.c_str(), info.account_name.c_str(), info.host_ip.c_str(), info.sys_type, - info.host_port, info.auth_mode, info.user_name.c_str(), ret_code, begin_time, end_time, - szTime, info.protocol); - - result = sqlite3_exec(sql_exec, szSQL, NULL, NULL, &errmsg); - if (result != 0) + ex_astr body; + if (!ts_http_get(url, body)) { - EXLOGE("[db] insert new session failed: %s.\n", errmsg); + // EXLOGV("request `get_auth_info` from web return: "); + // EXLOGV(body.c_str()); + // EXLOGV("\n"); return false; } - ex_strformat(szSQL, 1024, "SELECT last_insert_rowid() as id;"); - result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); - if (result != 0) - { - if (dbResult) - sqlite3_free_table(dbResult); + Json::Reader jreader; + Json::Value jret; + + if (!jreader.parse(body.c_str(), jret)) return false; - } - - index = nColumn; - if (nColumn != 1) - { - if (dbResult) - sqlite3_free_table(dbResult); + if (!jret.isObject()) + return false; + if (!jret["data"].isObject()) + return false; + if (!jret["data"]["rid"].isUInt()) return false; - } - sid = atoi(dbResult[index]); - - sqlite3_free_table(dbResult); + record_id = jret["data"]["rid"].asUInt(); return true; } //session 结束 -bool TsDB::session_end(int id, int ret_code) +bool TsDB::session_end(int record_id, int ret_code) { - int result = 0; - char * errmsg = NULL; +// int result = 0; +// char * errmsg = NULL; +// +// sqlite3* sql_exec = get_db(); +// if (sql_exec == NULL) +// return false; +// +// int end_time = 0; +// if (!ex_localtime_now(&end_time, NULL)) +// { +// EXLOGE("[db] can not local time.\n"); +// return false; +// } +// +// char szSQL[256] = { 0 }; +// ex_strformat(szSQL, 256, "UPDATE ts_log SET ret_code=%d, end_time=%d WHERE id=%d;", ret_code, end_time, id); +// +// result = sqlite3_exec(sql_exec, szSQL, 0, 0, &errmsg); +// if (result != 0) +// { +// EXLOGE("[db] update log failed: %s.\n", errmsg); +// return false; +// } +// +// return true; - sqlite3* sql_exec = get_db(); - if (sql_exec == NULL) - return false; + Json::FastWriter json_writer; + Json::Value jreq; + jreq["method"] = "session_end"; + jreq["param"]["rid"] = record_id; + jreq["param"]["code"] = ret_code; - int end_time = 0; - if (!ex_localtime_now(&end_time, NULL)) - { - EXLOGE("[db] can not local time.\n"); - return false; - } + ex_astr json_param; + json_param = json_writer.write(jreq); - char szSQL[256] = { 0 }; - ex_strformat(szSQL, 256, "UPDATE ts_log SET ret_code=%d, end_time=%d WHERE id=%d;", ret_code, end_time, id); + ex_astr param; + ts_url_encode(json_param.c_str(), param); + ex_astr url = "http://127.0.0.1:7190/rpc?"; + url += param; - result = sqlite3_exec(sql_exec, szSQL, 0, 0, &errmsg); - if (result != 0) - { - EXLOGE("[db] update log failed: %s.\n", errmsg); - return false; - } +// ex_astr param; +// ts_url_encode("{\"method\":\"session_end\",\"param\":[]}", param); +// ex_astr url = "http://127.0.0.1:7190/rpc?"; +// url += param; - return true; + ex_astr body; + return ts_http_get(url, body); } -//获取所有的认证ID -// bool TsDB::get_auth_id_list_by_all(AuthInfo2Vec& auth_info_list) -// { -// int result = 0; -// char * errmsg = NULL; -// char **dbResult; -// int nRow, nColumn; -// int index; -// -// sqlite3* sql_exec = get_db(); -// if (sql_exec == NULL) -// { -// EXLOGE("[db] can not get db.\n"); -// return false; -// } -// -// const char* szSQL = "SELECT auth_id,a.host_id as host_id, \ -// host_ip,host_pro_type as pro_type,host_lock,host_auth_mode as auth_mode \ -// FROM ts_auth as a LEFT JOIN ts_host_info as b ON a.host_id = b.host_id"; -// -// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); -// if (result != 0) -// { -// EXLOGE("[db] get all auth-id list failed: %s.\n", errmsg); -// return false; -// } -// -// //查询是否存在表 -// index = nColumn; -// -// int i = 0, j = 0; -// for (i = 0; i < nRow; i++) -// { -// mapStringKey mapstringKey; -// for (j = 0; j < nColumn; j++) -// { -// ex_astr temp = dbResult[j]; -// if (dbResult[index] == NULL) -// mapstringKey[dbResult[j]] = ""; -// else -// mapstringKey[dbResult[j]] = dbResult[index]; -// -// ++index; -// } -// -// TS_DB_AUTH_INFO_2 info; -// mapStringKey::iterator it = mapstringKey.find("auth_id"); -// if (it != mapstringKey.end()) -// info.auth_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("host_id"); -// if (it != mapstringKey.end()) -// info.host_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("host_ip"); -// if (it != mapstringKey.end()) -// info.host_ip = it->second; -// -// it = mapstringKey.find("host_lock"); -// if (it != mapstringKey.end()) -// info.host_lock = atoi(it->second.c_str()); -// -// it = mapstringKey.find("pro_type"); -// if (it != mapstringKey.end()) -// info.pro_type = atoi(it->second.c_str()); -// -// it = mapstringKey.find("auth_mode"); -// if (it != mapstringKey.end()) -// info.auth_mode = atoi(it->second.c_str()); -// -// auth_info_list.push_back(info); -// } -// -// sqlite3_free_table(dbResult); -// return true; -// } - -//通过IP获取认证ID -// bool TsDB::get_auth_id_list_by_ip(ex_astr host_ip, AuthInfo2Vec& auth_info_list) -// { -// int result = 0; -// char * errmsg = NULL; -// char **dbResult; -// int nRow, nColumn; -// int i, j; -// int index; -// -// sqlite3* sql_exec = get_db(); -// if (sql_exec == NULL) -// return false; -// -// char szSQL[1024] = { 0 }; -// ex_strformat(szSQL, 1024, -// "SELECT auth_id,a.host_id as host_id, \ -// host_ip,host_pro_type as pro_type,host_lock,host_auth_mode as auth_mode \ -// FROM ts_auth as a LEFT JOIN ts_host_info as b ON a.host_id = b.host_id WHERE b.host_ip = \"%s\";", host_ip.c_str()); -// -// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); -// if (result != 0) -// { -// EXLOGE("[db] get auth-id by ip failed: %s.\n", errmsg); -// return false; -// } -// -// //查询是否存在表 -// index = nColumn; -// for (i = 0; i < nRow; i++) -// { -// mapStringKey mapstringKey; -// for (j = 0; j < nColumn; j++) -// { -// ex_astr temp = dbResult[j]; -// if (dbResult[index] == NULL) -// mapstringKey[dbResult[j]] = ""; -// else -// mapstringKey[dbResult[j]] = dbResult[index]; -// -// ++index; -// } -// -// TS_DB_AUTH_INFO_2 info; -// mapStringKey::iterator it = mapstringKey.find("auth_id"); -// if (it != mapstringKey.end()) -// info.auth_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("host_id"); -// if (it != mapstringKey.end()) -// info.host_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("host_ip"); -// if (it != mapstringKey.end()) -// info.host_ip = it->second; -// -// it = mapstringKey.find("host_lock"); -// if (it != mapstringKey.end()) -// info.host_lock = atoi(it->second.c_str()); -// -// it = mapstringKey.find("pro_type"); -// if (it != mapstringKey.end()) -// info.pro_type = atoi(it->second.c_str()); -// -// it = mapstringKey.find("auth_mode"); -// if (it != mapstringKey.end()) -// info.auth_mode = atoi(it->second.c_str()); -// -// auth_info_list.push_back(info); -// } -// -// sqlite3_free_table(dbResult); -// return true; -// } - -//获取所有的认证的信息 -// bool TsDB::get_auth_info_list_by_all(AuthInfo3Vec& auth_info_list) -// { -// int result = 0; -// char * errmsg = NULL; -// char **dbResult; -// int nRow, nColumn; -// int i, j; -// int index; -// -// sqlite3* sql_exec = get_db(); -// if (sql_exec == NULL) -// return false; -// -// const char* szSQL = -// "SELECT host_id ,host_ip,host_user_name, \ -// host_user_pwd, host_auth_mode as auth_mode,a.cert_id as cert_id, \ -// cert_pri,cert_name,cert_pub from ts_host_info as a LEFT JOIN ts_cert as b \ -// ON a.cert_id = b.cert_id;"; -// -// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); -// if (result != 0) -// { -// EXLOGE("[db] get all auth-info list failed: %s.\n", errmsg); -// return false; -// } -// -// //查询是否存在表 -// index = nColumn; -// for (i = 0; i < nRow; i++) -// { -// mapStringKey mapstringKey; -// for (j = 0; j < nColumn; j++) -// { -// //ex_astr temp = dbResult[j]; -// if (dbResult[index] == NULL) -// mapstringKey[dbResult[j]] = ""; -// else -// mapstringKey[dbResult[j]] = dbResult[index]; -// -// ++index; -// } -// -// TS_DB_AUTH_INFO_3 info; -// mapStringKey::iterator it = mapstringKey.find("host_id"); -// if (it != mapstringKey.end()) -// info.host_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("host_ip"); -// if (it != mapstringKey.end()) -// info.host_ip = it->second; -// -// it = mapstringKey.find("host_user_name"); -// if (it != mapstringKey.end()) -// info.host_user_name = it->second; -// -// it = mapstringKey.find("host_user_pwd"); -// if (it != mapstringKey.end()) -// info.host_user_pwd = it->second; -// -// it = mapstringKey.find("auth_mode"); -// if (it != mapstringKey.end()) -// info.auth_mode = atoi(it->second.c_str()); -// -// it = mapstringKey.find("cert_id"); -// if (it != mapstringKey.end()) -// info.cert_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("cert_name"); -// if (it != mapstringKey.end()) -// info.cert_pub = it->second; -// -// it = mapstringKey.find("cert_pri"); -// if (it != mapstringKey.end()) -// info.cert_pri = it->second; -// -// it = mapstringKey.find("cert_pub"); -// if (it != mapstringKey.end()) -// info.cert_pub = it->second; -// -// auth_info_list.push_back(info); -// } -// -// sqlite3_free_table(dbResult); -// return true; -// } - -//通过IP获取认证信息 -// bool TsDB::get_auth_info_list_by_ip(ex_astr host_ip, AuthInfo3Vec& auth_info_list) -// { -// int result = 0; -// char * errmsg = NULL; -// char **dbResult; -// int nRow, nColumn; -// int i, j; -// int index; -// -// sqlite3* sql_exec = get_db(); -// if (sql_exec == NULL) -// return false; -// -// char szSQL[1024] = { 0 }; -// ex_strformat(szSQL, 1024, -// "select host_id ,host_ip,host_user_name, \ -// host_user_pwd, host_auth_mode as auth_mode,a.cert_id as cert_id, \ -// cert_pri,cert_name,cert_pub from ts_host_info as a LEFT JOIN ts_cert as b \ -// ON a.cert_id = b.cert_id where a.host_ip = \"%s\"", host_ip.c_str()); -// -// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); -// if (result != 0) -// { -// EXLOGE("[db] get auth-info by ip failed: %s.\n", errmsg); -// return false; -// } -// -// //查询是否存在表 -// index = nColumn; -// -// for (i = 0; i < nRow; i++) -// { -// //typedef std::map mapStringKey; -// mapStringKey mapstringKey; -// for (j = 0; j < nColumn; j++) -// { -// ex_astr temp = dbResult[j]; -// if (dbResult[index] == NULL) -// mapstringKey[dbResult[j]] = ""; -// else -// mapstringKey[dbResult[j]] = dbResult[index]; -// -// ++index; -// } -// -// TS_DB_AUTH_INFO_3 info; -// mapStringKey::iterator it = mapstringKey.find("host_id"); -// if (it != mapstringKey.end()) -// info.host_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("host_ip"); -// if (it != mapstringKey.end()) -// info.host_ip = it->second; -// -// it = mapstringKey.find("host_user_name"); -// if (it != mapstringKey.end()) -// info.host_user_name = it->second; -// -// it = mapstringKey.find("host_user_pwd"); -// if (it != mapstringKey.end()) -// info.host_user_pwd = it->second; -// -// it = mapstringKey.find("auth_mode"); -// if (it != mapstringKey.end()) -// info.auth_mode = atoi(it->second.c_str()); -// -// it = mapstringKey.find("cert_id"); -// if (it != mapstringKey.end()) -// info.cert_id = atoi(it->second.c_str()); -// -// it = mapstringKey.find("cert_name"); -// if (it != mapstringKey.end()) -// info.cert_pub = it->second; -// -// it = mapstringKey.find("cert_pri"); -// if (it != mapstringKey.end()) -// info.cert_pri = it->second; -// -// it = mapstringKey.find("cert_pub"); -// if (it != mapstringKey.end()) -// info.cert_pub = it->second; -// -// auth_info_list.push_back(info); -// } -// -// sqlite3_free_table(dbResult); -// return true; -// } - -// bool TsDB::get_server_config(TS_DB_SERVER_CONFIG* server_config) -// { -// int result = 0; -// char * errmsg = NULL; -// char **dbResult; -// int nRow, nColumn; -// int i, j; -// int index; -// -// sqlite3* sql_exec = get_db(); -// if (sql_exec == NULL) -// return false; -// -// char* szSQL = "SELECT name, value FROM ts_config"; -// result = sqlite3_get_table(sql_exec, szSQL, &dbResult, &nRow, &nColumn, &errmsg); -// if (result != 0) -// { -// EXLOGE("[db] get server confit failed: %s.\n", errmsg); -// return false; -// } -// -// //查询是否存在表 -// index = nColumn; -// for (i = 0; i < nRow; i++) -// { -// mapStringKey mapstringKey; -// for (j = 0; j < nColumn; j++) -// { -// ex_astr temp = dbResult[j]; -// if (dbResult[index] == NULL) -// mapstringKey[dbResult[j]] = ""; -// else -// mapstringKey[dbResult[j]] = dbResult[index]; -// -// ++index; -// } -// -// TS_DB_AUTH_INFO_3 info; -// mapStringKey::iterator it = mapstringKey.find("name"); -// if (it != mapstringKey.end()) -// { -// ex_astr temp = it->second; -// temp.erase(remove_if(temp.begin(), temp.end(), std::ptr_fun(::isspace)), temp.end()); -// -// mapStringKey::iterator value = mapstringKey.find("value"); -// if (temp.compare("ts_server_rpc_port") == 0) -// server_config->ts_server_rpc_port = atoi(value->second.c_str()); -// else if (temp.compare("ts_server_rdp_port") == 0) -// server_config->ts_server_rdp_port = atoi(value->second.c_str()); -// else if (temp.compare("ts_server_ssh_port") == 0) -// server_config->ts_server_ssh_port = atoi(value->second.c_str()); -// else if (temp.compare("ts_server_telnet_port") == 0) -// server_config->ts_server_telnet_port = atoi(value->second.c_str()); -// else if (temp.compare("ts_server_rpc_ip") == 0) -// server_config->ts_server_rpc_ip = value->second.c_str(); -// } -// } -// -// sqlite3_free_table(dbResult); -// return true; -// } diff --git a/server/tp_core/core/ts_db.h b/server/tp_core/core/ts_db.h index a400d6a..051fcdb 100644 --- a/server/tp_core/core/ts_db.h +++ b/server/tp_core/core/ts_db.h @@ -4,63 +4,63 @@ #include "ts_session.h" #include -#include +//#include #include -#include -typedef std::map sqlite3Map; +// #include +// typedef std::map sqlite3Map; +// +// typedef struct TS_DB_AUTH_INFO +// { +// ex_astr host_ip; +// int host_port; +// int host_lock; +// int sys_type; +// int protocol; +// int is_encrypt; +// int auth_mode; +// int account_lock; +// ex_astr user_name; +// ex_astr user_auth; +// ex_astr user_param; +// ex_astr account_name; +// }TS_DB_AUTH_INFO; +// +// typedef struct TS_DB_AUTH_INFO_2 +// { +// int auth_id; +// int host_id; +// ex_astr host_ip; +// int pro_type; +// int auth_mode; +// int host_lock; +// }TS_DB_AUTH_INFO_2; -typedef struct TS_DB_AUTH_INFO -{ - ex_astr host_ip; - int host_port; - int host_lock; - int sys_type; - int protocol; - int is_encrypt; - int auth_mode; - int account_lock; - ex_astr user_name; - ex_astr user_auth; - ex_astr user_param; - ex_astr account_name; -}TS_DB_AUTH_INFO; +// typedef struct TS_DB_AUTH_INFO_3 +// { +// int host_id; +// ex_astr host_ip; +// ex_astr host_user_name; +// ex_astr host_user_pwd; +// int auth_mode; +// int cert_id; +// ex_astr cert_name; +// ex_astr cert_pri; +// ex_astr cert_pub; +// +// }TS_DB_AUTH_INFO_3; -typedef struct TS_DB_AUTH_INFO_2 -{ - int auth_id; - int host_id; - ex_astr host_ip; - int pro_type; - int auth_mode; - int host_lock; -}TS_DB_AUTH_INFO_2; +// typedef struct TS_DB_SERVER_CONFIG +// { +// ex_astr ts_server_rpc_ip; +// int ts_server_rpc_port; +// int ts_server_rdp_port; +// int ts_server_ssh_port; +// int ts_server_telnet_port; +// }TS_DB_SERVER_CONFIG; -typedef struct TS_DB_AUTH_INFO_3 -{ - int host_id; - ex_astr host_ip; - ex_astr host_user_name; - ex_astr host_user_pwd; - int auth_mode; - int cert_id; - ex_astr cert_name; - ex_astr cert_pri; - ex_astr cert_pub; - -}TS_DB_AUTH_INFO_3; - -typedef struct TS_DB_SERVER_CONFIG -{ - ex_astr ts_server_rpc_ip; - int ts_server_rpc_port; - int ts_server_rdp_port; - int ts_server_ssh_port; - int ts_server_telnet_port; -}TS_DB_SERVER_CONFIG; - -typedef std::vector AuthInfo2Vec; -typedef std::vector AuthInfo3Vec; +// typedef std::vector AuthInfo2Vec; +// typedef std::vector AuthInfo3Vec; class TsDB { public: @@ -70,31 +70,18 @@ public: // 根据认证ID获取认证信息(包括服务器IP、端口,用户名、密码或私钥、协议如RDP或SSH等等) bool get_auth_info(int auth_id, Json::Value& jret); -// bool get_cert_pri(int cert_id, ex_astr& cert_pri); - // 授权的主机数量 -// bool get_host_count(int& count); - // 重置log日志状态 bool update_reset_log(); - bool session_begin(TS_SESSION_INFO& info, int& sid); + // 记录会话的开始 + bool session_begin(TS_SESSION_INFO& info, int& record_id); //session 结束 bool session_end(int id,int ret_code); - //获取所有的认证ID -// bool get_auth_id_list_by_all(AuthInfo2Vec& auth_info_list); - //通过IP获取认证ID -// bool get_auth_id_list_by_ip(ex_astr host_ip, AuthInfo2Vec& auth_info_list); - //获取所有的认证的信息 -// bool get_auth_info_list_by_all(AuthInfo3Vec& auth_info_list); - //通过IP获取认证信息 -// bool get_auth_info_list_by_ip(ex_astr host_ip, AuthInfo3Vec& auth_info_list); -// //获取server 的配置信息 -// bool get_server_config(TS_DB_SERVER_CONFIG* server_config); -// -protected: - sqlite3* get_db(); -private: - ExThreadLock m_lock; - sqlite3Map m_sqlite3Map; + +// protected: +// sqlite3* get_db(); +// private: +// ExThreadLock m_lock; +// sqlite3Map m_sqlite3Map; }; extern TsDB g_db; diff --git a/server/tp_core/core/ts_http_rpc.cpp b/server/tp_core/core/ts_http_rpc.cpp index e954e74..eb10fa2 100644 --- a/server/tp_core/core/ts_http_rpc.cpp +++ b/server/tp_core/core/ts_http_rpc.cpp @@ -4,7 +4,7 @@ #include "ts_crypto.h" #include "ts_db.h" -#include +//#include #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W') diff --git a/server/www/teleport/app/eom_app/app/session.py b/server/www/teleport/app/eom_app/app/session.py index 4b48764..faa3011 100644 --- a/server/www/teleport/app/eom_app/app/session.py +++ b/server/www/teleport/app/eom_app/app/session.py @@ -72,6 +72,7 @@ class WebSession(threading.Thread): self._session_dict[s_id] = {'v': value, 't': int(datetime.datetime.utcnow().timestamp()), 'e': expire} def get(self, s_id, _default=None): + # 浠巗ession涓幏鍙栦竴涓暟鎹紙璇诲彇骞舵洿鏂版渶鍚庤闂椂闂达級 with self._lock: if s_id in self._session_dict: if self._session_dict[s_id]['e'] == 0: @@ -87,6 +88,15 @@ class WebSession(threading.Thread): else: return _default + def taken(self, s_id, _default=None): + # 浠巗ession涓彇璧颁竴涓暟鎹紙璇诲彇骞跺垹闄わ級 + with self._lock: + if s_id in self._session_dict: + ret = self._session_dict[s_id]['v'] + del self._session_dict[s_id] + return ret + else: + return _default def web_session(): """ diff --git a/server/www/teleport/app/eom_app/app/util.py b/server/www/teleport/app/eom_app/app/util.py index 13f9279..0d47a05 100644 --- a/server/www/teleport/app/eom_app/app/util.py +++ b/server/www/teleport/app/eom_app/app/util.py @@ -23,7 +23,7 @@ from .configs import app_cfg cfg = app_cfg() -__all__ = ['async_post_http'] +__all__ = ['async_post_http', 'async_enc'] @tornado.gen.coroutine @@ -43,6 +43,62 @@ def async_post_http(url, values): return None +@tornado.gen.coroutine +def async_enc(data): + # # url = cfg.ts_enc_url + # config_list = set.get_config_list() + # rpc_port = 52080 + # if 'ts_server_rpc_port' in config_list: + # rpc_port = int(config_list['ts_server_rpc_port']) + # ts_server_rpc_ip = '127.0.0.1' + # if 'ts_server_rpc_ip' in config_list: + # ts_server_rpc_ip = config_list['ts_server_rpc_ip'] + # + ts_server_rpc_ip = cfg.core.rpc.ip + ts_server_rpc_port = cfg.core.rpc.port + + # url = 'http://{}:{}/enc'.format(ts_server_rpc_ip, ts_server_rpc_port) + # + # values = dict() + # if not isinstance(data, str): + # data = "{}".format(data) + # + # values['p'] = data + # return_data = post_http(url, values) + # if return_data is None: + # return -2, '' + # + # if return_data is not None: + # return_data = json.loads(return_data) + # else: + # return -3, '' + + url = 'http://{}:{}/rpc'.format(ts_server_rpc_ip, ts_server_rpc_port) + req = {'method': 'enc', 'param': {'p': data}} + _yr = async_post_http(url, req) + return_data = yield _yr + if return_data is None: + return {'code': -2} + if 'code' not in return_data: + return {'code': -3} + if return_data['code'] != 0: + return {'code': return_data['code']} + + # ret_code = return_data['code'] + # if ret_code != 0: + # return ret_code, '' + if 'data' not in return_data: + return {'code': -5} + + # data = return_data['data'] + if 'c' not in return_data['data']: + return {'code': -6} + + return {'code': 0, 'data': return_data['data']['c']} + + # return 0, decry_data + + _chars = 'ACDEFHJKLMNPQRTVWXY34679' diff --git a/server/www/teleport/app/eom_app/controller/__init__.py b/server/www/teleport/app/eom_app/controller/__init__.py index 0f7cacc..6c2f202 100644 --- a/server/www/teleport/app/eom_app/controller/__init__.py +++ b/server/www/teleport/app/eom_app/controller/__init__.py @@ -90,8 +90,8 @@ controllers = [ (r'/host/update-group', host.UpdateGroup), (r'/host/delete-group', host.DeleteGroup), (r'/host/add-host-to-group', host.AddHostToGroup), - (r'/host/get-host-extend-info', host.GetHostExtendInfo), - (r'/host/update-host-extend-info', host.UpdateHostExtendInfo), + # (r'/host/get-host-extend-info', host.GetHostExtendInfo), + # (r'/host/update-host-extend-info', host.UpdateHostExtendInfo), (r'/host/update', host.UpdateHandler), (r'/host/load-file', host.LoadFile), (r'/host/', host.IndexHandler), diff --git a/server/www/teleport/app/eom_app/controller/base.py b/server/www/teleport/app/eom_app/controller/base.py index 7b7e056..4c327a5 100644 --- a/server/www/teleport/app/eom_app/controller/base.py +++ b/server/www/teleport/app/eom_app/controller/base.py @@ -115,6 +115,7 @@ class SwxJsonpHandler(SwxAppHandler): if data is None: self.write('})') + self.finish() return if not isinstance(data, dict): @@ -123,6 +124,7 @@ class SwxJsonpHandler(SwxAppHandler): self.write(',data:') self.write(json_encode(data)) self.write('})') + self.finish() class SwxJsonHandler(SwxAppHandler): @@ -149,6 +151,7 @@ class SwxJsonHandler(SwxAppHandler): self.set_header("Content-Type", "application/json") self.write(json_encode(_ret)) + self.finish() def write_raw_json(self, data=None): @@ -157,6 +160,7 @@ class SwxJsonHandler(SwxAppHandler): self.set_header("Content-Type", "application/json") self.write(json_encode(data)) + self.finish() class SwxAuthHandler(SwxAppHandler): diff --git a/server/www/teleport/app/eom_app/controller/host.py b/server/www/teleport/app/eom_app/controller/host.py index 9f72216..4476076 100644 --- a/server/www/teleport/app/eom_app/controller/host.py +++ b/server/www/teleport/app/eom_app/controller/host.py @@ -3,6 +3,7 @@ import time import csv import os +import threading import urllib import urllib.parse import urllib.request @@ -15,12 +16,15 @@ from eom_app.app.util import * from eom_app.module import host from eom_app.module.common import * from eom_common.eomcore.logger import * +from eom_app.app.session import web_session from .base import SwxAuthHandler, SwxAuthJsonHandler, SwxAdminJsonHandler cfg = app_cfg() # 涓存椂璁よ瘉ID鐨勫熀鏁帮紝姣忔浣跨敤鏃跺潎閫掑噺 tmp_auth_id_base = -1 +tmp_auth_id_lock = threading.RLock() + class IndexHandler(SwxAuthHandler): def get(self): @@ -33,7 +37,7 @@ class IndexHandler(SwxAuthHandler): try: # f = open(var_js, 'w') _type = _user['type'] - config_list = set.get_config_list() + # config_list = set.get_config_list() ts_server = dict() # ts_server['ip'] = config_list['ts_server_ip'] # ts_server['ip'] = cfg['ts_server_ip'] @@ -63,8 +67,8 @@ class IndexHandler(SwxAuthHandler): else: group_list = host.get_group_list() - if config_list is None: - return + # if config_list is None: + # return self.render('host/common_index.mako', group_list=group_list, @@ -72,9 +76,12 @@ class IndexHandler(SwxAuthHandler): class LoadFile(SwxAuthJsonHandler): - def get(self): - pass + # def get(self): + # pass + # TODO: 瀵煎叆鎿嶄綔鍙兘浼氭瘮杈冭楁椂锛屽簲璇ュ垎绂诲鍏ュ拰鑾峰彇瀵煎叆鐘舵佷袱涓繃绋嬶紝鍦ㄩ〉闈笂鍙互鍛堢幇瀵煎叆杩涘害锛屽苟鍒楀嚭瀵煎嚭鎴愬姛/澶辫触鐨勯」 + + @tornado.gen.coroutine def post(self): """ csv瀵煎叆瑙勫垯锛 @@ -179,10 +186,22 @@ class LoadFile(SwxAuthJsonHandler): elif auth_mode == 1: try: if is_encrpty == 0: - ret_code, tmp_pswd = get_enc_data(user_pswd) + # ret_code, tmp_pswd = get_enc_data(user_pswd) + _yr = async_enc(user_pswd) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + tmp_pswd = return_data['data'] + else: tmp_pswd = user_pswd + user_args['user_pswd'] = tmp_pswd + except Exception: ret_code = -1 log.e('get_enc_data() failed.\n') @@ -220,8 +239,6 @@ class LoadFile(SwxAuthJsonHandler): if os.path.exists(csv_filename): os.remove(csv_filename) - # self.write_json(0) - class GetListHandler(SwxAuthJsonHandler): def post(self): @@ -525,13 +542,13 @@ class GetCertList(SwxAuthJsonHandler): class AddCert(SwxAuthJsonHandler): + + @tornado.gen.coroutine def post(self): args = self.get_argument('args', None) if args is not None: args = json.loads(args) - # print('args', args) else: - # ret = {'code':-1} self.write_json(-1) return @@ -542,25 +559,36 @@ class AddCert(SwxAuthJsonHandler): if len(cert_pri) == 0: self.write_json(-1) return - try: - ret_code, cert_pri = get_enc_data(cert_pri) - except Exception as e: - self.write_json(-100) - return - if 0 != ret_code: - self.write_json(ret_code) - return + + # ret_code, cert_pri = + _yr = async_enc(cert_pri) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + cert_pri = return_data['data'] + + + # try: + # ret_code, cert_pri = get_enc_data(cert_pri) + # except Exception as e: + # self.write_json(-100) + # return + # if 0 != ret_code: + # self.write_json(ret_code) + # return try: ret = host.add_cert(cert_pub, cert_pri, cert_name) if ret: - self.write_json(0) + return self.write_json(0) else: - self.write_json(-1) - return + return self.write_json(-1) except: - self.write_json(-1) - return + return self.write_json(-1) class DeleteCert(SwxAuthJsonHandler): @@ -587,6 +615,8 @@ class DeleteCert(SwxAuthJsonHandler): class UpdateCert(SwxAuthJsonHandler): + + @tornado.gen.coroutine def post(self): args = self.get_argument('args', None) if args is not None: @@ -602,14 +632,22 @@ class UpdateCert(SwxAuthJsonHandler): cert_name = args['cert_name'] if len(cert_pri) > 0: - try: - ret_code, cert_pri = get_enc_data(cert_pri) - except Exception as e: - self.write_json(-100) - return - if 0 != ret_code: - self.write_json(ret_code) - return + _yr = async_enc(cert_pri) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + cert_pri = return_data['data'] + # + # try: + # ret_code, cert_pri = get_enc_data(cert_pri) + # except Exception as e: + # return self.write_json(-100) + # if 0 != ret_code: + # return self.write_json(ret_code) try: ret = host.update_cert(cert_id, cert_pub, cert_pri, cert_name) @@ -717,63 +755,63 @@ class AddHostToGroup(SwxAuthJsonHandler): return -class GetHostExtendInfo(SwxAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - try: - host_id = args['host_id'] - _host = host.get_host_extend_info(host_id) - self.write_json(0, data=_host) - return - except: - self.write_json(-1) - return - - -class UpdateHostExtendInfo(SwxAuthJsonHandler): - def post(self): - args = self.get_argument('args', None) - if args is not None: - args = json.loads(args) - # print('args', args) - else: - # ret = {'code':-1} - self.write_json(-1) - return - host_id = args['host_id'] - - if args['host_auth_mode'] == 1: - if len(args['user_pwd']) > 0: - try: - ret_code, tmp_pswd = get_enc_data(args['user_pwd']) - except Exception as e: - self.write_json(-100) - return - if 0 != ret_code: - self.write_json(ret_code) - return - - args['user_pwd'] = tmp_pswd - - # ip = args['ip'] - # port = args['port'] - # user_name = args['user_name'] - # user_pwd = args['user_pwd'] - # cert_id = args['cert_id'] - # pro_type = args['pro_type'] - ret = host.update_host_extend_info(host_id, args) - if ret: - self.write_json(0) - else: - self.write_json(-1) - +# class GetHostExtendInfo(SwxAuthJsonHandler): +# def post(self): +# args = self.get_argument('args', None) +# if args is not None: +# args = json.loads(args) +# # print('args', args) +# else: +# # ret = {'code':-1} +# self.write_json(-1) +# return +# try: +# host_id = args['host_id'] +# _host = host.get_host_extend_info(host_id) +# self.write_json(0, data=_host) +# return +# except: +# self.write_json(-1) +# return +# +# +# class UpdateHostExtendInfo(SwxAuthJsonHandler): +# def post(self): +# args = self.get_argument('args', None) +# if args is not None: +# args = json.loads(args) +# # print('args', args) +# else: +# # ret = {'code':-1} +# self.write_json(-1) +# return +# host_id = args['host_id'] +# +# if args['host_auth_mode'] == 1: +# if len(args['user_pwd']) > 0: +# try: +# ret_code, tmp_pswd = get_enc_data(args['user_pwd']) +# except Exception as e: +# self.write_json(-100) +# return +# if 0 != ret_code: +# self.write_json(ret_code) +# return +# +# args['user_pwd'] = tmp_pswd +# +# # ip = args['ip'] +# # port = args['port'] +# # user_name = args['user_name'] +# # user_pwd = args['user_pwd'] +# # cert_id = args['cert_id'] +# # pro_type = args['pro_type'] +# ret = host.update_host_extend_info(host_id, args) +# if ret: +# self.write_json(0) +# else: +# self.write_json(-1) +# class GetSessionId(SwxAuthJsonHandler): @tornado.gen.coroutine @@ -828,6 +866,7 @@ class GetSessionId(SwxAuthJsonHandler): class AdminGetSessionId(SwxAuthJsonHandler): + @tornado.gen.coroutine def post(self, *args, **kwargs): args = self.get_argument('args', None) if args is not None: @@ -839,38 +878,34 @@ class AdminGetSessionId(SwxAuthJsonHandler): if 'host_auth_id' not in args: self.write_json(-1) return - host_auth_id = args['host_auth_id'] + + _host_auth_id = int(args['host_auth_id']) + + user = self.get_current_user() # host_auth_id 瀵瑰簲鐨勬槸 ts_auth_info 琛ㄤ腑鐨勬煇涓潯鐩紝鍚湁鍏蜂綋鐨勮璇佹暟鎹紝鍥犱负绠$悊鍛樻棤闇鎺堟潈鍗冲彲璁块棶鎵鏈夎繙绋嬩富鏈猴紝鍥犳 - # 鐩存帴缁欏嚭 host_auth_id锛屼笖account鐩存帴鎸囨槑鏄痑dmin锛孴ODO: 搴旇鏄綋鍓嶇櫥褰曠敤鎴风殑鐢ㄦ埛鍚嶏紝杩欐牱鑳藉鑷傚簲 + # 鐩存帴缁欏嚭 host_auth_id锛屼笖account鐩存帴鎸囨槑鏄綋鍓嶇櫥褰曠敤鎴凤紙鍏跺繀鐒舵槸绠$悊鍛橈級 - # TODO: 浠庢暟鎹簱涓煡璇㈠搴旂殑璁よ瘉鏁版嵁鍚庯紝缂撳瓨鍒板唴瀛樹腑骞跺搴斾竴涓礋鏁扮殑auth_id锛屽彂缁檆ore鏈嶅姟锛屼粠鑰屽彇寰椾竴涓猻ession-id. - - values = host.get_host_auth_info(host_auth_id) - if values is None: + tmp_auth_info = host.get_host_auth_info(_host_auth_id) + if tmp_auth_info is None: self.write_json(-1) return - values['account'] = 'admin' - # config_list = host.get_config_list() - # ts_server_rpc_ip = '127.0.0.1' - # - # if 'ts_server_rpc_ip' in config_list: - # ts_server_rpc_ip = config_list['ts_server_rpc_ip'] - # ts_server_rpc_port = 52080 - # if 'ts_server_rpc_port' in config_list: - # ts_server_rpc_port = config_list['ts_server_rpc_port'] + tmp_auth_info['account_lock'] = 0 + tmp_auth_info['account_name'] = user['name'] + ts_server_rpc_ip = cfg.core.rpc.ip ts_server_rpc_port = cfg.core.rpc.port - url = 'http://{}:{}/request_session'.format(ts_server_rpc_ip, ts_server_rpc_port) - req = {'method': 'request_session', 'param': {'authid': auth_id}} - # values['auth_id'] = auth_id - # return_data = post_http(url, values) - # if return_data is None: - # return self.write_json(-1) - # return_data = json.loads(return_data) + with tmp_auth_id_lock: + global tmp_auth_id_base + tmp_auth_id_base -= 1 + auth_id = tmp_auth_id_base + web_session().set('tmp-auth-info-{}'.format(auth_id), tmp_auth_info, 10) + + url = 'http://{}:{}/rpc'.format(ts_server_rpc_ip, ts_server_rpc_port) + req = {'method': 'request_session', 'param': {'authid': auth_id}} _yr = async_post_http(url, req) return_data = yield _yr if return_data is None: @@ -878,12 +913,14 @@ class AdminGetSessionId(SwxAuthJsonHandler): if 'code' not in return_data: return self.write_json(-1) + _code = return_data['code'] if _code != 0: return self.write_json(_code) + try: session_id = return_data['data']['sid'] - except: + except IndexError: return self.write_json(-1) data = dict() @@ -893,6 +930,7 @@ class AdminGetSessionId(SwxAuthJsonHandler): class AdminFastGetSessionId(SwxAdminJsonHandler): + @tornado.gen.coroutine def post(self, *args, **kwargs): args = self.get_argument('args', None) if args is not None: @@ -901,88 +939,83 @@ class AdminFastGetSessionId(SwxAdminJsonHandler): self.write_json(-1) return + user = self.get_current_user() + + tmp_auth_info = dict() + try: - host_ip = args['host_ip'] - host_port = args['host_port'] - sys_type = args['sys_type'] - user_name = args['user_name'] - user_pswd = args['user_pswd'] - host_auth_id = args['host_auth_id'] - cert_id = args['cert_id'] - auth_mode = args['auth_mode'] - protocol = args['protocol'] - user_param = args['user_param'] - except Exception as e: + _host_auth_id = int(args['host_auth_id']) + _user_pswd = args['user_pswd'] + _cert_id = int(args['cert_id']) + + tmp_auth_info['host_ip'] = args['host_ip'] + tmp_auth_info['host_port'] = int(args['host_port']) + tmp_auth_info['sys_type'] = int(args['sys_type']) + tmp_auth_info['protocol'] = int(args['protocol']) + tmp_auth_info['user_name'] = args['user_name'] + tmp_auth_info['auth_mode'] = int(args['auth_mode']) + tmp_auth_info['user_param'] = args['user_param'] + tmp_auth_info['encrypt'] = 1 + tmp_auth_info['account_lock'] = 0 + tmp_auth_info['account_name'] = user['name'] + except IndexError: self.write_json(-2) return - values = dict() - values['ip'] = host_ip - values['port'] = int(host_port) - values['systype'] = int(sys_type) - - values['uname'] = user_name - values['uparam'] = user_param - values['authmode'] = int(auth_mode) - - values['protocol'] = int(protocol) - values['enc'] = 1 - - if auth_mode == 1: - if len(user_pswd) == 0: - h = host.get_host_auth_info(host_auth_id) - tmp_pswd = h['uauth'] - else: - ret_code, tmp_pswd = get_enc_data(user_pswd) - if ret_code != 0: - self.write_json(-99) - return - values['uauth'] = tmp_pswd - elif auth_mode == 2: - uauth = host.get_cert_info(int(cert_id)) - if uauth is None: - self.write_json(-100) - return - values['uauth'] = uauth - elif auth_mode == 0: - values['uauth'] = '' - else: - self.write_json(-101) - return - - values['account'] = 'admin' - ts_server_rpc_ip = cfg.core.rpc.ip ts_server_rpc_port = cfg.core.rpc.port - # 涓虹粺涓璋冪敤褰㈠紡锛岃繖閲屽厛灏嗗瘑鐮佹垨绉侀挜浼犻掔粰core鏈嶅姟鍔犲瘑锛岀劧鍚庣敓鎴愪竴涓复鏃惰璇佷俊鎭緵鍚庣画request_session鏃禼ore鏈嶅姟鏉ヨ幏鍙 + if tmp_auth_info['auth_mode'] == 1: + if len(_user_pswd) == 0: # 淇敼鐧诲綍鐢ㄦ埛淇℃伅鏃跺彲鑳戒笉浼氫慨鏀瑰瘑鐮侊紝鍥犳椤甸潰涓婂彲鑳戒笉浼氫紶鏉ュ瘑鐮侊紝闇瑕佷粠鏁版嵁搴撲腑鐩存帴璇诲彇 + h = host.get_host_auth_info(_host_auth_id) + tmp_auth_info['user_auth'] = h['user_auth'] + else: # 濡傛灉椤甸潰涓婁慨鏀逛簡瀵嗙爜鎴栬呮柊寤鸿处鍙锋椂璁惧畾浜嗗瘑鐮侊紝閭d箞闇瑕佸厛浜ょ粰core鏈嶅姟杩涜鍔犲瘑 + url = 'http://{}:{}/rpc'.format(ts_server_rpc_ip, ts_server_rpc_port) + req = {'method': 'enc', 'param': {'p': _user_pswd}} + _yr = async_post_http(url, req) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + tmp_auth_info['user_auth'] = return_data['data']['c'] + + elif tmp_auth_info['auth_mode'] == 2: + tmp_auth_info['user_auth'] = host.get_cert_info(_cert_id) + if tmp_auth_info['user_auth'] is None: + self.write_json(-100) + return + elif tmp_auth_info['auth_mode'] == 0: + tmp_auth_info['user_auth'] = '' + else: + self.write_json(-101) + return + + with tmp_auth_id_lock: + global tmp_auth_id_base + tmp_auth_id_base -= 1 + auth_id = tmp_auth_id_base + + web_session().set('tmp-auth-info-{}'.format(auth_id), tmp_auth_info, 10) + url = 'http://{}:{}/rpc'.format(ts_server_rpc_ip, ts_server_rpc_port) - req = {'method': 'enc', 'param': {'p': values['uauth']}} + req = {'method': 'request_session', 'param': {'authid': auth_id}} _yr = async_post_http(url, req) return_data = yield _yr if return_data is None: return self.write_json(-1) - if 'code' not in return_data or return_data['code'] != 0: - return self.write_json(-1) - values['uauth'] = return_data['data']['c'] - - # TODO: 鐢熸垚涓涓复鏃惰璇佷俊鎭鐢紙濡備綍淇濊瘉涓存椂鐨刟uth_id鍞竴锛燂級 - - url = 'http://{}:{}/request_session'.format(ts_server_rpc_ip, ts_server_rpc_port) - # values['auth_id'] = auth_id - return_data = post_http(url, values) - if return_data is None: - return self.write_json(-1) - return_data = json.loads(return_data) if 'code' not in return_data: return self.write_json(-1) + _code = return_data['code'] if _code != 0: return self.write_json(_code) + try: session_id = return_data['data']['sid'] - except: + except IndexError: return self.write_json(-1) data = dict() @@ -1010,36 +1043,45 @@ class SysUserList(SwxAuthJsonHandler): class SysUserAdd(SwxAuthJsonHandler): + @tornado.gen.coroutine def post(self, *args, **kwargs): args = self.get_argument('args', None) if args is not None: args = json.loads(args) else: - self.write_json(-1) - return + return self.write_json(-1) try: auth_mode = args['auth_mode'] user_pswd = args['user_pswd'] cert_id = args['cert_id'] - except Exception as e: - self.write_json(-2) - return + except IndexError: + return self.write_json(-2) if auth_mode == 1: if 0 == len(args['user_pswd']): - self.write_json(-1) - return - try: - ret_code, tmp_pswd = get_enc_data(user_pswd) - except Exception as e: - self.write_json(ret_code) - return - if 0 != ret_code: - self.write_json(ret_code) - return + return self.write_json(-1) - args['user_pswd'] = tmp_pswd + _yr = async_enc(user_pswd) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) + + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + args['user_pswd'] = return_data['data'] + + # try: + # ret_code, tmp_pswd = get_enc_data(user_pswd) + # except Exception as e: + # self.write_json(ret_code) + # return + # if 0 != ret_code: + # self.write_json(ret_code) + # return + # + # args['user_pswd'] = tmp_pswd if host.sys_user_add(args) < 0: return self.write_json(-1) @@ -1048,6 +1090,7 @@ class SysUserAdd(SwxAuthJsonHandler): class SysUserUpdate(SwxAuthJsonHandler): + @tornado.gen.coroutine def post(self, *args, **kwargs): args = self.get_argument('args', None) if args is not None: @@ -1078,16 +1121,25 @@ class SysUserUpdate(SwxAuthJsonHandler): cert_id = kv['cert_id'] if auth_mode == 1 and user_pswd is not None: - try: - ret_code, tmp_pswd = get_enc_data(user_pswd) - except Exception as e: - self.write_json(-100) - return - if 0 != ret_code: - self.write_json(ret_code) - return + # try: + # ret_code, tmp_pswd = get_enc_data(user_pswd) + # except Exception as e: + # self.write_json(-100) + # return + # if 0 != ret_code: + # self.write_json(ret_code) + # return + # + # args['kv']['user_pswd'] = tmp_pswd + _yr = async_enc(user_pswd) + return_data = yield _yr + if return_data is None: + return self.write_json(-1) - args['kv']['user_pswd'] = tmp_pswd + if 'code' not in return_data or return_data['code'] != 0: + return self.write_json(-1) + + args['kv']['user_pswd'] = return_data['data'] if host.sys_user_update(args['host_auth_id'], args['kv']): return self.write_json(0) diff --git a/server/www/teleport/app/eom_app/controller/rpc.py b/server/www/teleport/app/eom_app/controller/rpc.py index ddbe697..f1f5777 100644 --- a/server/www/teleport/app/eom_app/controller/rpc.py +++ b/server/www/teleport/app/eom_app/controller/rpc.py @@ -5,7 +5,8 @@ import tornado.gen import json import urllib.parse -from eom_app.module import host +from eom_app.app.session import web_session +from eom_app.module import host, record from .base import SwxJsonHandler @@ -20,7 +21,6 @@ class RpcHandler(SwxJsonHandler): return yield self._dispatch(urllib.parse.unquote(_uri[1])) - self.finish() @tornado.gen.coroutine def post(self): @@ -31,7 +31,6 @@ class RpcHandler(SwxJsonHandler): return yield self._dispatch(req) - self.finish() @tornado.gen.coroutine def _dispatch(self, req): @@ -61,35 +60,69 @@ class RpcHandler(SwxJsonHandler): self.write_json(-1, message='invalid method.') def _get_auth_info(self, param): - # todo: 濡傛灉鏄〉闈笂杩涜杩炴帴娴嬭瘯锛堝鍔犳垨淇敼涓绘満鍜岀敤鎴锋椂锛夛紝淇℃伅骞朵笉鍐欏叆鏁版嵁搴擄紝鑰屾槸鍦ㄥ唴瀛樹腑瀛樺湪锛屼紶閫掔粰core鏈嶅姟鐨 - # 搴旇鏄礋鏁板舰寮忕殑authid銆傛湰鎺ュ彛搴旇鏀寔鍖哄垎杩欎袱绉嶈璇両D銆 + # 濡傛灉鏄〉闈笂杩涜杩炴帴娴嬭瘯锛堝鍔犳垨淇敼涓绘満鍜岀敤鎴锋椂锛夛紝淇℃伅骞朵笉鍐欏叆鏁版嵁搴擄紝鑰屾槸鍦ㄥ唴瀛樹腑瀛樺湪锛屼紶閫掔粰core鏈嶅姟鐨 + # 搴旇鏄礋鏁板舰寮忕殑authid銆傛湰鎺ュ彛鏀寔鍖哄垎杩欎袱绉嶈璇両D銆 if 'authid' not in param: self.write_json(-1, message='invalid request.') return - # 鏍规嵁authid浠庢暟鎹簱涓煡璇㈠搴旂殑鏁版嵁锛岀劧鍚庤繑鍥炵粰璋冪敤鑰 - x = host.get_auth_info(param['authid']) - print('get_auth_info():', x) - - self.write_json(0, data=x) + authid = param['authid'] + if authid > 0: + # 鏍规嵁authid浠庢暟鎹簱涓煡璇㈠搴旂殑鏁版嵁锛岀劧鍚庤繑鍥炵粰璋冪敤鑰 + x = host.get_auth_info(param['authid']) + print('get_auth_info():', x) + self.write_json(0, data=x) + elif authid < 0: + x = web_session().taken('tmp-auth-info-{}'.format(authid), None) + print('get_auth_info():', x) + self.write_json(0, data=x) + else: + self.write_json(-1, message='invalid auth id.') def _session_begin(self, param): if 'sid' not in param: - self.write_json(-1, message='invalid request.') - return + return self.write_json(-1, message='invalid request.') - self.write_json(0, data={'rid': 12}) + # jreq["param"]["sid"] = info.sid.c_str(); + # jreq["param"]["account_name"] = info.account_name.c_str(); + # jreq["param"]["host_ip"] = info.host_ip.c_str(); + # jreq["param"]["sys_type"] = info.sys_type; + # jreq["param"]["host_port"] = info.host_port; + # jreq["param"]["auth_mode"] = info.auth_mode, + # jreq["param"]["user_name"] = info.user_name.c_str(); + # jreq["param"]["protocol"] = info.protocol; + + try: + _sid = param['sid'] + _acc_name = param['account_name'] + _host_ip = param['host_ip'] + _sys_type = param['sys_type'] + _host_port = param['host_port'] + _auth_mode = param['auth_mode'] + _user_name = param['user_name'] + _protocol = param['protocol'] + except IndexError: + return self.write_json(-1, message='invalid request.') + + record_id = record.session_begin(_sid, _acc_name, _host_ip, _sys_type, _host_port, _auth_mode, _user_name, _protocol) + if record_id <= 0: + self.write_json(-1, message='can not write database.') + else: + self.write_json(0, data={'rid': record_id}) def _session_end(self, param): if 'rid' not in param or 'code' not in param: self.write_json(-1, message='invalid request.') return - self.write_json(0) + if not record.session_end(param['rid'], param['code']): + self.write_json(-1) + else: + self.write_json(0) def _session_fix(self): - # do db operation. + record.session_fix() self.write_json(0) def _exit(self): diff --git a/server/www/teleport/app/eom_app/module/common.py b/server/www/teleport/app/eom_app/module/common.py index 95232b6..4f067b6 100644 --- a/server/www/teleport/app/eom_app/module/common.py +++ b/server/www/teleport/app/eom_app/module/common.py @@ -8,7 +8,7 @@ import urllib.request import eom_common.eomcore.eom_mysql as mysql import eom_common.eomcore.eom_sqlite as sqlite from eom_app.app.configs import app_cfg -from eom_app.module import set +# from eom_app.module import set cfg = app_cfg() @@ -35,72 +35,72 @@ def get_db_con(): return sql_exec -def post_http(url, values): - try: - # log.v('post_http(), url={}\n'.format(url)) - - user_agent = 'Mozilla/4.0 (compatible;MSIE 5.5; Windows NT)' - # values = { - # 'act': 'login', - # 'login[email]': 'yzhang@i9i8.com', - # 'login[password]': '123456' - # } - values = json.dumps(values) - data = urllib.parse.quote(values).encode('utf-8') - # data = urllib.parse.urlencode(values).encode() - headers = {'User-Agent': user_agent} - # url = 'http://www.baidu.com' - req = urllib.request.Request(url=url, data=data, headers=headers) - response = urllib.request.urlopen(req, timeout=3) - the_page = response.read() - info = response.info() - _zip = info.get('Content-Encoding') - if _zip == 'gzip': - the_page = gzip.decompress(the_page) - else: - pass - the_page = the_page.decode() - return the_page - except: - return None +# def post_http(url, values): +# try: +# # log.v('post_http(), url={}\n'.format(url)) +# +# user_agent = 'Mozilla/4.0 (compatible;MSIE 5.5; Windows NT)' +# # values = { +# # 'act': 'login', +# # 'login[email]': 'yzhang@i9i8.com', +# # 'login[password]': '123456' +# # } +# values = json.dumps(values) +# data = urllib.parse.quote(values).encode('utf-8') +# # data = urllib.parse.urlencode(values).encode() +# headers = {'User-Agent': user_agent} +# # url = 'http://www.baidu.com' +# req = urllib.request.Request(url=url, data=data, headers=headers) +# response = urllib.request.urlopen(req, timeout=3) +# the_page = response.read() +# info = response.info() +# _zip = info.get('Content-Encoding') +# if _zip == 'gzip': +# the_page = gzip.decompress(the_page) +# else: +# pass +# the_page = the_page.decode() +# return the_page +# except: +# return None -def get_enc_data(data): - # url = cfg.ts_enc_url - config_list = set.get_config_list() - rpc_port = 52080 - if 'ts_server_rpc_port' in config_list: - rpc_port = int(config_list['ts_server_rpc_port']) - ts_server_rpc_ip = '127.0.0.1' - if 'ts_server_rpc_ip' in config_list: - ts_server_rpc_ip = config_list['ts_server_rpc_ip'] - - url = 'http://{}:{}/enc'.format(ts_server_rpc_ip, rpc_port) - - values = dict() - if not isinstance(data, str): - data = "{}".format(data) - - values['p'] = data - return_data = post_http(url, values) - if return_data is None: - return -2, '' - - if return_data is not None: - return_data = json.loads(return_data) - else: - return -3, '' - - ret_code = return_data['code'] - if ret_code != 0: - return ret_code, '' - if 'data' not in return_data: - return -5, '' - - data = return_data['data'] - if 'c' not in data: - return -6, '' - - decry_data = data['c'] - - return 0, decry_data +# def get_enc_data(data): +# # url = cfg.ts_enc_url +# config_list = set.get_config_list() +# rpc_port = 52080 +# if 'ts_server_rpc_port' in config_list: +# rpc_port = int(config_list['ts_server_rpc_port']) +# ts_server_rpc_ip = '127.0.0.1' +# if 'ts_server_rpc_ip' in config_list: +# ts_server_rpc_ip = config_list['ts_server_rpc_ip'] +# +# url = 'http://{}:{}/enc'.format(ts_server_rpc_ip, rpc_port) +# +# values = dict() +# if not isinstance(data, str): +# data = "{}".format(data) +# +# values['p'] = data +# return_data = post_http(url, values) +# if return_data is None: +# return -2, '' +# +# if return_data is not None: +# return_data = json.loads(return_data) +# else: +# return -3, '' +# +# ret_code = return_data['code'] +# if ret_code != 0: +# return ret_code, '' +# if 'data' not in return_data: +# return -5, '' +# +# data = return_data['data'] +# if 'c' not in data: +# return -6, '' +# +# decry_data = data['c'] +# +# return 0, decry_data diff --git a/server/www/teleport/app/eom_app/module/host.py b/server/www/teleport/app/eom_app/module/host.py index 27fdf66..84c3f18 100644 --- a/server/www/teleport/app/eom_app/module/host.py +++ b/server/www/teleport/app/eom_app/module/host.py @@ -496,7 +496,7 @@ def delete_group(group_id): def update_group(group_id, group_name): sql_exec = get_db_con() str_sql = 'UPDATE ts_group SET group_name = \'{}\' ' \ - ' WHERE group_id = {}'.format(group_name, group_id) + 'WHERE group_id = {}'.format(group_name, group_id) ret = sql_exec.ExecProcNonQuery(str_sql) return ret @@ -531,30 +531,31 @@ def get_host_auth_info(host_auth_id): return None x = DbItem() x.load(db_ret[0], ['a_{}'.format(i) for i in field_a] + ['b_{}'.format(i) for i in field_b]) - h = dict() + print(x) - h['ip'] = x.b_host_ip - h['systype'] = x.b_host_sys_type - h['authmode'] = x.a_auth_mode - h['uname'] = x.a_user_name + h = dict() + h['host_ip'] = x.b_host_ip + h['host_port'] = x.b_host_port + h['sys_type'] = x.b_host_sys_type + h['auth_mode'] = x.a_auth_mode + h['user_name'] = x.a_user_name h['protocol'] = x.b_protocol if x.a_encrypt is None: - h['enc'] = 1 + h['encrypt'] = 1 else: - h['enc'] = x.a_encrypt + h['encrypt'] = x.a_encrypt if x.a_user_param is None: - h['uparam'] = '' + h['user_param'] = '' else: - h['uparam'] = x.a_user_param + h['user_param'] = x.a_user_param - h['uauth'] = x.a_user_pswd - h['port'] = int(x.b_host_port) + h['user_auth'] = x.a_user_pswd # user_auth = x.a_user_auth if x.a_auth_mode == 1: - h['uauth'] = x.a_user_pswd + h['user_auth'] = x.a_user_pswd elif x.a_auth_mode == 2: if x.a_cert_id is None: cert_id = 0 @@ -564,11 +565,11 @@ def get_host_auth_info(host_auth_id): db_ret = sql_exec.ExecProcQuery(str_sql) if db_ret is not None and len(db_ret) == 1: (cert_pri,) = db_ret[0] - h['uauth'] = cert_pri + h['user_auth'] = cert_pri else: return None elif x.a_auth_mode == 0: - h['uauth'] = '' + h['user_auth'] = '' else: return None diff --git a/server/www/teleport/app/eom_app/module/record.py b/server/www/teleport/app/eom_app/module/record.py index eb5f815..60382b3 100644 --- a/server/www/teleport/app/eom_app/module/record.py +++ b/server/www/teleport/app/eom_app/module/record.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import os +import datetime import shutil import struct @@ -202,3 +203,46 @@ def delete_log(log_list): return True except: return False + + +def session_fix(): + try: + sql_exec = get_db_con() + str_sql = 'UPDATE ts_log SET ret_code=7 WHERE ret_code=0;' + return sql_exec.ExecProcNonQuery(str_sql) + except: + return False + + +def session_begin(sid, acc_name, host_ip, sys_type, host_port, auth_mode, user_name, protocol): + try: + _now = int(datetime.datetime.utcnow().timestamp()) + sql_exec = get_db_con() + + str_sql = 'INSERT INTO ts_log (session_id, account_name,host_ip,sys_type, host_port,auth_type, user_name,ret_code,begin_time,end_time,log_time, protocol) ' \ + 'VALUES (\'{}\',\'{}\',\'{}\',{},{},{},\'{}\',{},{},{},\'{}\',{});'.format( + sid, acc_name, host_ip, sys_type, host_port, auth_mode, user_name, 0, _now, 0, '', protocol) + + ret = sql_exec.ExecProcNonQuery(str_sql) + if not ret: + return -101 + + str_sql = 'SELECT last_insert_rowid()' + db_ret = sql_exec.ExecProcQuery(str_sql) + if db_ret is None: + return -102 + user_id = db_ret[0][0] + return user_id + + except: + return False + + +def session_end(record_id, ret_code): + try: + _now = int(datetime.datetime.utcnow().timestamp()) + sql_exec = get_db_con() + str_sql = 'UPDATE ts_log SET ret_code={}, end_time={} WHERE id={};'.format(ret_code, _now, record_id) + return sql_exec.ExecProcNonQuery(str_sql) + except: + return False diff --git a/server/www/teleport/app/eom_app/module/user.py b/server/www/teleport/app/eom_app/module/user.py index cde3f51..3d7dacc 100644 --- a/server/www/teleport/app/eom_app/module/user.py +++ b/server/www/teleport/app/eom_app/module/user.py @@ -210,13 +210,13 @@ def delete_host_user(user_name, auth_id_list): return False -def get_enc_data_helper(data): - try: - ret_code, data = get_enc_data(data) - except Exception as e: - return -100, '' - - return ret_code, data +# def get_enc_data_helper(data): +# try: +# ret_code, data = get_enc_data(data) +# except Exception as e: +# return -100, '' +# +# return ret_code, data def get_log_list(filter, limit): @@ -296,7 +296,7 @@ def get_log_list(filter, limit): if cost_time < 0: cost_time = 0 h['cost_time'] = cost_time - h['log_time'] = x.a_log_time + h['begin_time'] = x.a_begin_time if x.a_protocol is not None: h['protocol'] = x.a_protocol else: diff --git a/server/www/teleport/app/eom_common/eomcore/eom_mysql.py b/server/www/teleport/app/eom_common/eomcore/eom_mysql.py index 3249f5d..d04a93e 100644 --- a/server/www/teleport/app/eom_common/eomcore/eom_mysql.py +++ b/server/www/teleport/app/eom_common/eomcore/eom_mysql.py @@ -100,7 +100,7 @@ class MySQL: if self.connect() is None: self.conn = None - return None + return False cur = self.conn.cursor() cur.execute(sql) diff --git a/server/www/teleport/app/eom_common/eomcore/eom_sqlite.py b/server/www/teleport/app/eom_common/eomcore/eom_sqlite.py index 1c78de5..8ed33c8 100644 --- a/server/www/teleport/app/eom_common/eomcore/eom_sqlite.py +++ b/server/www/teleport/app/eom_common/eomcore/eom_sqlite.py @@ -35,7 +35,6 @@ class eom_sqlite: raise RuntimeError('can not open database.') return self._conn - # 璋冪敤瀹炰緥 ms.ExecProcQuery('exec P_Agent_Cmd_Get @CmdGroupId=7') def ExecProcQuery(self, sql): if self._conn is None: if self.connect() is None: @@ -46,13 +45,11 @@ class eom_sqlite: cursor.execute(sql) db_ret = cursor.fetchall() return db_ret - except Exception as e: + except Exception: return None finally: cursor.close() - # return None - def ExecProcNonQuery(self, sql): if self._conn is None: if self.connect() is None: @@ -62,7 +59,7 @@ class eom_sqlite: try: cursor.execute(sql) self._conn.commit() - except Exception as e: + except Exception: log.e('can not create/open database.\n') return False finally: diff --git a/server/www/teleport/static/js/ui/log.js b/server/www/teleport/static/js/ui/log.js index ffac736..9e093b2 100644 --- a/server/www/teleport/static/js/ui/log.js +++ b/server/www/teleport/static/js/ui/log.js @@ -43,7 +43,7 @@ ywl.on_init = function (cb_stack, cb_args) { {title: "鍗忚", key: "protocol", render: 'protocol', fields: {protocol: 'protocol'}}, {title: "绯荤粺", key: "sys_type", width: 40, render: 'sys_type', fields: {sys_type: 'sys_type'}}, {title: "杩滅▼涓绘満鍦板潃", key: "host_ip", render: 'server_info', fields: {host_ip: 'host_ip', host_port: 'host_port'}}, - {title: "寮濮嬫椂闂", key: "log_time", width: 160, render: 'log_time', fields: {log_time: 'log_time'}}, + {title: "寮濮嬫椂闂", key: "begin_time", width: 160, render: 'begin_time', fields: {begin_time: 'begin_time'}}, {title: "鑰楁椂", key: "cost_time", render: 'cost_time', fields: {cost_time: 'cost_time', ret_code: 'ret_code'}}, {title: "鐘舵", key: "ret_code", render: 'ret_code', fields: {ret_code: 'ret_code'}}, { @@ -257,8 +257,8 @@ ywl.on_host_table_created = function (tbl) { // } }; - render.log_time = function (row_id, fields) { - return '' + fields.log_time + ' '; + render.begin_time = function (row_id, fields) { + return '' + format_datetime(utc_to_local(fields.begin_time)) + ' '; }; render.cost_time = function (row_id, fields) {