def post(self): args = self.get_argument('args', None) if args is not None: args = json.loads(args) else: return self.write_json(-1, '参数错误') cmd = args['cmd'] if cmd == 'create_db': if not get_db().need_create: return self.write_json(-1, '无需创建') task_id = thread_mgr.create_db() return self.write_json(0, data={"task_id": task_id}) if cmd == 'upgrade_db': if not get_db().need_upgrade: return self.write_json(-1, '无需升级') task_id = thread_mgr.upgrade_db() return self.write_json(0, data={"task_id": task_id}) elif cmd == 'get_task_ret': r = thread_mgr.get_task(args['tid']) if r is None: return self.write_json(0, data={'running': False, 'steps': []}) else: return self.write_json(0, data=r) else: self.write_json(-1, '未知命令 `{}`!'.format(cmd))
def get(self): if get_db().need_create: return self.redirect('/maintenance/install') elif get_db().need_upgrade: self.render('maintenance/upgrade.mako') else: self.redirect('/')
def delete_log(log_list): try: where = list() for item in log_list: where.append(' `id`={}'.format(item)) db = get_db() sql = 'DELETE FROM `{}log` WHERE{};'.format(db.table_prefix, ' OR'.join(where)) ret = db.exec(sql) 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().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().core.replay_path, 'rdp', '{:06d}'.format(log_id)) if os.path.exists(record_path): shutil.rmtree(record_path) except Exception: pass return True except: return False
def get_host_auth_info(host_auth_id): db = get_db() field_a = ['id', 'auth_mode', 'user_name', 'user_pswd', 'user_param', 'cert_id', 'encrypt'] field_b = ['host_id', 'host_lock', 'host_ip', 'host_port', 'host_desc', 'group_id', 'host_sys_type', 'protocol'] sql = 'SELECT {},{} ' \ 'FROM `{}auth_info` AS a ' \ 'LEFT JOIN `{}host_info` AS b ON `a`.`host_id`=`b`.`host_id` ' \ 'WHERE `a`.`id`={};'.format(','.join(['`a`.`{}`'.format(i) for i in field_a]), ','.join(['`b`.`{}`'.format(i) for i in field_b]), db.table_prefix, db.table_prefix, host_auth_id) db_ret = db.query(sql) if db_ret is None or len(db_ret) != 1: 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() 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['encrypt'] = 1 else: h['encrypt'] = x.a_encrypt if x.a_user_param is None: h['user_param'] = '' else: h['user_param'] = x.a_user_param h['user_auth'] = x.a_user_pswd if x.a_auth_mode == 1: h['user_auth'] = x.a_user_pswd elif x.a_auth_mode == 2: if x.a_cert_id is None: cert_id = 0 else: cert_id = int(x.a_cert_id) # int(user_auth) sql = 'SELECT `cert_pri` FROM `{}key` WHERE `cert_id`={};'.format(db.table_prefix, cert_id) db_ret = db.query(sql) if db_ret is not None and len(db_ret) == 1: (cert_pri,) = db_ret[0] h['user_auth'] = cert_pri else: return None elif x.a_auth_mode == 0: h['user_auth'] = '' else: return None return h
def verify_user(name, password): cfg = app_cfg() db = get_db() sql = 'SELECT `account_id`, `account_type`, `account_name`, `account_pwd`, `account_lock` FROM `{}account` WHERE `account_name`="{}";'.format(db.table_prefix, name) db_ret = db.query(sql) if db_ret is None: # 特别地,如果无法取得数据库连接,有可能是新安装的系统,尚未建立数据库,此时应该处于维护模式 # 因此可以特别地处理用户验证:用户名admin,密码admin可以登录为管理员 if cfg.app_mode == APP_MODE_MAINTENANCE: if name == 'admin' and password == 'admin': return 1, 100, 'admin', 0 return 0, 0, '', 0 if len(db_ret) != 1: return 0, 0, '', 0 user_id = db_ret[0][0] account_type = db_ret[0][1] name = db_ret[0][2] locked = db_ret[0][4] if locked == 1: return 0, 0, '', locked if not sec_verify_password(password, db_ret[0][3]): # 按新方法验证密码失败,可能是旧版本的密码散列格式,再尝试一下 if db_ret[0][3] != hashlib.sha256(password.encode()).hexdigest(): return 0, 0, '', locked else: # 发现此用户的密码散列格式还是旧的,更新成新的吧! _new_sec_password = sec_generate_password(password) sql = 'UPDATE `{}account` SET `account_pwd`="{}" WHERE `account_id`={}'.format(db.table_prefix, _new_sec_password, int(user_id)) db.exec(sql) return user_id, account_type, name, locked
def get(self): core_detected = False req = {'method': 'get_config', 'param': []} _yr = async_post_http(req) return_data = yield _yr if return_data is not None: if 'code' in return_data: _code = return_data['code'] if _code == 0: cfg.update_core(return_data['data']) core_detected = True if not core_detected: cfg.update_core(None) _db = get_db() db = {'type': _db.db_type} if _db.db_type == _db.DB_TYPE_SQLITE: db['sqlite_file'] = _db.sqlite_file elif _db.db_type == _db.DB_TYPE_MYSQL: db['mysql_host'] = _db.mysql_host db['mysql_port'] = _db.mysql_port db['mysql_db'] = _db.mysql_db db['mysql_user'] = _db.mysql_user param = { 'core': cfg.core, 'web': { 'version': TS_VER, 'core_server_rpc': cfg.common.core_server_rpc, 'db': db } } self.render('config/index.mako', page_param=json.dumps(param))
def alloc_host(user_name, host_list): db = get_db() field_a = ['host_id'] sql = 'SELECT {} FROM `{}auth` AS a WHERE `account_name`="{}";'.format(','.join(['`a`.`{}`'.format(i) for i in field_a]), db.table_prefix, user_name) db_ret = db.query(sql) ret = dict() for item in db_ret: x = DbItem() x.load(item, ['a_{}'.format(i) for i in field_a]) host_id = int(x.a_host_id) ret[host_id] = host_id a_list = list() for item in host_list: if item in ret: pass else: a_list.append(item) try: for item in a_list: host_id = int(item) sql = 'INSERT INTO `{}auth` (`account_name`, `host_id`) VALUES ("{}", {});'.format(db.table_prefix, user_name, host_id) ret = db.exec(sql) if not ret: return False return True except: return False
def session_end(record_id, ret_code): try: db = get_db() sql = 'UPDATE `{}log` SET `ret_code`={}, `end_time`={} WHERE `id`={};'.format(db.table_prefix, int(ret_code), timestamp_utc_now(), int(record_id)) return db.exec(sql) except: return False
def session_fix(): try: db = get_db() sql = 'UPDATE `{}log` SET `ret_code`=7 WHERE `ret_code`=0;'.format(db.table_prefix) return db.exec(sql) except: return False
def get_cert_list(): db = get_db() field_a = ['cert_id', 'cert_name', 'cert_pub', 'cert_pri', 'cert_desc'] sql = 'SELECT {} FROM `{}key` AS a;'.format(','.join(['`a`.`{}`'.format(i) for i in field_a]), db.table_prefix) db_ret = db.query(sql) ret = list() if db_ret is None: return ret for item in db_ret: x = DbItem() x.load(item, ['a_{}'.format(i) for i in field_a]) h = dict() h['cert_id'] = x.a_cert_id if x.a_cert_name is None: x.a_cert_name = '' h['cert_name'] = x.a_cert_name h['cert_pub'] = x.a_cert_pub h['cert_pri'] = x.a_cert_pri if x.a_cert_desc is None: x.a_cert_desc = '' h['cert_desc'] = x.a_cert_desc ret.append(h) return ret
def get_user_list(with_admin=False): db = get_db() ret = list() field_a = ['account_id', 'account_type', 'account_name', 'account_status', 'account_lock', 'account_desc'] if with_admin: where = '' else: where = 'WHERE `a`.`account_type`<100' sql = 'SELECT {} FROM `{}account` as a {} ORDER BY `account_name`;'.format(','.join(['`a`.`{}`'.format(i) for i in field_a]), db.table_prefix, where) db_ret = db.query(sql) if db_ret is None: return ret for item in db_ret: x = DbItem() x.load(item, ['a_{}'.format(i) for i in field_a]) h = dict() h['user_id'] = x.a_account_id h['user_type'] = x.a_account_type h['user_name'] = x.a_account_name h['user_status'] = x.a_account_status h['user_lock'] = x.a_account_lock h['user_desc'] = x.a_account_desc ret.append(h) return ret
def add_host_to_group(host_list, group_id): db = get_db() group_id = int(group_id) for item in host_list: host_id = int(item) sql = 'UPDATE `{}host_info` SET group_id={} ' \ 'WHERE `host_id`={};'.format(db.table_prefix, group_id, host_id) ret = db.exec(sql) return ret
def get_cert_info(cert_id): db = get_db() sql = 'SELECT `cert_pri` FROM `{}key` WHERE `cert_id`={};'.format(db.table_prefix, cert_id) db_ret = db.query(sql) if db_ret is not None and len(db_ret) == 1: (cert_pri,) = db_ret[0] return cert_pri else: return None
def update_oath_secret(user_id, oath_secret): db = get_db() sql = 'UPDATE `{}account` SET `oath_secret`="{}" WHERE `account_id`={}'.format( db.table_prefix, oath_secret, int(user_id)) db_ret = db.exec(sql) if db_ret: return 0 else: return -102
def update_cert(cert_id, cert_pub, cert_pri, cert_name): db = get_db() if 0 == len(cert_pri): sql = 'UPDATE `{}key` SET `cert_pub`="{}",`cert_name`="{}" ' \ 'WHERE `cert_id`={};'.format(db.table_prefix, cert_pub, cert_name, int(cert_id)) else: sql = 'UPDATE `{}key` SET `cert_pub`="{}", `cert_pri`="{}", `cert_name`="{}" ' \ 'WHERE `cert_id`={};'.format(db.table_prefix, cert_pub, cert_pri, cert_name, int(cert_id)) return db.exec(sql)
def sys_user_delete(_id): db = get_db() try: sql = 'DELETE FROM `{}auth_info` WHERE `id`={};'.format(db.table_prefix, int(_id)) ret = db.exec(sql) sql = 'DELETE FROM `{}auth` WHERE `host_auth_id`={};'.format(db.table_prefix, int(_id)) ret = db.exec(sql) except: return False return True
def prepare(self): super().prepare() if self._finished: return reference = self.request.uri user = self.get_current_user() if not user['is_login'] or user['type'] != 100: if reference != '/auth/login': # 防止循环重定向 x = quote(reference) self.redirect('/auth/login?ref={}'.format(x)) else: self.redirect('/auth/login') else: if cfg.app_mode == APP_MODE_MAINTENANCE: if not reference.startswith('/maintenance/'): if get_db().need_create: self.redirect('/maintenance/install') elif get_db().need_upgrade: self.redirect('/maintenance/upgrade')
def delete_host_user(user_name, auth_id_list): db = get_db() try: for item in auth_id_list: auth_id = int(item) sql = 'DELETE FROM `{}auth` WHERE `account_name`="{}" AND `auth_id`={};'.format(db.table_prefix, user_name, auth_id) ret = db.exec(sql) if not ret: return False return True except: return False
def delete_group(group_id): db = get_db() sql = 'SELECT `host_id` FROM `{}host_info` WHERE `group_id`={};'.format(db.table_prefix, int(group_id)) db_ret = db.query(sql) if len(db_ret) != 0: return -2 sql = 'DELETE FROM `{}group` WHERE `group_id`={};'.format(db.table_prefix, group_id) ret = db.exec(sql) if ret: return 0 return -3
def _create_db(self, tid): def _step_begin(msg): return self._step_begin(tid, msg) def _step_end(sid, code, msg=None): self._step_end(tid, sid, code, msg) if get_db().create_and_init(_step_begin, _step_end): cfg.app_mode = APP_MODE_NORMAL # self._step_begin(tid, '操作已完成') self._thread_end(tid)
def _upgrade_db(self, tid): def _step_begin(msg): return self._step_begin(tid, msg) def _step_end(sid, code, msg=None): self._step_end(tid, sid, code, msg) if get_db().upgrade_database(_step_begin, _step_end): cfg.app_mode = APP_MODE_NORMAL # self._step_begin(tid, '操作已完成') self._thread_end(tid)
def sys_user_update(_id, kv): if len(kv) == 0: return False _val = '' for k in kv: if len(_val) > 0: _val += ',' _val += '`{}`="{}"'.format(k, kv[k]) db = get_db() sql = 'UPDATE `{}auth_info` SET {} WHERE `id`={};'.format(db.table_prefix, _val, int(_id)) return db.exec(sql)
def get(self): if get_db().need_create: cfg.reload() _db = get_db() _db.init() db = {'type': _db.db_type} if _db.db_type == _db.DB_TYPE_SQLITE: db['sqlite_file'] = _db.sqlite_file elif _db.db_type == _db.DB_TYPE_MYSQL: db['mysql_host'] = _db.mysql_host db['mysql_port'] = _db.mysql_port db['mysql_user'] = _db.mysql_user db['mysql_db'] = _db.mysql_db param = {'db': db} self.render('maintenance/install.mako', page_param=json.dumps(param)) elif get_db().need_upgrade: return self.redirect('/maintenance/upgrade') else: self.redirect('/')
def add_user(user_name, user_pwd, user_desc): db = get_db() sql = 'SELECT `account_id` FROM `{}account` WHERE `account_name`="{}";'.format(db.table_prefix, user_name) db_ret = db.query(sql) if db_ret is None or len(db_ret) != 0: return -100 sec_password = sec_generate_password(user_pwd) sql = 'INSERT INTO `{}account` (`account_type`, `account_name`, `account_pwd`, `account_status`,' \ '`account_lock`,`account_desc`) VALUES (1,"{}","{}",0,0,"{}")'.format(db.table_prefix, user_name, sec_password, user_desc) ret = db.exec(sql) if ret: return 0 return -101
def delete_host(host_list): # TODO: 使用事务的方式防止删除操作中途失败 db = get_db() for item in host_list: host_id = int(item) sql = 'DELETE FROM `{}host_info` WHERE `host_id`={};'.format(db.table_prefix, host_id) ret = db.exec(sql) sql = 'DELETE FROM `{}auth_info` WHERE `host_id`={};'.format(db.table_prefix, host_id) ret = db.exec(sql) sql = 'DELETE FROM `{}auth` WHERE `host_id`={};'.format(db.table_prefix, host_id) ret = db.exec(sql) return True
def verify_oath(user_id, oath_code): db = get_db() sql = 'SELECT `oath_secret` FROM `{}account` WHERE `account_id`={};'.format( db.table_prefix, user_id) db_ret = db.query(sql) if db_ret is None: return False if len(db_ret) != 1: return False oath_secret = db_ret[0][0] return verify_oath_code(oath_secret, oath_code)
def add_host(args, must_not_exists=True): db = get_db() protocol = args['protocol'] host_port = args['host_port'] host_ip = args['host_ip'] sql = 'SELECT `host_id` FROM `{}host_info` WHERE (`host_ip`="{}" AND `protocol`={} AND `host_port`={});'.format(db.table_prefix, host_ip, protocol, host_port) db_ret = db.query(sql) if db_ret is not None and len(db_ret) > 0: if not must_not_exists: return db_ret[0][0] else: return -100 group_id = args['group_id'] host_sys_type = args['host_sys_type'] # pro_port = args['pro_port'] # pro_port = json.dumps(pro_port) # host_user_name = args['user_name'] # host_user_pwd = args['user_pwd'] # host_pro_type = args['pro_type'] # cert_id = args['cert_id'] # host_encrypt = 1 # host_auth_mode = args['host_auth_mode'] host_desc = args['host_desc'] if len(host_desc) == 0: host_desc = '描述未填写' host_lock = 0 # sql = 'INSERT INTO `{}host_info` (group_id, host_sys_type, host_ip, ' \ 'host_port, protocol, host_lock, host_desc) ' \ 'VALUES ({},{},"{}",{},{},{},"{}")' \ ''.format(db.table_prefix, group_id, host_sys_type, host_ip, host_port, protocol, host_lock, host_desc) ret = db.exec(sql) if not ret: return -101 sql = 'SELECT last_insert_rowid()' db_ret = db.query(sql) if db_ret is None: return -102 host_id = db_ret[0][0] return host_id
def sys_user_add(args): host_id = int(args['host_id']) auth_mode = int(args['auth_mode']) user_name = args['user_name'] user_pswd = args['user_pswd'] cert_id = int(args['cert_id']) if 'user_param' in args: user_param = args['user_param'] else: user_param = 'ogin:\nassword:' encrypt = 1 db = get_db() # 判断此登录账号是否已经存在,如果存在则报错 sql = 'SELECT `id` FROM `{}auth_info` WHERE (`host_id`={} AND `auth_mode`={} AND `user_name`="{}");'.format(db.table_prefix, host_id, auth_mode, user_name) db_ret = db.query(sql) if db_ret is not None and len(db_ret) > 0: return -100 log_time = GetNowTime() if auth_mode == 1: sql = 'INSERT INTO `{}auth_info` (`host_id`,`auth_mode`,`user_name`,`user_pswd`,`user_param`,`encrypt`,`cert_id`,`log_time`) ' \ 'VALUES ({},{},"{}","{}","{}",{}, {},"{}")' \ ''.format(db.table_prefix, host_id, auth_mode, user_name, user_pswd, user_param, encrypt, 0, log_time) elif auth_mode == 2: sql = 'INSERT INTO `{}auth_info` (`host_id`,`auth_mode`,`user_name`,`user_pswd`,`user_param`,`encrypt`,`cert_id`,`log_time`) ' \ 'VALUES ({},{},"{}","{}","{}",{},{},"{}")' \ ''.format(db.table_prefix, host_id, auth_mode, user_name, '', user_param, encrypt, cert_id, log_time) elif auth_mode == 0: sql = 'INSERT INTO `{}auth_info` (`host_id`,`auth_mode`,`user_name`,`user_pswd`,`user_param`,`encrypt`,`cert_id`,`log_time`) ' \ 'VALUES ({},{},"{}","{}","{}",{},{},"{}")' \ ''.format(db.table_prefix, host_id, auth_mode, user_name, '', user_param, encrypt, 0, log_time) ret = db.exec(sql) if not ret: return -101 sql = 'SELECT last_insert_rowid()' db_ret = db.query(sql) if db_ret is None: return -102 user_id = db_ret[0][0] return user_id
def sys_user_list(host_id, with_pwd=True, host_auth_id=0): db = get_db() field_a = ['id', 'host_id', 'auth_mode', 'user_name', 'user_pswd', 'user_param', 'cert_id', 'log_time'] if host_auth_id == 0: sql = 'SELECT {} ' \ 'FROM `{}auth_info` AS a ' \ 'WHERE `a`.`host_id`={};'.format(','.join(['`a`.`{}`'.format(i) for i in field_a]), db.table_prefix, int(host_id)) else: sql = 'SELECT {} ' \ 'FROM `{}auth_info` AS a ' \ 'WHERE `a`.`id`={} and `a`.`host_id`={};'.format(','.join(['`a`.`{}`'.format(i) for i in field_a]), db.table_prefix, int(host_auth_id), int(host_id)) db_ret = db.query(sql) if db_ret is None: return None ret = list() for item in db_ret: x = DbItem() x.load(item, ['a_{}'.format(i) for i in field_a]) h = dict() # h['id'] = x.a_id h['host_auth_id'] = x.a_id h['host_id'] = x.a_host_id # h['pro_type'] = x.a_pro_type h['auth_mode'] = x.a_auth_mode h['user_name'] = x.a_user_name if with_pwd: h['user_pswd'] = x.a_user_pswd if x.a_user_param is None: h['user_param'] = '' else: h['user_param'] = x.a_user_param h['cert_id'] = x.a_cert_id h['log_time'] = x.a_log_time # if x.a_auth_mode == 2: # h['user_auth'] = x.a_user_auth # else: # h['user_auth'] = "******" ret.append(h) return ret
def alloc_host_user(user_name, host_auth_dict): db = get_db() field_a = ['host_id', 'host_auth_id'] sql = 'SELECT {} FROM `{}auth` AS a WHERE `account_name`="{}";'.format( ','.join(['`a`.`{}`'.format(i) for i in field_a]), db.table_prefix, user_name) db_ret = db.query(sql) ret = dict() for item in db_ret: x = DbItem() x.load(item, ['a_{}'.format(i) for i in field_a]) host_id = int(x.a_host_id) host_auth_id = int(x.a_host_auth_id) if host_id not in ret: ret[host_id] = dict() temp = ret[host_id] temp[host_auth_id] = host_id ret[host_id] = temp add_dict = dict() for k, v in host_auth_dict.items(): host_id = int(k) auth_id_list = v for item in auth_id_list: host_auth_id = int(item) if host_id not in ret: add_dict[host_auth_id] = host_id continue temp = ret[host_id] if host_auth_id not in temp: add_dict[host_auth_id] = host_id continue try: for k, v in add_dict.items(): host_auth_id = int(k) host_id = int(v) sql = 'INSERT INTO `{}auth` (`account_name`, `host_id`, `host_auth_id`) VALUES ("{}", {}, {});'.format( db.table_prefix, user_name, host_id, host_auth_id) ret = db.exec(sql) if not ret: return False return True except: return False