def license_info(): """ 返回机器码 """ msg = {} userip = get_oper_ip_info(request) loginuser = request.args.get('loginuser') msg['UserName'] = loginuser msg['UserIP'] = userip msg['ManageStyle'] = 'WEB' msg['Operate'] = u'license授权,获取机器码' msg['Result'] = '1' # 从底层获取机器码 try: license_key = os.popen('mc_gen').read() update_str = "update license_info set license_key = '%s'" % str( license_key) db_proxy = DbProxy(CONFIG_DB_NAME) res = db_proxy.write_db(update_str) msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 1, "license_key": license_key}) except: send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 0, "msg": "获取机器码出错! "})
def record_log_to_db(request, status, info): post_data = request.get_json() loginuser = post_data['loginuser'] msg = {} userip = get_oper_ip_info(request) msg['UserName'] = loginuser msg['UserIP'] = userip msg['Operate'] = info msg['ManageStyle'] = 'WEB' msg['Result'] = status send_log_db(MODULE_OPERATION, msg)
def mw_export_switch_info(): db_proxy = DbProxy(CONFIG_DB_NAME) loginuser = request.args.get('loginuser') msg = {} userip = get_oper_ip_info(request) msg['UserIP'] = userip msg['UserName'] = loginuser msg['ManageStyle'] = 'WEB' try: # 防止初次导出时无文件报错 if not os.path.exists(SWITCH_UPLOAD_FOLDER): os.makedirs(SWITCH_UPLOAD_FOLDER) os.system('rm /data/switchinfo/switch_list.csv') csvfile = open('/data/switchinfo/switch_list.csv', 'wb') csvfile.write(codecs.BOM_UTF8) writer = csv.writer(csvfile, dialect='excel') writer.writerow([ '交换机名称', 'IP', '类型', '位置', 'SNMP版本', '团体名', '安全等级', '安全用户名', '认证方式', '认证密码', '加密方式', '加密密码', 'ssh用户名', 'ssh密码' ]) sql_str = "select name,ip, type, locate,snmp_version,group_name,security_level,security_name,auth_mode,auth_pwd,priv_mode,priv_pwd,ssh_name,ssh_pwd from switch_info order by id desc" result, rows = db_proxy.read_db(sql_str) for row in rows: row = list(row) row[6] = SECURITY_LEVEL_DICT[str(row[6])] row[4] = SNMP_VERSION_DICT[str(row[4])] # 导出时去掉v3版本字段默认信息 if not row[7]: row[4] = "" row[6] = "" row[8] = "" row[10] = "" writer.writerow(row) csvfile.close() msg['Operate'] = u"导出switch_list" msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) return send_from_directory(SWITCH_UPLOAD_FOLDER, "switch_list.csv", as_attachment=True) except: current_app.logger.error(traceback.format_exc()) msg['Operate'] = u"导出switch_list" msg['Result'] = '1' send_log_db(MODULE_OPERATION, msg) status = 0 return jsonify({'status': status})
def start_pcap(): if request.method == 'POST': result = request.get_json() pcap_name = result['pcap_name'] pcap_orig_size = result['pcap_orig_size'] pcap_orig_time = result['pcap_orig_time'] # 记录日志 msg = {} userip = get_oper_ip_info(request) data = request.get_json() loginuser = data.get('loginuser', '') msg['UserName'] = loginuser msg['UserIP'] = userip msg['ManageStyle'] = 'WEB' msg['Operate'] = u'开始在线抓包' # 判断文件名是否重复 db_proxy = DbProxy(CONFIG_DB_NAME) sql_str = "select pcap_name from pcap_down_data" sql_count = "select count(*) from pcap_down_data " res, name_result = db_proxy.read_db(sql_str) pcap_name = pcap_name + '.pcap' for name in name_result: if pcap_name == name[0]: return jsonify({'status': 0, 'msg': '文件名重复'}) else: continue # 判断数据库数据是否超过10条 res, count_rows = db_proxy.read_db(sql_count) total = count_rows[0][0] if int(total) >= 10: return jsonify({'status': 0, 'msg': '文件总数超过10条'}) else: pcap_start_time = int(time.time()) sql_str = "update pcap_down_status set flag=1,pcap_name='%s',pcap_orig_size='%s',pcap_orig_time='%s',pcap_start_time='%s';" % ( pcap_name, pcap_orig_size, pcap_orig_time, pcap_start_time) res = db_proxy.write_db(sql_str) if res == 0: msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 1, 'msg': '开始抓包成功'}) else: msg['Result'] = '1' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 0, 'msg': '开始抓包失败'})
def down_user_manaual(): directory='/app/local/share/new_self_manage' filename='天地和兴工控安全审计平台使用手册.pdf' ret=0 # 成功 try: response = send_from_directory(directory, filename, as_attachment=True) except: ret=1 response =make_response('') current_app.logger.error(traceback.format_exc()) msg = {} userip = get_oper_ip_info(request) loginuser = request.args.get('loginuser', '') msg['UserName'] = loginuser msg['UserIP'] = userip msg['Operate'] = u'下载用户使用手册' msg['ManageStyle'] = 'WEB' msg['Result'] = ret send_log_db(MODULE_OPERATION, msg) return response
def license_file_info(): """ 验证上传的license是否合法并返回结果 """ loginuser = request.form.get('loginuser') msg = {} userip = get_oper_ip_info(request) msg['UserName'] = loginuser msg['UserIP'] = userip msg['ManageStyle'] = 'WEB' msg['Operate'] = u'上传license授权文件' msg['Result'] = '1' if not os.path.exists(LICENSE_UPLOAD_FOLDER): os.makedirs(LICENSE_UPLOAD_FOLDER) f = request.files['license_filename'] if f: # 如果路径下有文件则先删除所有文件 delList = os.listdir(LICENSE_UPLOAD_FOLDER) for i in delList: filePath = os.path.join(LICENSE_UPLOAD_FOLDER, i) if os.path.isfile(filePath): os.remove(filePath) # 将新文件保存到路径下(所有上传文件重新命名为licensefile.lic) new_fname = 'licensefile.lic' f.save(os.path.join(LICENSE_UPLOAD_FOLDER, new_fname)) license_legal, license_time, license_func = license_status_verify() if license_legal == 1: msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) return jsonify({ 'status': 1, "license_time": license_time, "license_func": license_func }) else: send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 0, "msg": "无效的license文件,请确认!"}) else: send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 0, "msg": "license上传错误!"})
def stop_pcap(): # 记录日志 msg = {} userip = get_oper_ip_info(request) loginuser = request.args.get('loginuser') msg['UserName'] = loginuser msg['UserIP'] = userip msg['ManageStyle'] = 'WEB' msg['Operate'] = u'停止在线抓包' status = 0 db_proxy = DbProxy(CONFIG_DB_NAME) sql_str = "select * from pcap_down_status" _, result = db_proxy.read_db(sql_str) pcap_name = result[0][2] start_pcap_time = int(result[0][7]) pcap_cur_size = pcap_cur_status(pcap_name) pcap_path = '/data/tcpdumpdata/' + pcap_name os.system('kill -9 $(pidof tcpdump)') finish_time = int(time.time()) # 抓包运行时间 pcap_cur_time = finish_time - start_pcap_time sql_str = "insert into pcap_down_data(finish_time,pcap_cur_size,pcap_cur_time,pcap_name,pcap_path) values ('%s','%s','%s', '%s','%s')" % ( finish_time, pcap_cur_size, pcap_cur_time, pcap_name, pcap_path) db_proxy.write_db(sql_str) sql_update = "update pcap_down_status set flag=0,pcap_name='',pcap_cur_time=0,pcap_cur_size=0,pcap_orig_size=0,pcap_orig_time=0,pcap_start_time=0" res = db_proxy.write_db(sql_update) if res == 0: status = 1 msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': status, 'msg': '停止抓包成功'}) else: msg['Result'] = '1' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': status, 'msg': '停止抓包失败'})
def delete_pcap(): # 记录日志 msg = {} userip = get_oper_ip_info(request) data = request.get_json() loginuser = data.get('loginuser', '') msg['UserName'] = loginuser msg['UserIP'] = userip msg['ManageStyle'] = 'WEB' msg['Operate'] = u'删除数据包' db_proxy = DbProxy(CONFIG_DB_NAME) if request.method == 'DELETE': result = request.get_json() ids = result.get('id', '') id_list = ids.split(",") for i in id_list: sql_name_str = "select pcap_name from pcap_down_data where id ='%s'" % i name_res, name_rows = db_proxy.read_db(sql_name_str) if name_res == 0: for name in name_rows: addr = '/data/tcpdumpdata/' + name[0] if os.path.exists(addr): os.remove(addr) else: logger.error("%s file not exist" % addr) sql_str = "delete from pcap_down_data where id='%s'" % i res = db_proxy.write_db(sql_str) if res != 0: msg['Result'] = '1' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 0, 'msg': '删除失败'}) msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) return jsonify({'status': 1, 'msg': '删除成功'})
def mw_import_switch_info(): if request.method == 'POST': db_proxy = DbProxy(CONFIG_DB_NAME) loginuser = request.form.get('loginuser') msg = {} userip = get_oper_ip_info(request) msg['UserIP'] = userip msg['UserName'] = loginuser msg['ManageStyle'] = 'WEB' try: if not os.path.exists(SWITCH_UPLOAD_FOLDER): os.makedirs(SWITCH_UPLOAD_FOLDER) file = request.files['file'] if not file or not switch_allowed_file(file.filename): return jsonify({'status': 0, 'msg': '导入文件格式错误'}) filename = secure_filename(file.filename) file.save(os.path.join(SWITCH_UPLOAD_FOLDER, filename)) FileName = '%s%s' % (SWITCH_UPLOAD_FOLDER, filename) csvfile = open(FileName, 'rb') reader = csv.reader(csvfile, dialect='excel') rows = [row for row in reader] if rows[0] != [ '\xef\xbb\xbf交换机名称', 'IP', '类型', '位置', 'SNMP版本', '团体名', '安全等级', '安全用户名', '认证方式', '认证密码', '加密方式', '加密密码', 'ssh用户名', 'ssh密码' ]: msg['Operate'] = u"导入switch_list" msg['Result'] = '1' send_log_db(MODULE_OPERATION, msg) os.system("rm '%s'" % (FileName)) return jsonify({'status': 0, 'msg': u"导入文件内容错误"}) # 验证导入的信息是否合法,任意一条数据不合法就return for data in rows[1:]: name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd = data id = 0 flag = 1 try: # 安全等级,SNMP版本信息转换 snmp_version = SNMP_VERSION_MAP[snmp_version] security_level = SECURITY_LEVEL_MAP[security_level] error_msg = verify_params(id, name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd, flag) if len(error_msg) != 0: return jsonify({'status': 0, 'msg': error_msg}) except: current_app.logger.error(traceback.format_exc()) continue # 验证完成,导入信息 csvfile = open(FileName, 'rb') reader = csv.reader(csvfile, dialect='excel') rows = [row for row in reader] for data in rows[1:]: name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd = data # 安全等级,SNMP版本信息转换 security_level = SECURITY_LEVEL_MAP[security_level] snmp_version = SNMP_VERSION_MAP[snmp_version] # 删除原有信息,导入新信息 del_str = "delete from switch_info where ip = '{}'".format(ip) db_proxy.write_db(del_str) sql_str = '''insert into switch_info (name,ip,type,locate,snmp_version,group_name,security_level,security_name,auth_mode,auth_pwd,priv_mode,priv_pwd,ssh_name,ssh_pwd) values('{}','{}','{}','{}',{},'{}','{}','{}','{}','{}','{}','{}','{}','{}')'''.format( name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd) db_proxy.write_db(sql_str) # 导入完成后重新计算所有的mac_port信息 导入速度太慢,导入时先导入列表,不计算 # autoGetSwitchInfo.get_all_switch_mac_port() os.system("rm '%s'" % (FileName)) msg['Operate'] = u"导入switch_list" msg['Result'] = '0' send_log_db(MODULE_OPERATION, msg) status = 1 return jsonify({'status': status, "msg": "导入成功"}) except: current_app.logger.error(traceback.format_exc()) msg['Operate'] = u"导入switch_list" msg['Result'] = '1' send_log_db(MODULE_OPERATION, msg) status = 0 return jsonify({'status': status})
def mw_switch_info(): db_proxy = DbProxy(CONFIG_DB_NAME) # 主页面及详情页面获取全部 if request.method == 'GET': ip = request.args.get('ip', '').encode('utf-8') locate = request.args.get('locate', '').encode('utf-8') name = request.args.get('name', '').encode('utf-8') type = request.args.get('type', '').encode('utf-8') page = request.args.get('page', 0, type=int) sql_str = 'select * from switch_info where 1=1 ' num_str = 'select count(*) from switch_info where 1=1 ' if name: sql_str += " and name like '%%%s%%'" % name num_str += " and name like '%%%s%%'" % name if ip: sql_str += " and ip like '%%%s%%'" % ip num_str += " and ip like '%%%s%%'" % ip if type: sql_str += " and type like '%%%s%%'" % type num_str += " and type like '%%%s%%'" % type if locate: sql_str += " and locate like '%%%s%%'" % locate num_str += " and locate like '%%%s%%'" % locate if page: limit_str = ' order by id desc limit ' + str( (page - 1) * 10) + ',10;' sql_str += limit_str info = [] try: res, rows = db_proxy.read_db(sql_str) for row in rows: item = {} item["id"] = row[0] item["switch_name"] = row[1] item["ip"] = row[2] item["type"] = row[3] item["locate"] = row[4] item["snmp_version"] = row[5] item["group_name"] = row[6] item["security_level"] = row[7] item["security_name"] = row[8] item["auth_mode"] = row[9] item["auth_pwd"] = row[10] item["priv_mode"] = row[11] item["priv_pwd"] = row[12] item["ssh_name"] = row[13] item["ssh_pwd"] = row[14] info.append(item) res, rows = db_proxy.read_db(num_str) if res == 0: total_num = rows[0][0] else: total_num = 0 return jsonify({'data': info, 'num': total_num, 'page': page}) except: current_app.logger.error(traceback.format_exc()) return jsonify({'data': [], 'num': 0, page: 1}) # 详情页面新增 elif request.method == 'POST': data = request.get_json() oper_msg = {} userip = get_oper_ip_info(request) loginuser = data.get('loginuser') oper_msg['UserName'] = loginuser oper_msg['UserIP'] = userip oper_msg['ManageStyle'] = 'WEB' oper_msg['Result'] = '1' try: switch_name = data.get("switch_name") ip = data.get("ip") type = data.get("type").decode("utf-8") locate = data.get("locate") snmp_version = data.get("snmp_version") group_name = data.get("group_name") security_level = data.get("security_level") security_name = data.get("security_name") auth_mode = data.get("auth_mode") auth_pwd = data.get("auth_pwd") priv_mode = data.get("priv_mode") priv_pwd = data.get("priv_pwd") ssh_name = data.get("ssh_name") ssh_pwd = data.get("ssh_pwd") id = 0 flag = 0 # 字段验证使用 error_msg = verify_params(id, switch_name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd, flag) if len(error_msg) != 0: oper_msg['Result'] = '0' send_log_db(MODULE_OPERATION, oper_msg) return jsonify({'status': 0, 'msg': error_msg}) except: current_app.logger.error(traceback.format_exc()) return jsonify({"status": 0, "msg": u"参数错误"}) try: cmd_str = '''insert into switch_info (name,ip,type,locate,snmp_version,group_name,security_level,security_name,auth_mode,auth_pwd,priv_mode,priv_pwd,ssh_name,ssh_pwd) values('{}','{}','{}','{}',{},'{}','{}','{}','{}','{}','{}','{}','{}','{}')'''.format( switch_name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd) res = db_proxy.write_db(cmd_str) if res != 0: send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 0, "msg": u"添加失败"}) # 调用计算函数重新计算mac_port表信息,并更新switch_mac_port表交换机名称信息 sql_str = "select snmp_version,group_name,security_level,security_name,auth_mode,auth_pwd,priv_mode,priv_pwd,ssh_name,ssh_pwd, ip,name from switch_info where name = '{}'".format( switch_name) res, rows = db_proxy.read_db(sql_str) if len(rows) > 0: for row in rows: autoGetSwitchInfo.get_one_switch_mac_port(row) oper_msg['Result'] = '0' oper_msg['Operate'] = "添加交换机:" + switch_name send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 1, "msg": u"添加成功"}) except: current_app.logger.error(traceback.format_exc()) send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 0, "msg": u"添加失败"}) # 详情页面的编辑修改 elif request.method == 'PUT': data = request.get_json() try: id = data.get("id") switch_name = data.get("switch_name") ip = data.get("ip") type = data.get("type").decode("utf-8") locate = data.get("locate") snmp_version = data.get("snmp_version") group_name = data.get("group_name") security_level = data.get("security_level") security_name = data.get("security_name") auth_mode = data.get("auth_mode") auth_pwd = data.get("auth_pwd") priv_mode = data.get("priv_mode") priv_pwd = data.get("priv_pwd") ssh_name = data.get("ssh_name") ssh_pwd = data.get("ssh_pwd") oper_msg = {} userip = get_oper_ip_info(request) loginuser = data.get('loginuser') oper_msg['UserName'] = loginuser oper_msg['UserIP'] = userip oper_msg['ManageStyle'] = 'WEB' oper_msg['Result'] = '1' flag = 0 error_msg = verify_params(id, switch_name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd, flag) if len(error_msg) != 0: oper_msg['Result'] = '0' send_log_db(MODULE_OPERATION, oper_msg) return jsonify({'status': 0, 'msg': error_msg}) except: current_app.logger.error(traceback.format_exc()) return jsonify({"status": 0, "msg": u"参数错误"}) try: cmd_str = "select name from switch_info where id={}".format(id) res, rows = db_proxy.read_db(cmd_str) old_name = rows[0][0] if res != 0: return jsonify({"status": 0, "msg": u"不存在的id"}) # delete and add del_str = "delete from switch_info where id={}".format(id) db_proxy.write_db(del_str) cmd_str = '''insert into switch_info (name,ip,type,locate,snmp_version,group_name,security_level,security_name,auth_mode,auth_pwd,priv_mode,priv_pwd,ssh_name,ssh_pwd) values('{}','{}','{}','{}',{},'{}','{}','{}','{}','{}','{}','{}','{}','{}')'''.format( switch_name, ip, type, locate, snmp_version, group_name, security_level, security_name, auth_mode, auth_pwd, priv_mode, priv_pwd, ssh_name, ssh_pwd) res = db_proxy.write_db(cmd_str) if res != 0: send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 0, "msg": u"编辑失败"}) # 调用计算函数重新计算mac_port表信息,并更新switch_mac_port表交换机名称信息 sql_str = "select snmp_version,group_name,security_level,security_name,auth_mode,auth_pwd,priv_mode,priv_pwd,ssh_name,ssh_pwd, ip,name from switch_info where name = '{}'".format( switch_name) res, rows = db_proxy.read_db(sql_str) if len(rows) > 0: for row in rows: autoGetSwitchInfo.get_one_switch_mac_port(row) oper_msg['Operate'] = "编辑交换机内容:" + old_name oper_msg['Result'] = '0' send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 1, "msg": u"编辑成功"}) except: current_app.logger.error(traceback.format_exc()) send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 0, "msg": u"编辑失败"}) # 主页面的删除 elif request.method == "DELETE": data = request.get_json() userip = get_oper_ip_info(request) loginuser = data.get('loginuser') oper_msg = {} oper_msg['UserName'] = loginuser oper_msg['UserIP'] = userip oper_msg['ManageStyle'] = 'WEB' oper_msg['Result'] = '1' try: id = data.get("id") cmd_str = "select name from switch_info where id in ({})".format( id) res, rows = db_proxy.read_db(cmd_str) name_list = [row[0] for row in rows] content_name_str = ",".join(name_list) oper_msg['Operate'] = "删除交换机内容:" + content_name_str oper_msg['Result'] = '1' # 删除交换机列表mac_port信息表中与之相关的mac_port信息 del_str = "delete from switch_mac_port where switch_name in (select name from switch_info where id in ({}));".format( id) res = db_proxy.write_db(del_str) # 删除交换机列表中信息 del_str = "delete from switch_info where id in ({})".format(id) res = db_proxy.write_db(del_str) if res != 0: send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 0, "msg": u"删除失败"}) oper_msg['Result'] = '0' send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 1, "msg": u"删除成功"}) except: current_app.logger.error(traceback.format_exc()) send_log_db(MODULE_OPERATION, oper_msg) return jsonify({"status": 0, "msg": u"删除失败"})