예제 #1
0
def del_white(request):
    """
    白名单删除多条记录
    :param request: ids = WL247153WL247177
    :return:
    """
    response = Response()
    try:
        # 这里split之后的list中,第一个元素会是一个空格,因此要从第二个元素开始取值
        id_list = request.POST.get("ids", "").split("WL")[1:]

        # 获取id在id_list范围里的所有白名单对象 进行删除
        targets = WhiteList.objects.filter(id__in=id_list)
        for target in targets:
            ret = {
                "filedata": target.file_data,
                "ip": target.ip,
                "filerouter": target.file_router,
                "id": target.id,
                "clientname": target.client_name
            }
            zmq_class.send_reset(ret)
        targets.delete()
    except Exception as e:
        logger.error(str(e))
        response.setcode('ERROR')
        response.adddata("message", str(e))

    return HttpResponse(json.dumps(response.__dict__))
예제 #2
0
def del_white_one(request):
    """
    白名单删除一条记录
    :param request: ids
    :return:
    """
    response = Response()
    try:
        # 接收参数
        _id = request.POST['ids']

        # 根据id获取白名单对象 进行删除
        target = WhiteList.objects.get(id=_id)
        ret = {
            "filedata": target.file_data,
            "ip": target.ip,
            "filerouter": target.file_router,
            "id": target.id,
            "clientname": target.client_name
        }
        zmq_class.send_reset(ret)
        target.delete()
    except Exception as e:
        logger.error(str(e))
        response.setcode('ERROR')
        response.adddata("message", str(e))

    return HttpResponse(json.dumps(response.__dict__))
def user_status(request):
    """
    请求用户登录数据
    :param request:
    :return:
    """
    response = Response()
    response.setcode('SUCCESS')
    response.adddata("username", request.user.username)
    return HttpResponse(json.dumps(response.__dict__))
def register(request):
    response = Response()
    if local_config.enable_register == 'off':
        response.setcode('LOGIN_CLOSED')
        return HttpResponse(json.dumps(response.__dict__))
    # 注册提交
    if request.method == 'POST':
        form = UserForm(data=request.POST)  # 将数据存储在form类对象中
        if form.is_valid():  # 检验数据是否为空
            username = request.POST.get('username')  # 取出用户名数据
            password = request.POST.get('password')  # 取出密码数据
            # 首先判断用户是否已存在
            filter_result = User.objects.filter(username=username)
            if filter_result.first() == ("" or None):  # 若不存在该用户,则添加用户名密码到数据库的auth_user表中
                # 这里三个参数是固定的,必须是用户名、邮箱、密码,且顺序不能改变
                new_user = User.objects.create_user(username, "", password)
                new_user.save()
                # request.session['username'] = username  # 把用户存储在session中
            else:
                response.setcode('USER_REMAIN')
            return HttpResponse(json.dumps(response.__dict__))
        else:
            response.setcode('PARAM_INVALID')
            return HttpResponse(json.dumps(response.__dict__))
    # 其他非post请求,则访问失败
    else:
        response.setcode('WRONG_CONNECT')
        return HttpResponse(json.dumps(response.__dict__))
예제 #5
0
def add_white(request):
    """
    添加白名单,发送
    :param request:
        参数1: wlName 主机名
        参数2: wlIP IP
        参数3: wlText 文件哈希
        参数4: wlUrl 文件路径
    :return: 成功或失败
    """
    response = Response()
    try:
        # 接收参数
        wl_name = request.POST['wlName']
        wl_ip = request.POST['wlIP']
        wl_text = request.POST['wlText']
        wl_url = request.POST['wlUrl']

        white_dict = {
            'clientname': wl_name,
            'ip': wl_ip,
            'filerouter': wl_url,
            'filedata': wl_text
        }
        zmq_class.send_repair(white_dict)
        white_lists = WhiteList.objects.filter(client_name=wl_name,
                                               ip=wl_ip,
                                               file_data=wl_text,
                                               file_router=wl_url)
        if white_lists.count == 0:
            WhiteList.objects.create(client_name=wl_name,
                                     ip=wl_ip,
                                     file_data=wl_text,
                                     file_router=wl_url)
        else:
            response.setcode('ERROR')
            response.adddata("message", "添加失败: 信息重复添加")
    except Exception as e:
        logger.error(e)
        response.setcode('ERROR')
        response.adddata("message", str(e))

    return HttpResponse(json.dumps(response.__dict__))
def modify_password(request):
    response = Response()
    if request.method == 'POST':
        # username = request.session.get('username')
        username = request.user.username
        oldpassword = request.POST.get('password')
        newpassword = request.POST.get('newpassword')
        try:  # 首先要校验用户名是否存在
            u = User.objects.get(username__exact=username)
            res = u.check_password(oldpassword)  # 校验密码是否正确
            if res:
                u.set_password(newpassword)  # 设置新密码
                u.save()  # 保存新密码
            else:
                response.setcode('密码错误')
        except Exception as e:
            logger.error(e)
            # 返回密码错误状态
            response.setcode('密码错误')
        return HttpResponse(json.dumps(response.__dict__))
예제 #7
0
def edit_white(request):
    """
    编辑白名单
    :param request:
        参数1: id 主机id
        参数2: wlName 主机名
        参数3: wlIP IP
        参数4: wlText 文件哈希
        参数5: wlUrl 文件路径
    :return:
    """
    response = Response()
    try:
        # 接收参数
        _id = request.POST['id']
        wl_name = request.POST['wlName']
        wl_ip = request.POST['wlIP']
        wl_text = request.POST['wlText']
        wl_url = request.POST['wlUrl']

        white_dict = {
            'clientname': wl_name,
            'ip': wl_ip,
            'filerouter': wl_url,
            'filedata': wl_text
        }
        zmq_class.send_repair(white_dict)

        # 根据id获取白名单对象 进行更新
        target = WhiteList.objects.get(id=_id)
        target.client_name = wl_name
        target.ip = wl_ip
        target.file_router = wl_url
        target.file_data = wl_text
        target.save()
    except Exception as e:
        logger.error(str(e))
        response.setcode('ERROR')
        response.adddata("message", str(e))

    return HttpResponse(json.dumps(response.__dict__))
def login(request):
    response = Response()
    if request.user.is_authenticated():
        # 用户已经登录
        response.setcode('USER_LOGON')
        return HttpResponse(json.dumps(response.__dict__))
    if request.method == 'POST':
        username = ""
        password = ""
        if request.POST.get('source', '') and request.POST.get('source') == "qingyun":
            username = jc.qingyun_user
            password = jc.qingyun_pwd
        else:
            username = request.POST.get('username')
            password = request.POST.get('password')
        logger.debug('username:'******' password: '******'auth successfully')
        if user is not None:
            if user.is_active:
                user_login(request, user)  # 登录用户
                # request.session['username'] = username
                logger.info("username login : " + username)
                return HttpResponse(json.dumps(response.__dict__))
            else:
                # 用户已被本系统禁用
                response.setcode('USER_INACTIVE')
                return HttpResponse(json.dumps(response.__dict__))
        else:
            # 用户名或者密码错误
            response.setcode('USER_LOGIN_FAIL')
            return HttpResponse(json.dumps(response.__dict__))
    else:
        # 非post访问
        response.setcode('WRONG_CONNECT')
        return HttpResponse(json.dumps(response.__dict__))
def transfer_db(request):
    if request.method != 'POST':
        response = Response()
        # 非post访问
        response.setcode('WRONG_CONNECTION')
        ret = [BIZ_CODE['WRONG_CONNECTION']]
        return HttpResponse(json.dumps(ret))

    username1 = request.POST['username1']
    dbname = request.POST['dbname']
    password1 = request.POST['password1']
    ip1 = request.POST['ip1']
    ip2 = request.POST['ip2']
    type2 = request.POST['type2']
    port1 = request.POST['port1']
    port2 = request.POST['port2']

    ip1 = 'localhost' if ip1 == gc.LOCALHOST else ip1
    ip2 = 'localhost' if ip2 == gc.LOCALHOST else ip2
    # 首先判断数据库类型在客户机上是否存在
    if type2 != 'MySQL':
        ret = [BIZ_CODE['NOT_SUPPORT_DABABASE_TYPE']]
        return HttpResponse(json.dumps(ret))
    if type2 == 'MySQL':
        conn, cursor = mysql_base_api.sql_init(ip1, username1, password1,
                                               dbname, int(port1))
        if str(type(conn)).find('int') != -1:
            if conn == 2003 and str(cursor).find(
                    '113'):  # 1. 网络不通 conn为整数2003, cursor 中包含错误(113)
                ret = [BIZ_CODE['NET_UNREACHABLE']]
                return HttpResponse(json.dumps(ret))
            if conn == 2003 and str(cursor).find(
                    '111'):  # 2. 没有数据库或无法连接到数据库,conn为2003,cursor中包含错误(111)
                ret = [BIZ_CODE['NOT_SUPPORT_DABABASE_TYPE']]
                return HttpResponse(json.dumps(ret))
            if conn == 1045:  # 3. 用户名密码错误,conn为1045
                ret = [BIZ_CODE['WRONG_CONNECTION']]
                return HttpResponse(json.dumps(ret))
            if conn == 1130:  # 4. 主机被限制连接,conn为1130
                ret = [BIZ_CODE['HOST_BINDED']]
                return HttpResponse(json.dumps(ret))
            if conn == 1049:
                ret = [BIZ_CODE['NOT_SUPPORT_DABABASE_TYPE']]
                return HttpResponse(json.dumps(ret))
        else:
            command1 = "sudo sed -i 's/^port/port            = " + port2 + \
                       "#/' /etc/mysql/my.cnf"
            res = ssh_cmd(request.POST, command1)
            if res['result']:
                ret = []
                temp = {
                    'name': dbname,
                    'type': type2,
                    'ip': ip2,
                    'size': float(res['size']),
                    'volume': float(res['volume']),
                    'port': port2
                }
                ret.append(temp)
                ret.append(BIZ_CODE['SUCCESS'])
                return HttpResponse(json.dumps(ret))
            else:
                ret = [BIZ_CODE['TRANSFER_DB_FAILED']]
                return HttpResponse(json.dumps(ret))
def deletedb(request):
    response = Response()
    if request.method != 'POST':
        # 非post访问
        response.setcode('WRONG_CONNECTION')
        ret = [BIZ_CODE['WRONG_CONNECTION']]
        return HttpResponse(json.dumps(ret))

    dbname = request.POST['dbname']
    ip = request.POST['ip']
    port = request.POST['port']
    user = request.POST['username']
    password = request.POST['password']
    sql_type = request.POST['type']
    if sql_type == 'MySQL':
        try:
            if port == '':
                conn, cursor = mysql_base_api.sql_init(ip, user, password,
                                                       dbname)
            else:
                conn, cursor = mysql_base_api.sql_init(ip, user, password,
                                                       dbname, int(port))
            if str(type(conn)).find('int') != -1:
                response.setcode('WRONG_CONNECTION')
                ret = [BIZ_CODE['WRONG_CONNECTION']]
                return HttpResponse(json.dumps(ret))
            # 删除数据库
            mysql_base_api.drop_database(cursor, dbname)
            # 删除client_info表中对应数据
            conn, cursor = mysql_base_api.sql_init(jc.mysql_host,
                                                   jc.mysql_user,
                                                   jc.mysql_pass, None,
                                                   jc.mysql_port)
            mysql_base_api.sql_execute(conn, cursor, "use `octastack_fuzhou`",
                                       "")
            del_list = [
                "DELETE FROM `client_info` where db_name = '" + dbname + "'" +
                " and db_ip='" + ip + "'"
            ]
            mysql_base_api.update_row(conn, cursor, del_list)
            mysql_base_api.sql_close(conn, cursor)
            response.setcode('SUCCESS')
            ret = [BIZ_CODE['SUCCESS']]
            return HttpResponse(json.dumps(ret))
        except:
            response.setcode('WRONG_CONNECTION')
            ret = [BIZ_CODE['WRONG_CONNECTION']]
            return HttpResponse(json.dumps(ret))
    elif sql_type == 'PostgreSQL':
        try:
            # 数据库连接参数
            conn = psycopg2.connect(user=user,
                                    password=password,
                                    host=ip,
                                    port=port)
            conn.set_isolation_level(0)
            cur = conn.cursor()
            cur.execute("DROP DATABASE IF EXISTS " + dbname + " ;")
            if conn is not None:
                conn.commit(
                )  # DELETE, INSERT, UPDATE operations should commit.
            conn.set_isolation_level(1)

            # 删除client_info表中对应数据
            mysql_conn, mysql_cursor = mysql_base_api.sql_init(
                jc.mysql_host, jc.mysql_user, jc.mysql_pass, None,
                jc.mysql_port)
            mysql_base_api.sql_execute(mysql_conn, mysql_cursor,
                                       "use `octastack_fuzhou`", "")
            del_list = [
                "DELETE FROM `client_info` where db_name = '" + dbname + "'" +
                " and db_ip='" + ip + "'"
            ]
            mysql_base_api.update_row(mysql_conn, mysql_cursor, del_list)
            mysql_base_api.sql_close(mysql_conn, mysql_cursor)

            ret = [BIZ_CODE['SUCCESS']]
            return HttpResponse(json.dumps(ret))
        except:
            response.setcode('WRONG_CONNECTION')
            ret = [BIZ_CODE['WRONG_CONNECTION']]
            return HttpResponse(json.dumps(ret))
        finally:
            cur.close()
            conn.close()
def update_db(request):
    response = Response()
    if request.method != 'POST':
        # 非post访问
        response.setcode('WRONG_CONNECTION')
        ret = [BIZ_CODE['WRONG_CONNECTION']]
        return HttpResponse(json.dumps(ret))

    dbname = request.POST['dbname']
    new_dbname = request.POST['newDBname']
    sql_type = request.POST['type']
    ip = request.POST['ip']
    port = request.POST['port']
    user = request.POST['username']
    cur_password = request.POST['curPassword']
    new_password = request.POST['newPassword']
    if sql_type == 'MySQL':
        if port == "":
            port = 3306
            conn, cursor = mysql_base_api.sql_init(ip, user, cur_password,
                                                   None, port)
        else:
            conn, cursor = mysql_base_api.sql_init(ip, user, cur_password,
                                                   None, int(port))
        if str(type(conn)).find('int') != -1:
            response.setcode('WRONG_CONNECTION')
            ret = [BIZ_CODE['WRONG_CONNECTION']]
            return HttpResponse(json.dumps(ret))
        # 如果数据库名有变更,则修改数据库名
        if dbname != new_dbname:
            # 首先创建目标数据库
            r = mysql_base_api.create_database(conn, cursor,
                                               new_dbname)  # 创建新的数据库
            if len(r) > 0 and r[0] == 1007:
                ret = [BIZ_CODE['DATABASE_EXIST']]
                return HttpResponse(json.dumps(ret))
            elif str(type(r)).find('tuple'):
                # 获取所有源库的表名
                mysql_base_api.sql_execute(conn, cursor,
                                           "use information_schema;", "")
                tables = mysql_base_api.sql_execute(
                    conn, cursor, "select table_name from TABLES where "
                    "TABLE_SCHEMA='" + dbname + "';", "")
                # 按照以下命令一个个修改原数据库表名
                if len(tables) > 0:
                    for table in tables:
                        table_name = table['table_name']
                        mysql_base_api.sql_execute(
                            conn, cursor,
                            "rename table " + dbname + "." + table_name +
                            " to " + new_dbname + "." + table_name + ";", "")
                mysql_base_api.drop_database(cursor, dbname)  # 删除原来的数据库
                # 获取新数据库的size和volume
                mysql_base_api.sql_execute(conn, cursor,
                                           "use information_schema;", "")
                volume = mysql_base_api.sql_execute(
                    conn, cursor,
                    "select concat(round(sum(DATA_LENGTH/1024/1024),2)) as data from TABLES",
                    "")
                size = mysql_base_api.sql_execute(
                    conn, cursor,
                    "select concat(round(sum(DATA_LENGTH/1024/1024),2)) as "
                    "data from TABLES where table_schema='" + new_dbname +
                    "';", "")
                if size[0]['data'] is None:
                    size[0]['data'] = 0
                # 更新client_info表
                conn, cursor = mysql_base_api.sql_init(jc.mysql_host,
                                                       jc.mysql_user,
                                                       jc.mysql_pass, None,
                                                       jc.mysql_port)
                mysql_base_api.sql_execute(conn, cursor,
                                           "use octastack_fuzhou;", "")
                update_row = [
                    "UPDATE `client_info` SET db_name='" + new_dbname +
                    "', db_size = " + str(size[0]['data']) + ", db_volume = " +
                    str(volume[0]['data']) + " where db_name='" + dbname +
                    "'" + " and db_ip='" + ip + "'"
                ]
                mysql_base_api.update_row(conn, cursor, update_row)
            else:
                ret = [BIZ_CODE['WRONG_CONNECTION']]
                return HttpResponse(json.dumps(ret))
        # 如果数据库用户密码有变更,则修改密码
        if new_password != "":
            # 同时修改密码
            logger.debug(
                "---------------- test change password ---------------" +
                new_password)
            mysql_base_api.sql_execute(conn, cursor, "use mysql;", None)
            mysql_base_api.sql_execute(
                conn, cursor, "UPDATE user SET Password = "******"PASSWORD(" + new_password + ") WHERE user = '******';",
                None)
            mysql_base_api.sql_execute(conn, cursor, "FLUSH PRIVILEGES;", None)
            logger.debug(
                "-------------------- success changed password-----------------"
            )
        # 获取数据库的size和volume
        mysql_base_api.sql_execute(conn, cursor, "use information_schema;",
                                   None)
        volume = mysql_base_api.sql_execute(
            conn, cursor,
            "select concat(round(sum(DATA_LENGTH/1024/1024),2)) as data from TABLES",
            "")
        size = mysql_base_api.sql_execute(
            conn, cursor,
            "select concat(round(sum(DATA_LENGTH/1024/1024),2)) as "
            "data from TABLES where table_schema='" + dbname + "';", "")
        if size[0]['data'] is None:
            size[0]['data'] = 0
        ret = []
        mysql_base_api.sql_close(conn, cursor)
        temp = {
            'name': new_dbname,
            'type': sql_type,
            'ip': ip,
            'port': port,
            'size': float(size[0]['data']),
            'volume': float(volume[0]['data'])
        }
        ret.append(temp)
        response.setcode('SUCCESS')
        ret.append(BIZ_CODE['SUCCESS'])
        return HttpResponse(json.dumps(ret))

    elif sql_type == 'PostgreSQL':
        conn = psycopg2.connect(user=user,
                                password=cur_password,
                                host=ip,
                                port=port)
        conn.set_isolation_level(0)
        cur = conn.cursor()
        if dbname != new_dbname:
            cur.execute("ALTER DATABASE " + dbname + " RENAME TO " +
                        new_dbname + ";")
        conn.set_isolation_level(1)
        cur.close()
        conn.close()

        # 更新client_info表
        mysql_conn, mysql_cursor = mysql_base_api.sql_init(
            jc.mysql_host, jc.mysql_user, jc.mysql_pass, None, jc.mysql_port)
        mysql_base_api.sql_execute(mysql_conn, mysql_cursor,
                                   "use octastack_fuzhou;", "")
        update_row = [
            "UPDATE `client_info` SET db_name='" + new_dbname +
            "', db_size = 0" + ", db_volume = 0" + " where db_name='" +
            dbname + "'" + " and db_ip='" + ip + "'"
        ]
        mysql_base_api.update_row(mysql_conn, mysql_cursor, update_row)
        mysql_base_api.sql_close(mysql_conn, mysql_cursor)

        ret = []
        temp = {
            'name': new_dbname,
            'type': sql_type,
            'ip': ip,
            'port': port,
            'size': 0,
            'volume': 0
        }
        ret.append(temp)
        response.setcode('SUCCESS')
        ret.append(BIZ_CODE['SUCCESS'])
        return HttpResponse(json.dumps(ret))
    else:
        response.setcode('NOT_SUPPORT_DABABASE_TYPE')
        ret = [BIZ_CODE['NOT_SUPPORT_DABABASE_TYPE']]
        return HttpResponse(json.dumps(ret))
def db_info(request):
    """

    :param request:
    :return:
    """
    response = Response()
    ret = []
    data_list = []
    # 用于判断是否连接上数据库
    is_connected = False
    # 连接本地mysql数据库octastack_fuzhou
    conn, cursor = gc.connect_localhost()
    # 从数据库取出client_info数据
    data_set = mysql_base_api.sql_execute(conn, cursor,
                                          "select * from client_info;", None)
    if len(data_set) > 0:  # 若client_info有数据
        # 获取主机相关信息
        common_set, record_list = get_common_set(data_set)
        # 按照注释中的形式组织数据
        data_list = organize_db_info(common_set, record_list)
    for d_list in data_list:
        if len(d_list) > 0:
            infos = d_list['diff']  # 取出diff中的list
            conn, cursor = mysql_base_api.sql_init(d_list['db_ip'],
                                                   d_list['sql_uname'],
                                                   d_list['sql_passwd'], None,
                                                   d_list['db_port'])
            if str(type(conn)).find(
                    'int') != -1:  # 若连接时返回的是整数,说明连接失败,则继续连接其他数据库
                continue
            check_db = mysql_base_api.sql_execute(conn, cursor,
                                                  "show databases;", "")
            db_list = []
            if len(check_db) > 0:  # 首先将连接接到的远程数据库放在list中
                for db in check_db:
                    db_list.append(db['Database'])
            for info in infos:
                if info[0] != 'octastack_fuzhou':  # octastack_fuzhou这个是系统数据库,不展示
                    if info[0] in db_list:
                        temp = {
                            'name': info[0],
                            'type': 'MySQL',
                            'ip': d_list['db_ip'],
                            'port': d_list['db_port'],
                            'size': info[1],
                            'volume': info[3]
                        }
                        ret.append(temp)
                    else:
                        conn, cursor = mysql_base_api.sql_init(
                            jc.mysql_host, jc.mysql_user, jc.mysql_pass, None,
                            jc.mysql_port)
                        mysql_base_api.sql_execute(conn, cursor,
                                                   "use octastack_fuzhou;", "")
                        mysql_base_api.sql_execute(
                            conn, cursor,
                            "delete from `client_info` WHERE db_name = '" +
                            info[0] + "';", "")
                    is_connected = True
            mysql_base_api.sql_close(conn, cursor)
    if is_connected:
        response.setcode('SUCCESS')
        ret.append(BIZ_CODE['SUCCESS'])
    else:
        response.setcode('WRONG_CONNECTION')
        ret = [BIZ_CODE['WRONG_CONNECTION']]
        return HttpResponse(json.dumps(ret))
    return HttpResponse(json.dumps(ret))